使用register_chrdev注册字符设备
1.2.2 使用register_chrdev注册字符设备
注册字符设备可以使用register_chrdev函数。
- int register_chrdev (unsigned int major, const char *name, struct file_operations*fops);
register_chrdev函数的major参数如果等于0,则表示采用系统动态分配的主设备号。
注销字符设备可以使用unregister_chrdev函数。
- int unregister_chrdev(unsigned int major, const char *name);
例1.3 register_chrdev注册字符设备实例
代码见光盘\src\1drivermodel\1-3register_chrdev。核心代码如下所示:
- static unsigned char simple_inc=0;
- static unsigned char demoBuffer[256];
- int simple_open(struct inode *inode, struct file *filp)
- {
- if(simple_inc>0)return -ERESTARTSYS;
- simple_inc++;
- return 0;
- }
- int simple_release(struct inode *inode, struct file *filp)
- {
- simple_inc--;
- return 0;
- }
- ssize_t simple_read(struct file *filp, char __user *buf, size_t count,loff_t *f_pos)
- {
- /* 把数据复制到应用程序空间 */
- if (copy_to_user(buf,demoBuffer,count))
- {
- count=-EFAULT;
- }
- return count;
- }
- ssize_t simple_write(struct file *filp, const char __user *buf, size_t count,loff_t *f_pos)
- {
- /* 把数据复制到内核空间 */
- if (copy_from_user(demoBuffer+*f_pos, buf, count))
- {
- count = -EFAULT;
- }
- return count;
- }
- struct file_operations simple_fops = {
- .owner = THIS_MODULE,
- .read = simple_read,
- .write = simple_write,
- .open = simple_open,
- .release = simple_release,
- };
- /*******************************************************
- MODULE ROUTINE
- *******************************************************/
- void simple_cleanup_module(void)
- {
- unregister_chrdev(simple_MAJOR, "simple");
- printk("simple_cleanup_module!\n");
- }
- int simple_init_module(void)
- {
- int ret;
- //根据设备号与设备名注册字符设备
- ret = register_chrdev(simple_MAJOR, "simple", &simple_fops);
- if (ret < 0)
- {
- printk("Unable to register character device %d!\n",simple_MAJOR);
- return ret;
- }
- return 0;
- }
- module_init(simple_init_module);
- module_exit(simple_cleanup_module);
应用程序的代码如下:
- void main(void)
- {
- int fd;
- int i;
- char data[256];
- int retval;
- fd=open("/dev/fgj",O_RDWR);
- if(fd==-1)
- {
- perror("error open\n");
- exit(-1);
- }
- printf("open /dev/fgj successfully\n");
- //写数据
- retval=write(fd,"fgj",3);
- if(retval==-1)
- {
- perror("write error\n");
- exit(-1);
- }
- //读数据
- retval=read(fd,data,3);
- if(retval==-1)
- {
- perror("read error\n");
- exit(-1);
- }
- data[retval]=0;
- printf("read successfully:%s\n",data);
- //关闭设备
- close(fd);
- }
【使用register_chrdev(LED_MAJOR,DEVICE_NAME,&dev_fops)注册字符设备驱动程序时都要手动建立节点 ,否则在应用程序无法打开该设备】
字符设备模块使用insmod加载,加载完毕需要在/dev目录下使用mkmod命令建立相应的文件结点,编译生成的应用层可执行程序为test。本例运行结果如下:
[root@/home]#insmod demo.ko [root@urbetter /home]# mknod /dev/fgj c 224 0 [root@urbetter /home]# ./test open /dev/fgj successfully read successfully:fgj
作者:柒月
Q群 :2122210(嵌入式/机器学习)