Im starting kernel programming and need info on the read and writing function
to a /proc file.

When a program writes to my /proc module, I need to store the contents.
When I read the contents of the /proc file, it only return the most recent
entry, and not the everything that has been written. How can I return all
written data.

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>   
#include <asm/uaccess.h>

#define PROCFS_MAX_SIZE     1024
#define PROCFS_NAME         "junk"

static struct proc_dir_entry *file;
static int size = 100;
static int index = -1;
char **lines;

int 
procfile_read(char *buffer,
          char **buffer_location,
          off_t offset, int buffer_length, int *eof, void *data){

    int ret = 0;
    int i;
    for(i = 0; i <= index; i++){
      buffer[buffer_length] = '\0';
      memcpy(buffer,lines[i],20);
      ret += 20;
    }

    return ret;

}

int procfile_write(struct file *file, const char *buffer, unsigned long count,
           void *data){

    if(copy_from_user(lines[++index],buffer,count))
        return -EFAULT;


    return count;

}

int init_module()
{

    file = create_proc_entry(PROCFS_NAME, 0644, NULL);

    if (file == NULL) {
        remove_proc_entry(PROCFS_NAME,NULL);
        printk(KERN_ALERT "Error: Could not initialize /proc/%s\n",
            PROCFS_NAME);
        return -ENOMEM;
    }

    file->read_proc  = procfile_read;
    file->write_proc = procfile_write;

    lines = kmalloc(10 * sizeof(char *),GFP_KERNEL);
    int i;
    for(i = 0; i < 10; i++)
     lines[i] = kmalloc(20 * sizeof(char),GFP_KERNEL);


    printk(KERN_INFO "/proc/%s created\n", PROCFS_NAME);    
    return 0;   /* everything is ok */
}

void cleanup_module()
{
    remove_proc_entry(PROCFS_NAME,NULL);
    index = 0;
    printk(KERN_INFO "/proc/%s removed\n", PROCFS_NAME);
}

My guess is that procfile_read() is writing beyond the bounds of buffer parameter. Is buffer allocated enough memory to hold all those lines of text?

Also, the loop on line 21 should be <index, not <=index because the loop starts counting at 0 and the value of index is initially 1.

Each string in the buffer is NULL terminated, which means you can't use any of the string functions in string.h unless you iterate through the entire buffer with a pointer so that the pointer can increment past the '\0' byte to gain access to the next string. So if you just did printf("%s\n", buffer) only the first of several strings will be printed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.