How to Export Data from Kernel to User-Space with Procfs
June 12, 2020
Procfs (/proc) is a virtual pseudo-file system also referred to as a virtual file system. A pesudo-file system such as procfs does not contains actual files but rather system and process information (e.g. CPU information, interrupts in use, etc.) and therefore they do not take up disk space (using only main memory). Procfs works in the same way as regular files using the open(), read() and close() system calls. Interestingly, most files exposed by the procfs have a file size of 0 bytes even though they can contain quite a lot of information. The reason is that virtual files in procfs are only populated when requested by the user.
A common use of procfs is to send data from kernel to the user and vice-versa. In order to demonstrate how to use procfs to send data from the kernel to user-space we are going to modify the kernel to send a random number from the kernel to user-space using procfs. For this example, we are using the Linux 5.4.
Inside fs/proc/base.c, we create the following functions:
Then, still in the fs/proc/base.c, we add the following line (which creates the actual entry inside procfs):
Inside the two declarations of:
Afterwards, inside kernel/sched/base.c we write the following function,
Finally, below is a simple program (adapted from code by Nathan Ackerman) to read the random number we just from procfs: