Writing a file in /proc continuouly floods the dmesg
我正在尝试使用/ proc文件输入工具在Linux内核模块中读取/写入变量。
内核模块编译成功,但是尝试通过
编写
1 | echo 1 > My_file |
此操作未完成。
此外,dmesg控制台会不断充斥一些随机值。
1 2 3 4 5 | [ 1171.481231] proc_write_flag New_Flag 1124646486 [ 1171.481245] proc_write_flag New_Flag 1124646486 [ 1171.481259] proc_write_flag New_Flag 1124646486 [ 1171.481271] proc_write_flag New_Flag 1124646486 [ 1171.481473] ^C |
我是linux设备驱动程序的新手,正在尝试使用linux内核提供的
是什么原因导致这种现象,我该如何纠正?
这是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | int my_flag; static struct proc_dir_entry *pdir = NULL; MODULE_LICENSE("GPL"); MODULE_AUTHOR("GPL"); static ssize_t proc_read_flag(struct file* page,char __user * data, size_t count, loff_t *offset); static ssize_t proc_write_flag(struct file *file, const char __user* ubuf, size_t count, loff_t* offset); static struct file_operations myops = { .owner = THIS_MODULE, .read = proc_read_flag, .write= proc_write_flag, }; //ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); //Updated Read function after the reply. static ssize_t proc_read_flag(struct file* page,char __user * data, size_t count,loff_t *offset) { int ret; if( count >my_flag) //my_flag holds the count of chars received by write function. count = my_flag; ret = copy_to_user(data, my_buf, my_flag ); printk("%s: ret = %d ,my_flag %d\ ",__FUNCTION__, ret, my_flag); return ( my_flag - ret ); } //ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); //Updated Write function After the reply. static ssize_t proc_write_flag(struct file *file, const char __user* ubuf, size_t count, loff_t* offset) { if( copy_from_user(my_buf,ubuf,count) ){ //Returns No. of bytes could not copy return -EFAULT; } my_flag = count; printk("%s New_Flag %d Data: %s\ ",__FUNCTION__,my_flag,my_buf); return count; } int init_module(void) { struct proc_dir_entry *pfile = NULL; pdir = proc_mkdir("My_dir",NULL); if(!pdir){ return -ENOMEM; } pfile = proc_create("My_file", 0666, pdir, &myops); if(!pfile) return -ENOMEM; printk("Proc_entry Created Successfully, Module initialized\ "); return 0; } void cleanup_function(void) { remove_proc_entry("My_file", pdir); remove_proc_entry("My_dir", NULL); printk("Removing Proc_entry!!!"); } |
write函数应返回您处理的字节数。
在您的情况下,\\'proc_write_flag \\'函数返回的\\'ret \\'为0。
这意味着它将被重复调用,直到您从\\'ubuf \\'
处理\\'count \\'个字节数为止
类似地,\\'proc_read_flag \\'应该返回您写入\\'data \\'的字节数。在您的情况下,它返回0(len)
\\'proc_write_flag \\'函数中还有其他问题。
\\'buf \\'数组未初始化,并且将\\'buf \\'(地址)强制转换为int不会给您预期的答案。
从此http://tuxthink.blogspot.com/2013/12/creating-directory-under-proc-in-kernel.html
开始
然后查??看kstrtol()函数。