Hello World.c
#include <linux/module.h> //模块的相关头文件
#include <linux/init.h> //初始化的相关头文件
#include <linux/miscdevice.h> //杂项设备驱动和相关头文件
#include <linux/fs.h> //文件操作集合
#include <linux/uaccess.h>
ssize_t hd_fops_read (struct file *file, char __user *ubuf, size_t size, loff_t *loff_t){
char kbuf[64] = "Hello Word";
printk("Hello hd_fops_read\n");
if( copy_to_user(ubuf,kbuf,strlen(kbuf)) != 0 ){
printk("hd_fops_release error\n");
return 0;
}
return 0;
}
ssize_t hd_fops_write (struct file *file, const char __user *ubuf, size_t size, loff_t *loff_t){
char kbuf[64] = {0};
printk("Hello hd_fops_write\n");
if( copy_from_user(kbuf,ubuf,size) != 0 ){
printk("hd_fops_write error\n");
return 0;
}
printk("hd_fops_write urse is %s\n",kbuf);
return 0;
}
int hd_fops_open (struct inode *inode, struct file *file){
printk("Hello hd_fops_open\n");
return 0;
}
int hd_fops_release (struct inode *inode, struct file *file){
printk("Hello hd_fops_release\n");
return 0;
}
struct file_operations hd_fops={//文件操作集合
.owner = THIS_MODULE,
.read = hd_fops_read,
.write = hd_fops_write,
.open = hd_fops_open,
.release = hd_fops_release,
};
struct miscdevice hd_misc={ //杂项设备结构体
.minor = MISC_DYNAMIC_MINOR, //此设备号
.name = "zcy", //在dev下生成的设备节点
.fops = &hd_fops,
};
static int helloword_init(void){
int ret = 0;
ret = misc_register(&hd_misc);//注册杂项设备
if( ret < 0 ){
printk("misc_register error!!!\n");
return 0;
}
printk("Hello Word!!!\n");
return 0;
}
static void helloword_exit(void){
misc_deregister(&hd_misc);//注销杂项设备驱动
printk("Bye!!!\n");
}
module_init(helloword_init);
module_exit(helloword_exit);
MODULE_LICENSE("GPL");
APP.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int fd;
char buf[64] = {0};
char writebuf[64]="123456";
fd = open("/dev/zcy",O_RDWR);
if(fd < 0)
{
perror("open error\n");
return fd;
}
read(fd,buf,sizeof(buf));
printf("read buf is %s\n",buf);
write(fd,writebuf,sizeof(writebuf));
close(fd);
return 0;
}