如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
利用udev、sys动态创建linux设备结点在Linux2.6内核中,devfs被认为是过时的方法,并最终被抛弃,udev取代了它。Devfs的一个很重要的特点就是可以动态创建设备结点。那我们现在如何通过udev和sys文件系统动态创建设备结点呢?下面通过一个实例,说明udev、sys动态创建设备结点的方法。注意代码中红色的部分是为了实现动态创建设备结点添加的。#include<linux/module.h>#include<linux/kernel.h>#include<linux/init.h>#include<linux/fs.h>#include<linux/cdev.h>#include<asm/uaccess.h>#include<linux/device.h>MODULE_LICENSE("GPL");inthello_major=252;inthello_minor=0;intnumber_of_devices=1;chardata[50]="foobarnotequaltobarfoo";structcdevcdev;dev_tdev=0;staticinthello_open(structinode*inode,structfile*file){printk(KERN_INFO"Hey!deviceopened\n");return0;}staticinthello_release(structinode*inode,structfile*file){printk(KERN_INFO"Hmmm...deviceclosed\n");return0;}ssize_thello_read(structfile*filp,char*buff,size_tcount,loff_t*offp){ssize_tresult=0;if(copy_to_user(buff,data,sizeof(data)-1))result=-EFAULT;elseprintk(KERN_INFO"wrote%dbytes\n",count);returnresult;}ssize_thello_write(structfile*filp,constchar*buf,size_tcount,loff_t*f_pos){ssize_tret=0;printk(KERN_INFO"Writing%dbytes\n",count);if(count>127)return-ENOMEM;if(count<0)return-EINVAL;if(copy_from_user(data,buf,count)){ret=-EFAULT;}else{data[127]='\0';printk(KERN_INFO"Received:%s\n",data);ret=count;}returnret;}structfile_operationshello_fops={.wner=THIS_MODULE,.pen=hello_open,.release=hello_release,.read=hello_read,.write=hello_write};structclass*my_class;staticvoidchar_reg_setup_cdev(void){interror,devno=MKDEV(hello_major,hello_minor);cdev_init(&cdev,&hello_fops);cdev.owner=THIS_MODULE;cdev.ops=&hello_fops;error=cdev_add(&cdev,devno,1);if(error)printk(KERN_NOTICE"Error%daddingchar_reg_setup_cdev",error);/*creatingyourownclass*/my_class=class_create(THIS_MODULE,"farsight_class");//addbylhtif(IS_ERR(my_class)){printk("Err:failedincreatingclass.\n");return;}/*registeryourowndeviceinsysfs,andthiswillcauseudevdtocreatecorrespondingdevicenode*/class_device_create(my_class,NULL,devno,NULL,"farsight_dev");//device_creat