一个可以运行的 linux下创建proc的代码示例
最近搞了一个proc来测试kernel的一个函数,记下来,省去以后再摸索。
#include <linux/types.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> /* TEST */ static int api_test_read_proc ( struct seq_file* seq, void* v ) { printk(" this is api read proc. "); return 0; } static ssize_t api_test_write_proc ( struct file* file, const char* buffer, size_t count, loff_t* off) { unsigned char tmpBuf[16] = {0}; char *token, *cp = tmpBuf; int len = (count > 15) ? 15 : count; int32 number1, number2; if (buffer && !copy_from_user(tmpBuf, buffer, len)) { token = strsep(&cp, " "); number1 = simple_strtoul(token, NULL, 16); token = strsep(&cp, " "); number2 = simple_strtoul(token, NULL, 16); return count; } return -EFAULT; } static int api_test_open_proc ( struct inode* inode, struct file* file ) { return single_open(file, api_test_read_proc, NULL); } struct file_operations api_test_fop = { .open = api_test_open_proc, .write = api_test_write_proc, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void api_test_proc_init (void) { struct proc_dir_entry* dir = NULL; struct proc_dir_entry* api_test = NULL; dir = proc_mkdir("proc_dir_name", NULL); api_test = proc_create("proc_name", 0, dir, &api_test_fop); if(!api_test) { printk (KERN_EMERG "api_test, create proc failed!"); } } static int __init api_test_module_init(void) { api_test_proc_init(); return 0; } static void __exit api_test_module_exit(void) { } module_init(api_test_module_init); module_exit(api_test_module_exit);