内核模块编程

Mas*_* HA 7 c linux

我正在尝试通过内核模块读取和写入proc文件
但是当我运行此命令时:

echo "hello" >> /proc/hello && cat /proc/hello

当我通过文本编辑器打开文件时,它不会打印任何内容.我发现了这样的神秘符号

 ^@^@^@^@^@^@^@^@^@^@ 
Run Code Online (Sandbox Code Playgroud)

任何帮助将提前感谢

#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);
Run Code Online (Sandbox Code Playgroud)

LPs*_*LPs 4

除了内核模块的其他问题(例如边界检查)

msg=kmalloc(GFP_KERNEL,10*sizeof(char));
Run Code Online (Sandbox Code Playgroud)

不得不

 msg=kmalloc(10*sizeof(char), GFP_KERNEL);
Run Code Online (Sandbox Code Playgroud)

通过您的呼叫kmalloc,您可能正在尝试分配太多或不足的字节,并且它拒绝您的kmalloc请求。

您应该始终检查kmalloc返回值是否一致:!= NULL