- #include <linux/module.h>
- #include <linux/init.h>
- #include <linux/fs.h>
- #include <asm/uaccess.h>
- MODULE_LICENSE("GPL");// 设置这个模块的协议为 GPL
- #define MAJOR_NUM 2918 //主设备号
- //声明Read函数
- static ssize_t device_read(struct file *, char *, size_t, loff_t*);
- //声明Write函数
- static ssize_t device_write(struct file *, const char *, size_t, loff_t*);
- //初始化字符设备驱动的file_operations结构体
- struct file_operations device_fops =
- {
- .read=device_read,
- .write=device_write,
- };
- static int device_var = 0; //"globalvar"设备的全局变量
- static int __init device_init(void)
- {
- int ret;
- //注册设备驱动
- ret = register_chrdev(MAJOR_NUM, "device", &device_fops);
- if (ret)
- {
- printk("device register failure");
- }
- else
- {
- printk("device register success");
- }
- return ret;
- }
- static void __exit device_exit(void)
- {
- int ret = 0;
- //注销设备驱动
- unregister_chrdev(MAJOR_NUM, "device");
- if (ret)
- {
- printk("device unregister failure");
- }
- else
- {
- printk("device unregister success");
- }
- }
- //READ
- static ssize_t device_read(struct file *filp, char *buf, size_t len, loff_t *off)
- {
- //将device_var从内核空间复制到用户空间
- if (copy_to_user(buf, &device_var, sizeof(int)))
- {
- return - EFAULT;
- }
- return sizeof(int);
- }
- static ssize_t device_write(struct file *filp, const char *buf, size_t len, loff_t *off)
- {
- //将用户空间的数据复制到内核空间的device_var
- if (copy_from_user(&device_var, buf, sizeof(int)))
- {
- return - EFAULT;
- }
- return sizeof(int);
- }
- module_init(device_init);
- module_exit(device_exit);
编译为模块:
命令为:make -C /lib/modules/3.0.0-7-generic/build M(等号)/home/shi/c_dev/modules
Makefile为
- # From《Linux Device Drivers》3rd Edition
- # Makefile
- ifneq ($(KERNELRELEASE),)
- # call from kernel build system
- obj-m := device.o
- else
- KERNELDIR ?= /lib/modules/$(shell uname -r)/build
- PWD := $(shell pwd)
- default:
- $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
- endif
完成之后,讲模块加入到内核中去
sudo insmod ./device.ko
查看所有模块
lsmod
删除模块
sudo rmmod ./device.ko
测试程序
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <stdio.h>
- #include <fcntl.h>
- main()
- {
- int fd,num;
- //打开"/dev/device"
- fd = open("/dev/device", O_RDWR, S_IRUSR | S_IWUSR);
- if (fd != 0)
- {
- //初次读device
- read(fd, &num, sizeof(int));
- printf("The device is %d\n", num);
- //写device
- printf("Please input the num written to device\n");
- scanf("%d", &num);
- write(fd, &num, sizeof(int));
- //再次读device
- read(fd, &num, sizeof(int));
- printf("The device is %d\n", num);
- //关闭"/dev/device"
- close(fd);
- }
- else
- {
- printf("Device open failure\n");
- }
- }
运行结果
shi@smkoo:~/c_dev$ ./test
The device is 134514219
Please input the num written to device
1
The device is 1