1.2.2 使用register_chrdev注册字符设备
注册字符设备可以使用register_chrdev函数。
- intregister_chrdev(unsignedintmajor,constchar*name,structfile_operations*fops);
register_chrdev函数的major参数如果等于0,则表示采用系统动态分配的主设备号。
注销字符设备可以使用unregister_chrdev函数。
- intunregister_chrdev(unsignedintmajor,constchar*name);
例1.3 register_chrdev注册字符设备实例
代码见光盘src1drivermodel1-3register_chrdev。核心代码如下所示:
- staticunsignedcharsimple_inc=0;
- staticunsignedchardemoBuffer[256];
- intsimple_open(structinode*inode,structfile*filp)
- {
- if(simple_inc>0)return-ERESTARTSYS;
- simple_inc++;
- return0;
- }
- intsimple_release(structinode*inode,structfile*filp)
- {
- simple_inc--;
- return0;
- }
- ssize_tsimple_read(structfile*filp,char__user*buf,size_tcount,loff_t*f_pos)
- {
- /*把数据复制到应用程序空间*/
- if(copy_to_user(buf,demoBuffer,count))
- {
- count=-EFAULT;
- }
- returncount;
- }
- ssize_tsimple_write(structfile*filp,constchar__user*buf,size_tcount,loff_t*f_pos)
- {
- /*把数据复制到内核空间*/
- if(copy_from_user(demoBuffer+*f_pos,buf,count))
- {
- count=-EFAULT;
- }
- returncount;
- }
- structfile_operationssimple_fops={
- .owner=THIS_MODULE,
- .read=simple_read,
- .write=simple_write,
- .open=simple_open,
- .release=simple_release,
- };
- /*******************************************************
- MODULEROUTINE
- *******************************************************/
- voidsimple_cleanup_module(void)
- {
- unregister_chrdev(simple_MAJOR,"simple");
- printk("simple_cleanup_module! ");
- }
- intsimple_init_module(void)
- {
- intret;
- //根据设备号与设备名注册字符设备
- ret=register_chrdev(simple_MAJOR,"simple",&simple_fops);
- if(ret<0)
- {
- printk("Unabletoregistercharacterdevice%d! ",simple_MAJOR);
- returnret;
- }
- return0;
- }
- module_init(simple_init_module);
- module_exit(simple_cleanup_module);
应用程序的代码如下:
- voidmain(void)
- {
- intfd;
- inti;
- chardata[256];
- intretval;
- fd=open("/dev/fgj",O_RDWR);
- if(fd==-1)
- {
- perror("erroropen ");
- exit(-1);
- }
- printf("open/dev/fgjsuccessfully ");
- //写数据
- retval=write(fd,"fgj",3);
- if(retval==-1)
- {
- perror("writeerror ");
- exit(-1);
- }
- //读数据
- retval=read(fd,data,3);
- if(retval==-1)
- {
- perror("readerror ");
- exit(-1);
- }
- data[retval]=0;
- printf("readsuccessfully:%s ",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