2012-04-13 63 views
1

我需要实现一个Linux内核驱动程序,(第一步)只将所有文件操作转发到另一个文件(在后面的步骤中,这应该被管理和操纵,但我不想在此讨论)。如何编写Linux驱动程序,只转发文件操作?

我的想法是下面的,但读书时,内核崩溃:

static struct { 
    struct file *file; 
    char *file_name; 
    int open; 
} file_out_data = { 
.file_name = "/any_file", 
.open  = 0, 
}; 


int memory_open(struct inode *inode, struct file *filp) { 
    PRINTK("<1>open memory module\n"); 
    /* 
    * We don't want to talk to two processes at the same time 
    */ 
    if (file_out_data.open) 
     return -EBUSY; 
    /* 
    * Initialize the message 
    */ 
    Message_Ptr = Message; 
    try_module_get(THIS_MODULE); 

     file_out_data.file = filp_open(file_out_data.file_name, filp->f_flags, filp->f_mode); //here should be another return handling in case of fail 
    file_out_data.open++; 

    /* Success */ 
    return 0; 
} 

int memory_release(struct inode *inode, struct file *filp) { 
     PRINTK("<1>release memory module\n"); 
    /* 
    * We're now ready for our next caller 
    */ 
    file_out_data.open--; 
    filp_close(file_out_data.file,NULL); 

    module_put(THIS_MODULE); 
    /* Success */ 
    return 0; 
} 

ssize_t memory_read(struct file *filp, char *buf, 
        size_t count, loff_t *f_pos) { 
    PRINTK("<1>read memory module \n"); 
ret=file_out_data.file->f_op->read(file_out_data.file,buf,count,f_pos); //corrected one, false one is to find in the history 
    return ret; 

} 

那么,谁能告诉我为什么?

+1

这听起来像是[功课] – C2H5OH 2012-04-13 13:01:00

+0

这仅仅是比功课有点大项目起点...但它是因为它是。 – nico 2012-04-13 13:07:23

+0

如果你知道更有效的方法,我不能使用vfs _ * - 命令。 – nico 2012-04-13 14:12:13

回答

2
  1. 请勿使用set_fs(),因为没有理由这样做。使用file->f_fop->read()代替vfs_read。看看filefile_operations结构。
+0

谢谢。我试过“ret = file_out_data.file-> f_op-> read(file_out_data.file,buf,count,f_pos);”在我阅读您的文章之前,它工作。 – nico 2012-04-13 14:39:37

2

为什么你递增file_out_data.open两次并递减一次?这可能导致您在关闭后使用file_out_data.file

+0

对不起,我的错。是的,它应该只增加一次。但即使第一次崩溃也没有改变。 – nico 2012-04-13 13:06:19

0

你想在你的文件中写内存吗? 因为你读,不写...... 可能我错了

相关问题