一、概念
①/proc文件系统可输出文件情况。例如:/proc/modules列出的是当前载入模块的列表。
②/pro文件系统是动态的,驱动程序模块可以在任何时候添加或删除其中的入口项。
二、Linux编写内核模块,实现在/proc目录下添加文件
函数介绍
1.创建文件夹
struct proc_dir_entry *proc_mkdir
(const char *name,
struct proc_dir_entry *parent);
1.创建的文件夹名称
2.创建的文件夹路径,若是在proc根目录,则参数为NULL
返回值是创建的文件夹路径
2.创建文件
static inline struct proc_dir_entry *proc_create(
const char *name,
umode_t mode,
struct proc_dir_entry *parent,
const struct file_operations *proc_fops);
1.创建的文件的名称
2.文件的读写权限
3.创建文件的路径,即在哪个文件夹创建,若是proc根目录,则该参数为NULL
4.此文件的操作函数file_opreations
3.删除
void proc_remove(struct proc_dir_entry *de)
1.删除的proc中的文件或文件路径
2.删除的文件或文件路径
实例:
在/proc目录下创建文件夹test,在test文件夹下创建文件demo,并输入内容hello world
#include <linux/module.h>
#include <linux/kernel.h>
#include<linux/sched.h>
#include <asm/uaccess.h>
#include <linux/proc_fs.h>
MODULE_LICENSE("GPL");
static struct proc_dir_entry *proc_parent;
int len;
int temp;
char *msg;
//该函数将文件内容通过msg复制给buf,以实现文件内容的读写。
static ssize_t read_proc(struct file *filp,char __user *buf,size_t count,loff_t *offp )
{
if(count>temp)
count=temp;
temp=temp-count;
raw_copy_to_user(buf,msg, count);
if(count==0)
temp=len;
return count;
}
static const struct file_operations proc_fops =
{
.read = read_proc //读取文件内容
};
void create_new_proc_entry(void)
{
//创建一个新的目录名hello,并返回一个指向该目录的指针
proc_parent = proc_mkdir("test",NULL);
if(!proc_parent){
printk(KERN_INFO "Error creating proc entry");
}
//创建一个名为world的文件,并使用proc_fops读取该文件的属性
proc_create("demo",0,proc_parent,&proc_fops);
msg="hello world\n"; //文件内容
len=strlen(msg);
temp=len;
printk(KERN_INFO "1.len=%d",len); //文件内容长度
printk(KERN_INFO "proc initialized");
}
int proc_init (void)
{
create_new_proc_entry();
return 0;
}
void proc_cleanup(void)
{
printk(KERN_INFO " Inside cleanup_module\n");
remove_proc_entry("test",proc_parent);
remove_proc_entry("demo",NULL);
}
module_init(proc_init);
module_exit(proc_cleanup);