Linux字符设备驱动学习(5)——/proc文件系统

一、概念

①/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);



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值