Pages

Creating a proc read entry

After understanding the basics of proc entries and their creation in the post "Creating a proc Entry" In this post we will see how to write a module to create a read only entry under the /proc file system.

To create a proc entry we need to include the file proc_fs.h



d Let us create a function create_new_proc_entry  in which we will call the function create_read_proc_entry as shown below


Note: The following module will not work for kernel versions 3.10 and above. Please refer to the post Creating read only proc entry in kernel versions above 3.10 for the new method of proc entry creation

This should create a read only entry under /proc with the name "hello" having default permissions.
We want to create the entry under /proc directly and not in any sub-directory in /proc hence the third argument is NULL .
The function that would get executed when the proc entry is read is "read_proc" .
We are not passing any data to the function, hence the last argument is NULL


The next step is to implement the read_proc function. The read function's prototype is




Arguments:
*buf : The kernel allocates a page of memory to any process that attempts to read a proc entry. The page pointer points to that buffer of memory into which the data is written.
**start: This pointer is used when the reading of the proc file should not start from the beginning of the file but from a certain offset. For small reads this is generally set to NULL.
off : The offset from the beginning of the file where the file pointer currently points to
count : The number of bytes of data to be read
data : The data passed from the create_read_proc_entry function call.
eof: is set to 1 to indicate end of file



The read_proc function returns an integer value which basically gives the number of bytes of data placed in the page buffer.

In our code we will just put a print statement in the read_proc function.



Note the printing in proc entries is using the command sprintf.

The proc entry should get created as soon as we do insertion of the module. The init function is the one that gets called when the module gets inserted so we add a call to the create_new_proc_entry in the init function of the module.


The proc entry need to be removed once we remove the module, hence add a call to remove_proc_entry in the cleanup function.

In our case it would be


Combining the above mentioned snippets into a module, the code will look as follows.

code: proc_read.c



Makefile :



Using the same makefile as before we can compile this into a .ko file.
Once compiled insert the module using the insmod command




If the insmod is successful then run the command



You should see the output as what ever you have given as print in the read_proc function.

6 comments: