Wednesday, May 9, 2012

Module to print the open files of a process

Linux maintains the information about the current process in a structure task_struct.
A macro named current returns a pointer to the task_struct of the current process.
A process can have one or more open files at any given time. A list of all the open files that any process has can be obtained from the structure task_struct.
The task_struct has a member files, which is of type files_struct.
The structure files_struct maintains the information regarding the files that are being used by the process.
files_struct which is defined in fdtable.h is as follows.



The member fdt, in files_struct, of type struct fdtable stores the file descriptors and other relevant pointers for the currently open files.
The struct fdtable which is also defined in fdtable.h is as follows



The member open_fds is bitmap of all the open files, and the member fd is a pointer to the array, which stores the pointers to struct file of each of the open file.

The index of the fd array is the file descriptor of the corresponding file.

The struct file has a member f_path which will enable us to get the complete path in the filesystem for the corresponding file.

Thus to get a list of all the open files we need to access the array fd in the structure fdtable.

The function files_fdtable defined in fdtable.h returns a pointer to the fdtable, taking as input the files_struct.

Once we have fdtable we can iterate over the fd array, printing the file path of each fd.

To retrieve the actual path from f_path we need to make use of the function d_path



defined in fs/dcache.c

Here is module that prints all the open files on being inserted into the kernel.

current_files.c



Makefile to compile the code



Note: Code tested on 2.6.32


Compile and insert.



After inserting into the kernel using insmod, to see the output run the command



By default all processes have 3 files open the standard input, standard output and the standard error with file descriptors 0,1,2 respectively.
Thus the three values /dev/pts/1 are pointing to the terminal on which we are ran the insmod.
To see how the file path changes if we change one of the three file descriptors, add a redirection to a file of output to a file.



Now run dmesg.



The path of file descriptor 2 has changed from the terminal to the new redirected file.

0 comments:

Post a Comment