Skip to content

procfs Entries

The /proc filesystem provides a mechanism for kernel modules to expose runtime information to user space. Creating entries in /proc involves using the proc_create() function, which allows you to register a file with a custom read callback. This section demonstrates how to implement such entries, focusing on the proc_create() API and the seq_file interface for efficient data retrieval.


proc_create() and Read Callbacks

The proc_create() function is used to create a new entry in the /proc filesystem. It requires three main parameters: 1. Name: The filename under /proc (e.g., myproc). 2. Mode: File permissions (e.g., 0644 for readable/writable). 3. Read callback: A function that handles read operations, typically implemented using the seq_file interface.

The read callback must return a pointer to a seq_file structure, which is populated with the data to be read. This approach is efficient for large datasets and avoids manual memory management.


Example: A Simple /proc Entry

Below is a kernel module that creates a /proc/myproc entry, exposing a static string. The module uses proc_create() and a custom read callback.

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>

static struct proc_dir_entry *my_proc_entry;

static int my_proc_show(struct seq_file *m, void *v) {
    seq_printf(m, "Hello from /proc/myproc!\n");
    return 0;
}

static int my_proc_open(struct inode *inode, struct file *file) {
    return single_open(file, my_proc_show, NULL);
}

static const struct file_operations my_proc_fops = {
    .owner = THIS_MODULE,
    .open = my_proc_open,
    .read = seq_read,
    .llseek = seq_lseek,
    .release = single_release,
};

static int __init my_module_init(void) {
    my_proc_entry = proc_create("myproc", 0644, NULL, &my_proc_fops);
    if (!my_proc_entry) {
        printk(KERN_ERR "Failed to create /proc/myproc\n");
        return -ENOMEM;
    }
    printk(KERN_INFO "myproc entry created\n");
    return 0;
}

static void __exit my_module_exit(void) {
    remove_proc_entry("myproc", NULL);
    printk(KERN_INFO "myproc entry removed\n");
}

module_init(my_module_init);
module_exit(my_module_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Example of creating a /proc entry");

Compilation and Testing

To compile and test the module: 1. Create a Makefile:

obj-m += mymodule.o
2. Build the module:
make -C /lib/modules/$(uname -r)/build M=$(pwd)
3. Load the module:
sudo insmod mymodule.ko
4. Read the /proc entry:
cat /proc/myproc
5. Unload the module:
sudo rmmod mymodule


Key takeaways

  • Use proc_create() to register a /proc entry with a custom read callback.
  • Implement read callbacks using the seq_file interface for efficient data handling.
  • Always clean up entries with remove_proc_entry() during module exit.
  • Ensure proper error handling and kernel compatibility when working with /proc.