- #include <linux/module.h>
- #include <linux/init.h>
- #include <linux/fs.h>
- #include <asm/uaccess.h>
- #include <linux/syscalls.h>
- MODULE_LICENSE("GPL");
- #define MAJOR_NUM 100
- int g_val;
- static ssize_t global_read(struct file *filp, char __user *buf, size_t len, loff_t *off)
- {
- int ret;
- char val[20];
- printk(KERN_ERR "###### global_read \n");
- sprintf(val, "%d\n", g_val);
- ret = simple_read_from_buffer(buf, len, off, val, strlen(val));
- return ret;
- }
- static ssize_t global_write(struct file *filp, const char __user *buf, size_t len, loff_t *off)
- {
- int ret, temp;
- char val[20];
- //simple_write_to_buffer(void *to, size_t available, loff_t *ppos,const void __user *from, size_t count);
- ret = simple_write_to_buffer(val, strlen(val), off, buf, len);
- sscanf(val, "%d", &temp);
- g_val = temp;
- return ret;
- }
- struct file_operations fileops = {
- .read = global_read,
- .write = global_write,
- };
- static int __init globalvar_init(void)
- {
- int reg;
- g_val = 0;
- printk(KERN_ERR "golabvar_init \n");
- reg = register_chrdev(MAJOR_NUM, "globalvar", &fileops);
- if(reg)
- {
- printk(KERN_ERR "register_chrdev fail \n");
- }
- else
- {
- printk(KERN_ERR "register_chrdev sucess \n");
- }
- sys_mknodat(AT_FDCWD, "/dev/xxx", O_RDWR | O_CREAT, 100);
- return 0;
- }
- static void __exit globalvar_exit(void)
- {
- printk("golabvar_exit \n");
- unregister_chrdev(MAJOR_NUM, "globalvar");
- }
- module_init(globalvar_init);
- module_exit(globalvar_exit);
一个简单的字符驱动
最新推荐文章于 2022-12-31 15:07:48 发布