【问题标题】:Linux Kernel module read/write into a fileLinux内核模块读/写文件
【发布时间】:2018-02-14 19:56:27
【问题描述】:

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

我关注了这个答案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 函数中执行此代码,test.txt 将在 .ko 文件所在的当前文件夹中创建/更新。

但是,我注意到如果我在一个新的 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 中给出相对路径吗?

【问题讨论】:

  • 您的__init 函数在用户空间进程的上下文 中执行,它为您的模块调用insmod。并且相对路径是针对用户空间当前目录计算的。但是 kthread 不是在用户空间进程的上下文中执行的——它是纯内核进程。所以它不知道 当前目录 的所有后果。
  • 所以不硬编码路径的唯一方法是在用户空间创建文件并将struct file *传递给kthread?
  • 嗯,我不确定struct file* 对象是否可以从一个内核线程传递到另一个内核线程。最好将路径(绝对)传递给文件。
  • 我试图创建一个全局变量struct file*,它指向用户进程打开的文件,它可以工作。为什么你认为它不应该起作用?
  • 我认为在某个进程的上下文中打开的文件绑定到该进程。但这可能与内核使用file_open() 打开的文件无关。

标签: linux io linux-kernel kernel-module


【解决方案1】:

这就是我所做的:

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)

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多