Linux在内核中创建文件

Linux在内核中创建文件

#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/file.h>

static int __init my_module_init(void) {
    struct file *file;
    mm_segment_t old_fs;
    const char *path = "/tmp/testfile";
    const char *data = "Hello,kernel world";
    loff_t pos = 0;
    ssize_t writtern;

    // 设置为允许访问用户空间地址
    old_fs = get_fs();
    set_fs(KERNEL_DS);

    // 创建并打开文件
    file = filp_open(path, O_CREAT | O_RDWR, 0644);
    if (IS_ERR(file)) {
        printk(KERN_ERR "Error opening file\n");
        set_fs(old_fs);
        return PTR_ERR(file);
    }
    
    //确保文件系统缓存准备好写操作
    file_start_write(file);
    
    written = vfs_write(file,data,strlen(data),&pos);
    if(written < 0)
    {
        printk(KER_ERR "Fail to write to file %ld\n",written);
        file_end_write(file);
        filp_close(file,NULL);
        set_fs(old_fs);
        return written;
    }

    //结束写操作
    file_end_write(file);
    
    // 关闭文件
    filp_close(file, NULL);
    
    //恢复地址空间
    set_fs(old_fs);
    
    printk(KERN_INFO "File written successfully\r\n");

    return 0;
}

static void __exit my_module_exit(void) {
    printk(KERN_INFO "Module exited\n");
}

module_init(my_module_init);
module_exit(my_module_exit);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("A simple example of creating a file in kernel space");
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值