Skip to content

Instantly share code, notes, and snippets.

@mad
Created January 3, 2011 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mad/763731 to your computer and use it in GitHub Desktop.
Save mad/763731 to your computer and use it in GitHub Desktop.
Reading files from the linux kernel
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
MODULE_LICENSE("GPL");
static int __init init_lkm (void)
{
struct file *f = NULL;
loff_t pos;
mm_segment_t old_fs;
int ret = 0;
char buf[10] = {0};
f = filp_open("/tmp/test", O_RDONLY, 0);
if (! IS_ERR(f)) {
pos = f->f_pos;
old_fs = get_fs();
set_fs(KERNEL_DS);
ret = vfs_read(f, buf, 10, &pos);
set_fs(old_fs);
f->f_pos = 0;
filp_close(f, NULL);
buf[ret] = 0;
printk("readed %d bytes: %s\n", ret, buf);
} else {
printk("open error %ld\n", -PTR_ERR(f));
}
return 0;
}
static void __exit exit_lkm (void)
{
}
module_init (init_lkm);
module_exit (exit_lkm);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment