sil2100//vx developer log

Welcome to my personal web page

Kernel writing to file

Today a quick post about something obvious - file reading/writing in kernel space. First of all, I'm obliged to inform you that this practice is very bad and shouldn't be done for purposes other than e.g. temporary debugging. You can find out why it's bad and how to do it properly here.

2010-05-31

Empty

But there are times when you want to dump something (e.g. binary data) to a file on a filesystem fast, just once and just for debugging.


struct file *file;
loff_t pos = 0;
int fd;
mm_segment_t old_fs = get_fs();

set_fs(KERNEL_DS);

file = filp_open("/tmp/dump", O_WRONLY | O_CREAT, 0644);
if (file != NULL) {
    vfs_write(file, mem_addr, mem_length, &pos);
    filp_close(file);
}
sys_close(fd);
set_fs(old_fs);

Reading can be done analogically, using a different flag instead (O_RDONLY or O_RDWR) and vfs_read().