proc文件系统
1.什么是proc文件系统
proc文件系统是一种在用户态检查内核状态的机制
/proc/meminfo查看内存使用情况
2.proc文件系统的特点
1)每个文件都规定了严格的权限
2)可以用本文编辑程序读取(more、cat、vi等)
3)不仅可以有文件还可以有子目录
4)可以自己编辑程序添加一个/proc目录下的程序
5)proc文件系统中文件的内容都是动态创建的在内存中,不存在磁盘中
3、proc内核编程AP
struct proc_dir_entrycreate_proc_entry(const char name,mode_t mode,struct proc_dir_entry*parent)
创建文件
参数:
name:要创建的文件名
mode:文件属性
parent:这个文件的父目录
struct proc_dir_entry* proc_mkdir(const char* name,struct proc_dir_entry* parent)
创建proc目录
name:创建的目录名
parent:这个目录的父目录
void remove_proc_entry(const charname,struct proc_dir_entry parent)
删除proce目录或者文件
name:要删除的文件名或者目录
parent:所在的父目录
读操作
int read_proc(char* buffer,char** stat,off_t off,int count,int peof,voiddata)
buffer:返回给用户的信息写在buffer里,最大不要超过PAGE_SIZE
stat:一般不用
off:偏移量
count:用户要读取的字节数
peof:读到文件尾时,需要把*peof置1
data:一般不使用
int write_proc(struct file* file,const char* buffer,unsigned long count,void* data)
file:读proc文件对应的file结构,一般忽略
buffer:写数据的位置
count:写数据的大小
data:一般不使用
demo:
#Include <linux/module.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>
static struct proc_dir_entry mydir;
static struct proc_dir_entry pfile;
static char msg[255];
static int myproc_read(char* page,char**start,off_t off,int count,int eof,voiddata)
{
int len=strlen(msg);
if(off >=len)
return 0;
if(count > len-off);
count=len-off;
memcpy(page+off,msg+off,count);
return off+count;
}
static int myproc_write(struct file *file,const char __user buffer,unsigned long count,void data)
{
unsigned long count2=count;
if(count2 > sizeof(msg))
count2=sizeof(msg)-1;
if(copy_from_user(msg,buffer,count2))
return -EFAULT;
msg[count2]=’\0’;
return count;
}
static int __init myproc_init(void)
{
mydir=proc_mkdir(“mydir”,NULL);
if(!mydir)
{
printk(KERN_ERR “cannot create /proc/mydir\n”);
return -1;
}
pfile=create_proc_entry(“pool”,0666,mydir);
if(!pfile)
{
printk(KERN_ERR “cannot create /proc/mydir/pool\n”);
remove_proc_entry(“mydir”,NULL);
return -1;
}
pfile->read_proc=myproc_read;
pfile->write_proc=myproc_write;
return 0;
}
static void __exit myproc_exit(void)
{
remove_proc_entry(“pool”,mydir);
remove_proc_entry(“mydir”,NULL);
}
module_init(myproc_init);
module_exit(myproc_exit);