Re: Open file in kernel Mode...

From: Richard B. Johnson (
Date: Wed May 24 2000 - 10:25:25 EST

On Wed, 24 May 2000, Praveen wrote:

> Hi folks,
> I want to open the file in init module..
> Following is the piece of code i tried..Have a look it...
> open=sys_call_table[__NR_open];
> fd=(*open) ("/dev/tty",0,0);
> But open system call is returning error value ( -14).
> Even i tried to read from standard input fd. I am getting the number of
> characters read,but data is not available in the buffer i used for read
> call. I think it may be because of buffer is in kernel space ...I am not
> sure about
> that..
> Please tell me, whats going on out there ....
> Thz..

This has become a FAQ. There are some tricks that allow some file
manipulation within the kernel. Others may explain. However, you
seem to missing some basic information.

The kernel is not a process. A file-descriptor needs a process-context
for it to mean anything. Otherwise how would the kernel keep your
STDIN_FILENO separate from somebody else's STDIN_FILENO?

Coding a kernel module is not like coding a user-mode program. You
should never write a module that requires reading or writing to any
logical device. The kernel is the thing that translates physical
I/O to logical I/O. Attempting to perform logical I/O in the kernel
is effectively going backwards.

If you need to get "outside world" information into your module, it's
easy. Your module can have code for open(), read(), write(), ioctl(),
and close(). A user-mode program can open() the device and perform
any kind of device-specific ioctl() (or read or write or whatever)
that it wants. This means that there is never, never, ever, never any
real reason to attempt to perform logical (like file) I/O within the
kernel at all.

That said, it is possible to do file I/O in the kernel, but doing
so is a severe violation of standard practice. It is also complicated
and can lead to races and crashes if, for instance, a file is removed
while your module has it open.

You can readily code a kernel module so that it can be controlled
from a user-mode script such as:

insmod my-thing.o
my_device < parameters

Until you understand this, you should not attempt to write a kernel

If you need human input for your module, it works the same way.

Dick Johnson

Penguin : Linux version 2.3.41 on an i686 machine (800.63 BogoMips).

To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to
Please read the FAQ at

This archive was generated by hypermail 2b29 : Wed May 31 2000 - 21:00:11 EST