写一个Linux内核驱动
时间: 2023-11-30 11:06:24 浏览: 136
给自己的Linux写驱动
写一个Linux内核驱动需要掌握C语言、Linux内核编程和设备驱动编程的知识。
下面以编写一个简单的字符设备驱动为例:
1. 首先创建一个新的目录,用于存放驱动程序的源代码和Makefile文件。
```
mkdir mychardev
```
2. 在该目录下创建一个C源文件并定义一个字符设备驱动模块。
```c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#define DEVICE_NAME "mychardev" // 设备名称
static int major_num; // 设备号
// 打开设备
static int mychardev_open(struct inode *inode, struct file *filp)
{
printk(KERN_ALERT "mychardev: Device has been opened.\n");
return 0;
}
// 释放设备
static int mychardev_release(struct inode *inode, struct file *filp)
{
printk(KERN_ALERT "mychardev: Device has been released.\n");
return 0;
}
// 读取设备
static ssize_t mychardev_read(struct file *filp, char __user *buf, size_t count, loff_t *offset)
{
printk(KERN_ALERT "mychardev: Device has been read.\n");
return 0;
}
// 写入设备
static ssize_t mychardev_write(struct file *filp, const char __user *buf, size_t count, loff_t *offset)
{
printk(KERN_ALERT "mychardev: Device has been written.\n");
return count;
}
// 设备操作集合
static struct file_operations mychardev_fops = {
.owner = THIS_MODULE,
.open = mychardev_open,
.release = mychardev_release,
.read = mychardev_read,
.write = mychardev_write,
};
// 初始化驱动
static int __init mychardev_init(void)
{
printk(KERN_ALERT "mychardev: Initializing device driver.\n");
// 注册字符设备驱动
major_num = register_chrdev(0, DEVICE_NAME, &mychardev_fops);
if (major_num < 0) {
printk(KERN_ALERT "mychardev: Failed to register device driver.\n");
return major_num;
}
printk(KERN_ALERT "mychardev: Device driver registered successfully with major number %d.\n", major_num);
return 0;
}
// 卸载驱动
static void __exit mychardev_exit(void)
{
printk(KERN_ALERT "mychardev: Unregistering device driver.\n");
// 注销字符设备驱动
unregister_chrdev(major_num, DEVICE_NAME);
printk(KERN_ALERT "mychardev: Device driver unregistered successfully.\n");
}
module_init(mychardev_init);
module_exit(mychardev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple character device driver.");
```
3. 在该目录下创建一个Makefile文件。
```
obj-m += mychardev.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
```
4. 编译驱动程序。
```
make
```
5. 加载驱动程序。
```
sudo insmod mychardev.ko
```
6. 检查设备是否被正确注册。
```
cat /proc/devices
```
输出应类似于:
```
Character devices:
1 mem
4 /dev/vc/0
4 tty
4 ttyS
5 /dev/tty
5 /dev/console
5 /dev/ptmx
10 misc
13 input
29 fb
89 i2c
116 alsa
128 ptm
136 pts
180 usb
188 ttyUSB
189 usb_device
226 drm
251 mychardev
```
7. 测试设备。
```
sudo chmod 666 /dev/mychardev
echo "Hello, world!" > /dev/mychardev
cat /dev/mychardev
```
输出应类似于:
```
mychardev: Device has been written.
mychardev: Device has been read.
Hello, world!
```
阅读全文