编写一个Linux字符驱动demo
时间: 2024-01-20 11:04:30 浏览: 76
以下是一个简单的Linux字符驱动示例代码,实现了一个名为mychar的字符设备驱动:
```c
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/cdev.h>
#define DEVICE_NAME "mychar"
#define BUF_LEN 80
static int Major;
static char msg[BUF_LEN];
static int msg_len;
static struct cdev mychar_cdev;
static int mychar_open(struct inode *inode, struct file *file)
{
printk(KERN_INFO "mychar: Device opened.\n");
return 0;
}
static int mychar_release(struct inode *inode, struct file *file)
{
printk(KERN_INFO "mychar: Device closed.\n");
return 0;
}
static ssize_t mychar_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
int len = msg_len;
if (len > count)
len = count;
if (len == 0)
return 0;
if (copy_to_user(buf, msg, len))
return -EFAULT;
*f_pos += len;
return len;
}
static ssize_t mychar_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos)
{
if (count > BUF_LEN)
count = BUF_LEN;
if (copy_from_user(msg, buf, count))
return -EFAULT;
msg_len = count;
return count;
}
static struct file_operations mychar_fops = {
.owner = THIS_MODULE,
.open = mychar_open,
.release = mychar_release,
.read = mychar_read,
.write = mychar_write,
};
static int __init mychar_init(void)
{
int err;
dev_t dev;
printk(KERN_INFO "mychar: Initializing.\n");
err = alloc_chrdev_region(&dev, 0, 1, DEVICE_NAME);
if (err < 0) {
printk(KERN_ERR "mychar: Failed to allocate chrdev region.\n");
return err;
}
Major = MAJOR(dev);
cdev_init(&mychar_cdev, &mychar_fops);
mychar_cdev.owner = THIS_MODULE;
err = cdev_add(&mychar_cdev, dev, 1);
if (err < 0) {
printk(KERN_ERR "mychar: Failed to add cdev.\n");
unregister_chrdev_region(dev, 1);
return err;
}
return 0;
}
static void __exit mychar_exit(void)
{
dev_t dev = MKDEV(Major, 0);
printk(KERN_INFO "mychar: Exiting.\n");
cdev_del(&mychar_cdev);
unregister_chrdev_region(dev, 1);
}
module_init(mychar_init);
module_exit(mychar_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple character device driver");
```
该驱动实现了一个字符设备,可以通过读写操作来对msg变量进行读写。在驱动初始化时,使用alloc_chrdev_region函数分配设备号,然后通过cdev_init和cdev_add函数将驱动添加到系统中。在read和write函数中,通过copy_to_user和copy_from_user函数来进行用户态数据与内核态数据之间的拷贝。在驱动退出时,使用cdev_del和unregister_chrdev_region函数来删除驱动和释放设备号。
阅读全文