Why writing files from the kernel is bad ?


The question "how to I open/read/write files from the kernel ?" is often asked on the kernelnewbies mailing list. However, the question cannot really be answered: opening, reading and writing files from within the kernel is usually a bad idea. Generally speaking, trying to use any of the sys_*() functions from the kernel itself is a bad idea.

For several reasons:

The good ways to exchange data with user space

There are several ways to exchange informations between userspace and the kernel, and the one to use really depends on what you want to do:

Using /proc is not anymore a good idea these days, except if you want to export information related to processes.

The good way to create device nodes

The good way is to have your device exported in sysfs and to let udev create the device node in /dev. Do not call try to call sys_mknod() from the kernel.


All that being said, there may be cases where the abovementioned ways to exchange data with userspace are not viable. For example quota reads the limits from special files, coda and intermezzo filesystems serve the content from files in cache etc. In such cases it is important to note, that you don't have a file descriptor table (syscalls have the one of the calling process and kernel threads usually drop it as part of reparenting to init), so you cannot use the sys_*() functions. Instead you have to use the functions operating on struct file directly. Be careful to check locking requirements of these functions, especially of the methods in the file_operations table.

KernelNewbies: FAQ/WhyWritingFilesFromKernelIsBad (last edited 2017-12-30 01:30:00 by localhost)