Kernel Module Programming

I'm trying to read and write to a proc file through kernel module
But when I run this command :

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

It doesn't print anything and when i open the file through text editor. I found mysterious symbols like this

 ^@^@^@^@^@^@^@^@^@^@ 

Any help will be appreciated thanks in advance

#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);

Apart from other problems of your kernel module (like boundaries check)

This

msg=kmalloc(GFP_KERNEL,10*sizeof(char));

have to be

 msg=kmalloc(10*sizeof(char), GFP_KERNEL);

With your call to kmalloc you are trying, probably, to allocate too many or not enough bytes and it refuses your kmalloc request.

You should always check the kmalloc return value to be consistent: != NULL


你可以在slab.h中找到kmalloc:

static __always_inline void *kmalloc(size_t size, gfp_t flags)
{
    if (__builtin_constant_p(size)) {
        if (size > KMALLOC_MAX_CACHE_SIZE)
            return kmalloc_large(size, flags);
    #ifndef CONFIG_SLOB
        if (!(flags & GFP_DMA)) {
            int index = kmalloc_index(size);

            if (!index)
                return ZERO_SIZE_PTR;

            return kmem_cache_alloc_trace(kmalloc_caches[index],
                    flags, size);
        }
    #endif
    }
    return __kmalloc(size, flags);
}
链接地址: http://www.djcxy.com/p/91274.html

上一篇: 除了最后一个<td>中的孩子之外,将所有<td>设置为不透明

下一篇: 内核模块编程