- 论坛徽章:
- 0
|
看一个我以前写的简单的字符设备的程序的部分代码
- static int hello_open (struct inode *inode, struct file *filp)
- {
- return 0;
- }
- static int hello_release (struct inode *inode, struct file *filp)
- {
- return 0;
- }
- static ssize_t hello_read (struct file *filp, char __user *buf,
- size_t count, loff_t *pos)
- {
- int size = count < MAXBUF ? count : MAXBUF;
- printk("hello: Read Hello World !\n");
- if (copy_to_user(buf, hello_buf, size))
- return -ENOMEM;
- return size;
- }
- static ssize_t hello_write (struct file *filp, const char __user *buf,
- size_t count, loff_t *pos)
- {
- int size = count < MAXBUF ? count : MAXBUF;
- printk("hello: Write Hello World !\n");
- memset(hello_buf, 0, sizeof(hello_buf));
- if (copy_from_user(hello_buf, buf, size))
- return -ENOMEM;
- return size;
- }
- static struct file_operations hello_fops = {
- .read = hello_read,
- .write = hello_write,
- .open = hello_open,
- .release = hello_release,
- };
- static struct cdev *hello_cdev;
- static int __init hello_init(void)
- {
- dev_t dev;
- int error;
- error = alloc_chrdev_region(&dev, 0, 2, "hello");
- if (error)
- {
- printk("hello: alloc_chardev_region failed!\n");
- return error;
- }
- hello_cdev = cdev_alloc();
- if (hello_cdev == NULL)
- {
- printk("hello: alloc cdev failed!\n");
- unregister_chrdev_region(hello_cdev->dev, 2);
- return -ENOMEM;
- }
- hello_cdev->ops = &hello_fops;
- hello_cdev->owner = THIS_MODULE;
- }
复制代码
这里就初始化了一个file_operations,其实类似系统启动的时候也必须初始化一个关于文件的open write read lseek(这些)等的底层到底是怎么完成的
也就是上面的
static struct file_operations hello_fops = {
.read = hello_read,
.write = hello_write,
.open = hello_open,
.release = hello_release,
};
因为对于linux任何东西都是文件,所以不管是文件系统 还是字符设备 块设备等都要初始话这么一个file_operations |
|