创建一个procfile池 向其中写数据 并读出

我们来分析一下这个procfile内核模块程序

首先是包含头文件  和架构体系无关的头文件都在内核文件的            /include/linux/         下。

首先看procfile的结构体的定义

struct proc_dir_entry {
unsigned int low_ino;
unsigned short namelen;  // 定义名字的长度
const char *name; //profile名字
mode_t mode; //模式  就是创建文件的属性
nlink_t nlink;
uid_t uid;
gid_t gid;
loff_t size;
const struct inode_operations *proc_iops;
/*
* NULL ->proc_fops means "PDE is going away RSN" or
* "PDE is just created". In either case, e.g. ->read_proc won't be
* called because it's too late or too early, respectively.
*
* If you're allocating ->proc_fops dynamically, save a pointer
* somewhere.
*/
const struct file_operations *proc_fops;
struct proc_dir_entry *next, *parent, *subdir;
void *data;
read_proc_t *read_proc; //函数回调指针  读取函数
write_proc_t *write_proc; //写入函数
atomic_t count; /* use count */
int pde_users; /* number of callers into module in progress */
spinlock_t pde_unload_lock; /* proc_fops checks and pde_users bumps */
struct completion *pde_unload_completion;
struct list_head pde_openers; /* who did ->open, but not ->release */
};

创建函数///

struct proc_dir_entry *create_proc_entry(const char *name, mode_t mode,
struct proc_dir_entry *parent)

参数的意义: 第一个为创建文件的名称  第二个为文件的属性 可读?可写? 第三个为父目录

代码区

#include<linux/module.h>

#include<linux/init.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** stat,off_t off,int count,int* eof,void* data)
{
int len = strlen(msg);

if(off>=len)
return 0;
if(count>len-off)
count = len-off;

memcpy(page+off,msg+off,count); //将msg数组中的数据从偏移量off开始读取count个字节到page中

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);//can shu first is the name sec is parent
if(mydir==NULL)
{
printk(KERN_ERR"mydir could not created!!!!!!\n");
return -1;
}

pfile = create_proc_entry("pfile",0666,mydir);

if(pfile == NULL)
{
remove_proc_entry("pfile",mydir);
printk(KERN_ERR"pfile could not created!!\n");
return -1;
}


pfile->read_proc = myproc_read;
pfile->write_proc = myproc_write;

return 0;
}


static void __exit mypfile_exit(void)
{
remove_proc_entry("mydir",NULL);
remove_proc_entry("pfile",mydir);
}


module_init(myproc_init);
module_exit(mypfile_exit);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值