作者: Austria 出自: http://www.linuxdiyf.com
在Linux 2.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");
int hello_major = 252;
int hello_minor = 0;
int number_of_devices = 1;
char data[50]="foobar not equal to barfoo";
struct cdev cdev;
dev_t dev = 0;
static int hello_open (struct inode *inode, struct file *file)
{
printk (KERN_INFO "Hey! device opened\n");
return 0;
}
static int hello_release (struct inode *inode, struct file *file)
{
printk (KERN_INFO "Hmmm... device closed\n");
return 0;
}
ssize_t hello_read (struct file *filp, char *buff, size_t count, loff_t *offp)
{
ssize_t result = 0;
if (copy_to_user (buff, data, sizeof(data)-1))
result = -EFAULT;
else
printk (KERN_INFO "wrote %d bytes\n", count);
return result;
}
ssize_t hello_write (struct file *filp, const char *buf, size_t count, loff_t *f_pos)
{
ssize_t ret = 0;
printk (KERN_INFO "Writing %d bytes\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;
}
return ret;
}
struct file_operations hello_fops = {
.owner = THIS_MODULE,
.open = hello_open,
.release = hello_release,
.read = hello_read,
.write = hello_write
};
struct >static void char_reg_setup_cdev (void)
{
int error, 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 %d adding char_reg_setup_cdev", error);
/* creating your own >my_>if(IS_ERR(my_>printk("Err: failed in creating >return ;
}
/* register your own device in sysfs, and this will cause udevd to create corresponding device node */
>// device_create(my_>}
static int __init hello_2_init (void)
{
int result;
dev = MKDEV (hello_major, hello_minor);
result = register_chrdev_region (dev, number_of_devices, "test");
if (result<0) {
printk (KERN_WARNING "hello: can't get major number %d\n", hello_major);
return result;
}
char_reg_setup_cdev ();
printk (KERN_INFO "char device registered\n");
return 0;
}
static void __exit hello_2_exit (void)
{
dev_t devno = MKDEV (hello_major, hello_minor);
cdev_del (&cdev);
unregister_chrdev_region (devno, number_of_devices);
>>}
module_init (hello_2_init);
module_exit (hello_2_exit);v
在编译了驱动后,可以检察/dev/farsight_dev装备结点,和 /sys/>
本代码的测试情形是Ubantu7.04,内核版本是2.6.20-15-generi。在分譬喻版本的内核中,有些琐细函数的参数可以不太一样。
版权声明: 原创作品,核准转载,转载时请务必以超链接形式标明文章 原始情由 、作者信息和本声明。否则将追究法令责任。