Linux内核模块读/写到文件中

时间:2018-02-14 19:56:28

标签: linux io linux-kernel kernel-module

我试图从我的内核模块读取/写入一个文件(我知道它很危险,根本没有建议,但我需要出于各种原因这样做)

我按照了这个答案How to read/write files within a Linux kernel module?,它运行正常。

这是我执行以测试基本功能是否有效的代码:

void test_file(){
   struct file * f = file_open("./test.txt", O_CREAT |  O_RDWR | 
                                   O_APPEND, S_IRWXU | S_IRWXG | S_IRWXO);

   if(f != NULL){
     char arr[100];

     char * str = "I just wrote something";
     file_write(f,0, str, strlen(str)); 

     memset(arr, '\0', 100);
     file_read(f, 0, arr, 20);
     printk(KERN_INFO "Read %s\n",arr); 

     file_close(f);
   }else{
     printk(KERN_ERR "Error! Cannot write into file\n");
   }
}

如果我在__init函数中执行此代码,则会在.ko文件所在的当前文件夹中创建/更新test.txt

但是,我注意到如果我在新的kthread中执行此代码,该文件将在/文件夹中创建,我需要提供绝对路径才能将其置于当前位置。

void test_function(){
   test_file(); // creates test.txt in /
} 

static int __init file_init(void) { 
 struct task_struct * test_thread = kthread_run((void *)test_function, NULL, "Test");
 test_file(); // creates test.txt in .
}
module_init(file_init)

file_writefile_readfile_closefile_open的定义在链接的stackoverflow答案中给出

有人知道如何在kthread中给出相对路径吗?

1 个答案:

答案 0 :(得分:0)

这就是我所做的:

struct file * f;

void test_file(){
  if(f != NULL){
     char arr[100];

     char * str = "I just wrote something";
     file_write(f,0, str, strlen(str)); 

     memset(arr, '\0', 100);
     file_read(f, 0, arr, 20);
     printk(KERN_INFO "Read %s\n",arr); 

     file_close(f);
    }else{
     printk(KERN_ERR "Error! Cannot open file\n");
    }
}


void test_function(){
   test_file(); // access the file from the kthread
} 


static int __init file_init(void) { 
    // Create and open the file in user space
    f = file_open("./test.txt", O_CREAT |  O_RDWR | O_APPEND, \
                                S_IRWXU | S_IRWXG | S_IRWXO);

   struct task_struct * test_thread = kthread_run((void *)test_function, \
                                                   NULL, "Test");
}


module_init(file_init)
相关问题