實現一個可以open和close的簡單字元驅動,並通過測試app驗證驅動驅動原始碼(cdev_demo.c)
#include <linux/init.h>#include <linux/module.h>#include <linux/cdev.h>#include <linux/fs.h>#define BASE_MINOR\t(0)#define COUNT\t\t(3)#define DRIVER_NAME\t"cdev demo"dev_t devno;struct cdev *cdevp = NULL; int cdev_open(struct inode *inode, struct file *filp);int cdev_release(struct inode *inode, struct file *filp);struct file_operations fops = {\t.owner = THIS_MODULE,\t.open = cdev_open,\t.release = cdev_release,};//應用程式open函式int cdev_open(struct inode *inode, struct file *filp){\tprintk("cdev demo open!\\r\\n");\treturn 0;}//應用程式close函式int cdev_release(struct inode *inode, struct file *filp){\tprintk("cdev demo release!\\r\\n");\treturn 0;}int cdev_demo_init(void){\tint ret;\t//1.alloc dev_t \tret = alloc_chrdev_region(&devno, BASE_MINOR, COUNT, DRIVER_NAME);\tif (0 != ret)\t{\t\tgoto err1;\t}\t//2.alloc cdev\tcdevp = cdev_alloc();\t\tif (NULL == cdevp)\t{\t\tret = -ENOMEM;\t\tgoto err2;\t}\t//3.init cdev\tcdev_init(cdevp, &fops);\t//4.add cdev into kernel\tret = cdev_add(cdevp, devno, COUNT);\tif (0 != ret)\t{\t\tgoto err2;\t}\tprintk("cdev driver init: %s, %s\\r\\n", __FILE__, __func__);\treturn 0;err2:\tunregister_chrdev_region(devno, COUNT);err1:\treturn ret;}void cdev_demo_exit(void){\t//1.delete cdev\tcdev_del(cdevp);\t//2.free dev_t\tunregister_chrdev_region(devno, COUNT);\t\tprintk("cdev driver exit: %s, %s\\r\\n", __FILE__, __func__);}module_init(cdev_demo_init);module_exit(cdev_demo_exit);MODULE_LICENSE("GPL");
Makefile(Makefile)KERNEL_DIR := /lib/modules/$(shell uname -r)/buildMODULE_DIR := $(shell pwd)obj-m:=cdev_demo.oall:\tmake -C $(KERNEL_DIR) M=$(MODULE_DIR) modulesclean:\tmake -C $(KERNEL_DIR) M=$(MODULE_DIR) clean
測試檔案原始碼(cdev_app.c)
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdio.h> void main(){\tint fd; \tfd = open("/dev/cdev_demo",O_RDWR);\tif(fd<0)\t{\t\tperror("open fail \\n");\t\treturn ;\t}\tprintf("cdev open succ\\r\\n"); \tclose(fd);}
測試方法:編譯驅動 - make 生成 cdev_demo.ko載入驅動 - sudo insmod cdev_demo.ko檢視驅動裝置號 - cat /proc/devices (找到cdev_demo,記下前面的數字即主裝置號建立裝置檔案 - sudo mknod /dev/cdev_demo c 主裝置號 0編譯應用檔案 - gcc cdev_app.c執行測試檔案 - sudo ./a.out檢視log - dmesg
最新評論