TA的每日心情 | 奋斗 2022-9-16 05:52 |
---|
签到天数: 1368 天 连续签到: 1 天 [LV.10]以坛为家III
|
没什么好说的,把驱动程序精简到最小,得到这个框架,以后往这个框架里填东西就行了。
后面把Makefile格式和测试程序的框架也发出来。
里面的一些变量命名之类的没有按照代码规范书写,自己看着舒服就行了。
- 1.驱动程序框架:xxx.c
- #include <linux/init.h>
- #include <linux/module.h>
- #include <linux/fs.h>
- #include <linux/cdev.h>
- #include <linux/device.h>
- #include <asm/io.h>
- #include <asm/uaccess.h>
- //用户程序接口部分
- int XXX_open(struct inode* n, struct file* f)
- {
- printk("Open Finished!\n"); return 0;
- }
- int XXX_close(struct inode* n, struct file* f)
- {
- printk("Close Finished!\n");
- return 0;
- }
- ssize_t XXX_write(struct file* f, const char __user* buf, size_t len, loff_t* l)
- {
- printk("Write Finished!\n");
- return len;
- }
- ssize_t XXX_read(struct file* f, char __user* buf, size_t len, loff_t* l)
- {
- printk("Read Finished!\n");
- return 0;
- }
- //操作系统接口部分
- #define DEV_NAME "XXX"
- #define DEV_COUNT 1
- static struct class* pClass;
- int major;
- static struct file_operations fops =
- {
- .owner = THIS_MODULE,
- .open = XXX_open,
- .write = XXX_write,
- .read = XXX_read,
- .release = XXX_close,
- };
- static int __init XXX_init(void)
- {
- major = register_chrdev(0, DEV_NAME, &fops);
- pClass = class_create(THIS_MODULE, DEV_NAME);
- if (pClass == NULL)
- {
- unregister_chrdev(major, DEV_NAME);
- return -1;
- }
- device_create(pClass, NULL, MKDEV(major, 0), NULL, DEV_NAME);
- printk("Init Finished!\n");
- return 0;
- }
- static void __exit XXX_exit(void)
- {
- unregister_chrdev(major, DEV_NAME);
- if (pClass)
- {
- device_destroy(pClass, MKDEV(major, 0));
- class_destroy(pClass);
- }
- printk("Exit Finished!\n");
- }
- MODULE_LICENSE("GPL");
- MODULE_AUTHOR("LiuYang");
- module_init(XXX_init);
- module_exit(XXX_exit);
- //代码结束
复制代码
2.Makefile框架:
- ifneq ($(KERNELRELEASE),)
- obj-m :=XXX.o
- else
- KDIR := /usr/src/linux-headers-3.4.29+
- all:
- make -C $(KDIR) M=$(PWD) modules
- clean:
- make -C $(KDIR) M=$(PWD) clean
- endif
复制代码
可以正常的编译,添加和卸载驱动,并且用户程序可以调用
insmod XXX.ko
rmmod XXX
dmesg | tail -10
3.用户程序框架:
- int main(int argc, char **argv)
- {
- int f;
- unsigned char Buf[2];
- f = open("/dev/XXX", O_RDWR);
- write(f, &Buf, 2);
- read(f, &Buf, 2);
- close(f);
- return 0;
- }
|
|