I was trying to read/write a file from my kernel module (I know it is dangerous and not suggested at all, but I need to do it for various reasons)
I followed this answer How to read/write files within a Linux kernel module?, and it works fine.
This is the code that I execute to test if the basic functions work:
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");
}
}
If I execute this code inside my __init
function, test.txt
is created/updated inside the current folder where the .ko file is.
However, I noticed that if I execute this code in a new kthread, the file is created in /
folder, and I need to provide the absolute path in order to get it in the current location.
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)
Definitions of file_write
, file_read
, file_close
and file_open
are given in the linked stackoverflow answer
Anybody knows how to give a relative path also in the kthread?