ubuntu 使用可加载模块读取文件

ubuntu reading a file using a loadable module

你好,我有一个 class 任务要求我拦截一个打开的调用然后读取文件并编辑输出而不编辑文件本身这一切都是在内核的可加载模块中完成的 space.当我说编辑时,我的意思是将单词 she 更改为 _he 用下划线替换 s 它会将单词 she 的每个实例更改为 _he well,这就是所需的结果。我在网上看了好几天试图弄清楚这个问题,我以为我找到了一个合适的例子,但它一直给我一个错误。一旦我将模块输入到内核中,它立即说已被杀死,然后它说我无法删除它,因为它正在使用,但它不是,这迫使我重新启动我的虚拟机。下面是代码。任何帮助将不胜感激谢谢。

 #include <linux/module.h>  // Needed by all modules
 #include <linux/kernel.h>  // Needed for KERN_INFO
 #include <linux/fs.h>      // Needed by filp
 #include <asm/uaccess.h>   // Needed by segment descriptors

 int init_module(void)
 {
  // Create variables
  struct file *f;
  char buf[128];
  mm_segment_t fs;
  int i;
  // Init the buffer with 0
  for(i=0;i<128;i++)
    buf[i] = 0;
  // To see in /var/log/messages that the module is operating
  printk(KERN_INFO "My module is loaded\n");
  // I am using Fedora and for the test I have chosen following file
 // Obviously it is much smaller than the 128 bytes, but hell with it =)
  f = filp_open("/etc/fedora-release", O_RDONLY, 0);
  if(f == NULL)
      printk(KERN_ALERT "filp_open error!!.\n");
  else{
     // Get current segment descriptor
     fs = get_fs();
     // Set segment descriptor associated to kernel space
     set_fs(get_ds());
     // Read the file
     f->f_op->read(f, buf, 128, &f->f_pos);
     // Restore segment descriptor
     set_fs(fs);
     // See what we read from file
     printk(KERN_INFO "buf:%s\n",buf);
     }
      filp_close(f,NULL);
      return 0;
     }

     void cleanup_module(void)
     {
       printk(KERN_INFO "My module is unloaded\n");
     }

     module_init(init_module);
     module_exit(cleanup_module);

关于从内核读取和写入文件,我建议您阅读以下文章并查看其中的代码片段: 快把我逼疯了——你永远不应该在内核中做的事情 Linux 2005 年期刊,Greg Kroah-Hartman

http://m.linuxjournal.com/article/8110