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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| /** /proc创建文件示例 */ #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/uaccess.h> #define MY_VERSION "foo" static int ver = 0; // 写入到proc目录指定文件 static int my_version_proc_show(struct seq_file *m, void *v) { seq_printf(m, "%s %d\n",MY_VERSION, ver); return 0; } static int my_version_proc_open(struct inode *inode, struct file *file) { return single_open(file, my_version_proc_show, NULL); } static ssize_t my_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_ops) { // 简单数字形式,只能0~9 #if 1 unsigned char tmp = 0; int value = 0; get_user(tmp, buf); value = simple_strtol(&tmp, NULL, 10); printk(KERN_ERR "got user info: %d....\n", value); ver = value; return count; #else unsigned char buffer[32] = {0}; int value = 0; if (copy_from_user(buffer, buf, (count > 32 ? 32: count))) goto out; // 如果只是输入简单的数字,可以:get_user(foo, buf); value = simple_strtol(buffer, NULL, 10); printk(KERN_ERR "got user info: %d....\n", value); ver = value; out: return count; #endif } static const struct file_operations my_debug_proc_fops = { .open = my_version_proc_open, .read = seq_read, .write = my_write, .llseek = seq_lseek, .release = single_release, }; static struct proc_dir_entry* my_proc_entry = NULL; void create_debugproc(void) { if (!my_proc_entry) { my_proc_entry = proc_create("myversion4", 0, NULL, &my_debug_proc_fops); // 在/proc目录下创建 } } void delete_debugproc(void) { if (my_proc_entry) proc_remove(my_proc_entry); } ///////////////////////////////////////////////// static int __init procfs_init(void) { printk(KERN_ERR "in %s\n", __func__); create_debugproc(); create_debugproc(); // note:多次调用,但该函数已经确保只注册一次 return 0; } static void __exit procfs_exit(void) { printk(KERN_ERR "in %s\n", __func__); delete_debugproc(); } module_init(procfs_init); module_exit(procfs_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("proc fs entry test driver by Late Lee");
|