[TOC]
由于没有经过完整测试代码中可能会有不足指出,如有网友发现还请斧正
[邮箱] liulf_pc@126.com
CSDN
仓库地址
该文当使用Typora markdown 编辑,使用Typora查看效果更好
linux驱动学习记录
这是一个学文档,所有代码仅供学习使用,请勿在生产环境中使用
字符驱动
字符驱动简介
字符驱动是linux驱动学习的第一站,该代码完成了一个最简单的字符驱动以及一个最小化打测试代码
代码示例
应用测试代码
代码仅做了open的测试
int main (int argc, char *argv[])
{
int fd = -1;
fd = open("/dev/chartest1",O_RDWR);
if(-1 == fd ){
printf("open file error\n");
return -1;
}
printf("open file success\n");
if(fd != -1){
printf("close file\n");
close(fd);
fd = -1;
}
return EXIT_SUCCESS;
}
驱动代码
下面打代码只做示例,具体代码请参考代码文件char_driver.c
static dev_t major = -1;
static int const devcnt = 1;
struct cdev cdev;
struct device *char_dev = NULL;
static struct class *chartest_class;
/*定义一个 file_operations 结构体*/
static const struct file_operations chardev_dev_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = chardev_dev_read,
.write = chardev_dev_write,
.unlocked_ioctl = chardev_dev_ioctl,
.open = chardev_dev_open,
.release = chardev_dev_release,
};
static int hello_init(void)
{
unsigned int err;
cdev_init(&cdev, &chardev_dev_fops); /*初始化字符驱动*/
err = alloc_chrdev_region(&major, 0, devcnt , "unused"); /*动态申请设备号*/
err = cdev_add(&cdev, major, 1);/*将设备注册到系统中*/
chartest_class = class_create(THIS_MODULE, "testclass"); /*创建设备文件:先创建一个class然后在class下创建一个设备文件*/
char_dev = device_create(chartest_class, NULL, major, NULL, "%s%d", "chartest", 1);
return 0;
}
static void hello_exit(void)
{
device_destroy(chartest_class, major);
class_destroy(chartest_class);
unregister_chrdev(major, "test");
major = -1;
cdev_del(&cdev);
printk(KERN_INFO "%s\n",__func__);
}
module_init(hello_init);
module_exit(hello_exit);