Saturday, August 30, 2008

Exposing module internals using seq_file interface

Learn all about seq_file interface here
http://www.xenotime.net/linux/doc/seq_file_howto.txt

The seq_file mechanism provides a more straightforward, non-iterator style, interface. A driver writer may simply define show() with operations that output data to proc file.

First of all, we have to create a file in /proc. For this, we have to call create_proc_entry in our module initialization function.

struct proc_dir_entry *foo = create_proc_entry("foo", 0, NULL); /* This will create "/proc/foo" */

Then initialize the proc file operations structure
foo->proc_fops = &foo_proc_operations;

where foo_proc_operations is defined as,

static struct file_operations foo_proc_operations = {
.open = foo_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
seq_read, seq_lseek, and single_release are functions defined by Linux seq_file core.

Within foo_proc_open we have to call single_open() and pass it "show()", the function performing actual display.

return single_open(file, foo_proc_show, NULL);

Within foo_proc_show, we can use seq_{putc|puts|printf} to output data to "/proc/foo". These functions work like normal putc|puts|printf.

static int foo_proc_show(struct seq_file *m, void *v)
{
seq_puts(m, "Hello from foo\n"); /* write to our proc file */
return 0;
}

And finally don't forget to remove the proc file by calling,

remove_proc_entry("foo", NULL);

No comments: