[KERNEL] 在procfs中新增文件的方法
最近遇到debug需要,在proc文件系统中新增一个文件进行控制debug的开关,主要是控制trace_printk什么时候开打打印,什么时候结束打印。debug函数从入口到出口所用的时间。
/* * * * Add a directory named hello under proc, * and a file named world under hello, whose content is "hello world" * * Copyright (C) 2019 Larry <https://github.com/Larry955/OS-exp.git> * * Released under the GPL. */ #include <linux/module.h> #include <linux/kernel.h> #include<linux/sched.h> #include <asm/uaccess.h> #include <linux/proc_fs.h> static struct proc_dir_entry *proc_parent;
static ssize_t read_proc(struct file *filp,char __user *buf,size_t count,loff_t *offp ) { char ibuf[5];
static char flag = 0;
int len;
len = sprintf(ibuf,"%d\n",xxxxxx); //cat时打印开关变量的状态
copy_to_user(buf, ibuf, len);
if (flag == 0){ //cat时,必须返回0表示read结束,否则会不停的read。
flag = 1;
return len;
}
else {
flag = 0;
return 0;
} }
static ssize_t read_proc(struct file *filp,char __user *buffer,size_t count,loff_t *offp){
char buf[5];
// pr_err("count = %d\n",count);
if (count > 5){
return -ESRCH;
}
copy_from_user(buf, buffer,len);
if (buf[0] == '0')
xxxxxx = 0;
else
if (buf[1] == '1')
xxxxxx = 1;
pr_err("set xxxxx status to %d\n", xxxxxxx);
return len; //返回len表示数据全部写完,否则echo会不停调用
}
static const struct file_operations proc_fops = {
.read = read_proc,
.write = write_proc, }; void create_new_proc_entry(void) { proc_parent = proc_mkdir("switchdir",NULL); if(!proc_parent) { printk(KERN_INFO "Error creating proc entry"); } proc_create("switch",0666,proc_parent,&proc_fops); } int proc_init (void) { create_new_proc_entry(); return 0; } void proc_cleanup(void) { remove_proc_entry("switchdir",proc_parent); remove_proc_entry("switch",NULL); } MODULE_LICENSE("GPL"); module_init(proc_init); module_exit(proc_cleanup);