linux proc
来源:互联网 发布:hyper v 网络设置 编辑:程序博客网 时间:2024/05/29 12:33
in Linux,
1.创建目录:
- struct
proc_dir_entry const*proc_mkdir( char *name, -
struct proc_dir_entry *parent);
2.创建proc文件:
- struct
proc_dir_entry const*create_proc_entry( char *name, mode_t mode, -
struct proc_dir_entry *parent );
create_proc_entry函数用于创建一个一般的proc文件,其中name是文件名,比如“hello”,mode是文件模式,parent是要创建的proc文件的父目录(若parent = NULL则创建在/proc目录下)。
3.删除proc文件/目录:
- void
remove_dir_entry( constchar *name, structproc_dir_entry *parent);
参数同proc_mkdir()函数类似
4.创建可读写的proc文件
proc文件实际上是一个叫做proc_dir entry的struct(定义在proc_fs.h),该struct中有int read_proc和int write_proc两个元素,要实现proc的文件的读写就要给这两个元素赋值。但这里不是简单地将一个整数赋值过去就行了,需要实现两个回调函数。
在用户或应用程序访问该proc文件时,就会调用这个函数,实现这个函数时只需将想要让用户看到的内容放入page即可。
写回调函数原型:int mod_write( struct file *filp, const char __user *buff,
在用户或应用程序试图写入该proc文件时,就会调用这个函数,实现这个函数时需要接收用户写入的数据(buff参数)。
写一个模块测试proc文件的读写:
- #include
linux/module.h - #include
linux/kernel.h - #include
linux/proc_fs.h - #include
linux/sched.h - #include
asm/uaccess.h -
- #define
STRINGLEN 1024 -
- char
global_buffer[STRINGLEN]; -
- struct
proc_dir_entry *example_dir, *hello_file; -
- int
proc_read_hello( char*page, char**start, intoff_t off, count, int*eof, -
void *data) { -
int len; -
len = sprintf(page, global_buffer); //把global_buffer的内容显示给访问者 -
return len; - }
-
- int
proc_write_hello( structfile const*file, char *buffer, longunsigned count, -
void *data) { -
int len; -
-
if (count = STRINGLEN) -
len = STRINGLEN – 1; -
else -
len = count; -
-
-
copy_from_user(global_buffer, buffer, len); -
global_buffer[len] = \0′; -
return len; - }
-
- static
int __init void)proc_test_init( { -
example_dir = proc_mkdir("proc_test", NULL); -
hello_file = create_proc_entry("hello", S_IRUGO, example_dir); -
strcpy(global_buffer, "hello"); -
hello_file->read_proc = proc_read_hello; -
hello_file->write_proc = proc_write_hello; -
return 0; - }
-
- static
void __exit void)proc_test_exit( { -
remove_proc_entry("hello", example_dir); -
remove_proc_entry(“proc_test”, NULL); - }
-
- module_init(proc_test_init);
- module_exit(proc_test_exit);
写入proc文件
echo "Hello from kernel" /proc/proc_test/hello'
读取proc文件内容,将看到屏幕上显示了我们写入的字符串:Hello from kernel
cat /proc/proc_test/hello
</pre><pre name="code" style="white-space: normal; color: rgb(70, 70, 70); font-size: 14px; line-height: 21px; background-color: rgb(255, 255, 255);">内核编程函数总结
</pre><pre name="code" style="white-space: normal; color: rgb(70, 70, 70); font-size: 14px; line-height: 21px; background-color: rgb(255, 255, 255);">一、头文件:
二、创建与删除proc文件:
*name,mode_t mode,struct proc_dir_entry *parent,read_proc_t*
read_proc,void *data);