Introduction
我们今天编写第一个Linux Kernel Module的驱动程序:一个字符型设备驱动。通过简单的open(), release(), read(), write(),你将理解驱动程序的编程方法。
file_operations结构
在Linux中,一切都是文件,设备驱动也毫不例外。文件的定义在linux/fs.h中,目前我们只需要关注file_operations结构。1
2
3
4
5
6
7
8struct file_operations {
...
ssize_t(*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t(*write) (struct file *, const char __user *, size_t, loff_t *);
int (*open) (struct inode *, struct file *);
int (*release) (struct inode *, struct file *);
...
};
上面四个回调函数,是我们目前需要关心的,后面的例子也只会使用这四个回调函数。
编写我们自己的设备驱动程序,需要根据需求实现file_operations结构中的回调函数,然后将驱动通过register_chrdev()注册到内核中即可。
完整的字符驱动code
1 |
|
编译运行
Makefile同之前的一样就好
$ make
$ sudo insmod csprojectedu.ko
$ dmesg
[115465.083271] 'mknod /dev/csprojectedu c 250 0'.
$ sudo mknod /dev/csprojectedu c 250 0
$ cat /dev/csprojectedu
Device open for 1 times.
$ cat /dev/csprojectedu
Device open for 2 times.
$ sudo rm /dev/csprojectedu
$ sudo rmmod csprojectedu.ko
Summary
通过编写一个简单的字符型设备驱动,我们了解了Linux Kernel Module在驱动程序方面的应用。
(本文出自csprojectedu.com,转载请注明出处)