0

I am learning kernel programming and I wrote a small module to create an entry in /proc and try to read contents from it when I use cat on that file. The code is:

#define PROC_DIR_NAME "driver/kernel_test_dir"
#define KERNEL_DATA "This is kernel test"

static int proc_entry_open(struct inode *inode, struct file *file) {
    return 0;
}

static int proc_entry_close(struct inode *inode, struct file *file) {
    return 0;
}

// Return temperature thresholds
static ssize_t proc_entry_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) {
    ssize_t len = (ssize_t) strlen(KERNEL_DATA);

    if(count > len)
    {
        count = len;
    }

    copy_to_user(buf,KERNEL_DATA,count);

    *ppos += count;
    return count;
}

static struct file_operations fops_proc_entry = {
    .open = proc_entry_open,
    .read = proc_entry_read,
    .release = proc_entry_close,
};

static int __init init_test_kernel(void) {
    proc_dir = proc_mkdir(PROC_DIR_NAME, NULL);
    if(proc_dir == NULL) {
        return -ENOMEM;
    }

    proc_entry_file = proc_create ("kernel_test_file", S_IRUSR, proc_dir,&fops_proc_entry);
    if(!proc_entry_file) {
        return -ENOMEM;
    }

    printk(KERN_INFO "kernel_test: Kernel Test module started\n");
    return 0;
}


// Cleanup module
static void __exit cleanup_test_kernel(void) {
    remove_proc_entry("kernel_test_file", proc_dir);
    remove_proc_entry(PROC_DIR_NAME,NULL);
    printk(KERN_INFO "kernel_test: Kernel Test module stopped\n");
}

module_init(init_test_kernel);
module_exit(cleanup_test_kernel);

When I am doing sudo cat /proc/driver/kernel_test_dir/kernel_test_file, nothing is shown on console. However, if I remove the module using rmmod, the console flushes strings like below:

This is kernel testThis is kernel testThis is kernel testThis is kernel test etc.

Why is it working like this?

red0ct
  • 4,840
  • 3
  • 17
  • 44
Monku
  • 2,440
  • 4
  • 33
  • 57
  • 1
    Your *.read* never returns 0, which should signal for `cat` about EOF. Exactly same problem as in [older question](http://stackoverflow.com/questions/31563107/cat-function-calling-read-infinite-times). – Tsyvarev Jun 16 '16 at 22:43
  • @Tsyvarev Thank you again. I got it working now. – Monku Jun 16 '16 at 22:55

0 Answers0