proc文件系统
/proc 目录就是Linux的proc文件系统了, 这里面存放内核的配置信息, 网络配置系统, 以及进程的状态都是以pid明明的目录。总之, 关于内核的基本配置你就可以找到。
内核更新
在内核的迭代过程中,总有一些接口被废弃, create_proc_entry就是其中之一。
依稀记得,去年的时候一直想写个proc文件系统测试下, 直到上个月才有时间来做这个事情。当初让我试了就不测试的原因就是那个create_proc_entry函数的弃用, 网上能搜索的例子基本都是用这个函数。
样例代码
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
static char *buffer = NULL;
static int hello_proc_show(struct seq_file *m, void *v) {
seq_printf(m, "Hello proc!\n");
seq_printf(m, "buffer=%s\n", buffer);
int i = 0;
if (buffer != NULL)
{
if (buffer[0] == 's')
{
for (i = 0; i < 10; i++)
seq_printf(m, "i = %d\n", i);
}
}
return 0;
}
static ssize_t hello_proc_write(struct file *file, const char *buffer, size_t len,
loff_t *off)
{
int user_len = 0;
user_len = len;
buffer = (char *)kmalloc(user_len+1, GFP_KERNEL);
memset(buffer, 0, user_len + 1);
if (copy_from_user(buffer, buffer, user_len))
{
printk( "hello_proc error\n");
return -EFAULT;
}
printk( "userlen=%d\n", user_len);
return user_len;
}
static int hello_proc_open(struct inode *inode, struct file *file) {
return single_open(file, hello_proc_show, NULL);
}
static const struct file_operations hello_proc_fops = {
.owner = THIS_MODULE,
.open = hello_proc_open,
.read = seq_read,
.write = hello_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
static int __init hello_proc_init(void) {
proc_create("hello_proc", 0666, NULL, &hello_proc_fops);
return 0;
}
static void __exit hello_proc_exit(void) {
remove_proc_entry("hello_proc", NULL);
}
MODULE_LICENSE("GPL");
module_init(hello_proc_init);
module_exit(hello_proc_exit);
样例代码注释
功能: 其在/proc目录下创建了hello_proc文件,
echo s >/proc/hello_proc
cat /proc/hello_proc
这样就会有输出信息了。
seq_file 是内核提供的序列接口, 详情就不介绍了,这种方式当数据大的时候内存分配不需要你去关心, 非常实用。
源码地址:qianguozheng