#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
/proc 虚拟文件系统 用于内核向用户空间导出信息 ,是一种内核与用户新的通讯方法,对/proc的读写 即与内核交互 如/proc/meminfo 文件包含内存信息
/proc 由内核控制,没有承载 /proc 的设备。因为 /proc 主要存放由内核控制的状态信息,所以大部分这些信息的逻辑位置位于内核控制的内存。对 /proc 进行一次
'ls -l' 可以看到大部分文件都是 0 字节大的;不过察看这些文件的时候,确实可以看到一些信息。
/proc/cpuinfo - CPU 的信息 (型号, 家族, 缓存大小等)
/proc/meminfo - 物理内存、交换空间等的信息
/proc/mounts - 已加载的文件系统的列表
/proc/devices - 可用设备的列表
/proc/filesystems - 被支持的文件系统
/proc/modules - 已加载的模块
/proc/version - 内核版本
/proc/cmdline - 系统启动时输入的内核命令行参数
内核中USB PCI 都会在/proc下导出内核信息
MODULE_AUTHOR("Barry Song (author@linuxdriver.cn)");
MODULE_DESCRIPTION("proc exmaple");
MODULE_LICENSE("GPL");
unsigned int variable;
struct proc_dir_entry *test_dir, *test_entry;
int test_proc_read(char *buf, char **start, off_t off, int count,
int *eof, void *data)
{ //start 用于返回实际写入到内存中的位置
if(off>0)
{
*eof=1;
return 0;
}
unsigned int *ptr_var = data;
int *p=0;
*p=1;
return sprintf(buf, "%u\n", *ptr_var);
}
int test_proc_write(struct file *file, const char *buffer,
unsigned long count, void *data)
{
int count =MINLEN(max_ul_len,count);
char k_buf[512];
copy_from_user(k_buf,buffer,count);
unsigned int *ptr_var = data;
printk(KERN_DEBUG "TEST: variable set to: %s", buffer);
//内核空间的字符串转化为整数 函数
*ptr_var = simple_strtoul(buffer, NULL, 10);
return count;
}
int register_proc_files(void)
{
test_dir = proc_mkdir("test_dir", NULL);
if (test_dir) {
//创建节点 0644 可读写的节点 test_dir 为父节点
test_entry = create_proc_entry("test_rw", 0644, test_dir);
if (test_entry) {
test_entry->nlink = 1;
test_entry->owner =THIS_MODULE;
test_entry->data = (void *) &variable;
//指定读写函数指针
test_entry->read_proc = test_proc_read;
test_entry->write_proc = test_proc_write;
return 0;
}
}
return -ENOMEM;
}
void unregister_proc_files(void)
{
//删除/proc 下的节点
remove_proc_entry("test_rw", test_dir);
remove_proc_entry("test_dir", NULL);
}
int test_proc_init(void)
{
return register_proc_files();
}
void test_proc_cleanup(void)
{
unregister_proc_files();
}
module_init(test_proc_init);
module_exit(test_proc_cleanup);
最后 使用 insmod 命令加载模块
cat 读取写入到其中的值
使用 echo xxx > /proc/test_rw 写入数据