1 #include <linux/module.h> 2 #include <linux/types.h> 3 #include <linux/kernel.h> 4 #include <linux/init.h> 5 #include <linux/random.h> 6 #include <linux/slab.h> 7 #include <linux/proc_fs.h> 8 #include <linux/seq_file.h> 9 #include <linux/list.h> 10 11 struct mylist_random { 12 struct list_head list; 13 char info[50]; 14 }; 15 16 static LIST_HEAD(test_list); 17 18 static void *seq_start(struct seq_file *m, loff_t *pos) 19 { 20 return seq_list_start(&test_list, *pos);; 21 } 22 23 static void seq_stop(struct seq_file *m, void *v) 24 { 25 /* No cleanup needed in this example */ 26 } 27 28 static void *seq_next(struct seq_file *m, void *v, loff_t *pos) 29 { 30 return seq_list_next(v, &test_list, pos); 31 } 32 33 static int seq_show(struct seq_file *m, void *v) 34 { 35 const struct mylist_random *p = list_entry(v, struct mylist_random, list); 36 37 seq_printf(m, "%s", p->info); 38 39 return 0; 40 } 41 42 static const struct seq_operations seq_test_ops = { 43 .start = seq_start, 44 .next = seq_next, 45 .stop = seq_stop, 46 .show = seq_show, 47 }; 48 49 static int seq_test_open(struct inode *inode, struct file *file) 50 { 51 return seq_open(file, &seq_test_ops); 52 } 53 54 static const struct file_operations seq_test_fops = { 55 .owner = THIS_MODULE, 56 .open = seq_test_open, 57 .read = seq_read, 58 .llseek = seq_lseek, 59 .release = seq_release, 60 }; 61 62 static int __init seq_test_init(void) 63 { 64 int i, count; 65 struct mylist_random *mylist_node; 66 struct proc_dir_entry *p; 67 68 p = proc_create("seq_file_test", S_IRUGO, NULL, &seq_test_fops); 69 if (!p) 70 goto out; 71 72 for(i = 0; i < 10; i++) { 73 mylist_node = kmalloc(sizeof(struct mylist_random), GFP_ATOMIC); 74 if (!mylist_node) 75 return -ENOMEM; 76 memset(mylist_node, 0, sizeof(struct mylist_random)); 77 get_random_bytes(&count, sizeof(int)); 78 sprintf(mylist_node->info, "random number %d: %d\n", i, count); 79 printk("%s", mylist_node->info); 80 list_add_tail(&mylist_node->list, &test_list); 81 } 82 83 return 0; 84 out: 85 remove_proc_entry("seq_file_test", NULL); 86 return -EFAULT; 87 } 88 89 static void __exit seq_test_exit(void) 90 { 91 struct list_head *p, *q; 92 struct mylist_random *mylist_node; 93 94 list_for_each_safe(p, q, &test_list) { 95 mylist_node = list_entry(p, struct mylist_random, list); 96 list_del(p); 97 kfree(mylist_node); 98 } 99 100 remove_proc_entry("seq_file_test", NULL); 101 } 102 103 module_init(seq_test_init); 104 module_exit(seq_test_exit); 105 106 MODULE_AUTHOR("Richard Tang <[email protected]>"); 107 MODULE_LICENSE("GPL");
http://blog.csdn.net/npy_lp/article/details/7219776
时间: 2024-10-14 15:09:43