我正在尝试通过内核模块读写proc文件。但是当我运行以下命令时:
echo "hello" >> /proc/hello && cat /proc/hello
,它没有输出任何内容。当我通过文本编辑器打开文件时,我发现了一些神秘的符号。请您帮我解决这个问题。 ^@^@^@^@^@^@^@^@^@^@
非常感谢您的帮助,任何帮助都将不胜感激。
提前致谢。
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include<linux/sched.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
int len,temp;
char *msg;
int read_proc(struct file *filp,char *buf,size_t count,loff_t *offp ){
if(count>temp){count=temp;}
temp=temp-count;
copy_to_user(buf,msg, count);
if(count==0)temp=len;
return count;
}
int write_proc(struct file *filp,const char *buf,size_t count,loff_t *offp){
copy_from_user(msg,buf,count);
len=count;
temp=len;
return count;
}
struct file_operations proc_fops = {
read: read_proc,
write: write_proc
};
void create_new_proc_entry(void){
proc_create("hello",0,NULL,&proc_fops);
msg=kmalloc(GFP_KERNEL,10*sizeof(char));
}
int proc_init (void){
create_new_proc_entry();
return 0;
}
void proc_cleanup(void){
remove_proc_entry("hello",NULL);
}
MODULE_LICENSE("GPL");
module_init(proc_init);
module_exit(proc_cleanup);
msg
中复制了一些东西,但是msg
的大小为10个字符=>在write_proc
中确保不允许count
超过10,否则你将会有一个缓冲区溢出! - Garf365