linux可加载内核模块读写文件实现源码

文章详细描述了一个简单的Linux内核模块,展示了如何进行文件读写操作,包括打开、读取、写入文件以及模块初始化和退出过程。
摘要由CSDN通过智能技术生成

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

#define FILE_PATH "/path/to/your/file.txt"
#define BUFFER_SIZE 1024

static int read_file(void) {
    struct file *file;
    char buffer[BUFFER_SIZE];
    mm_segment_t oldfs;
    int bytes_read = 0;

    // Open the file
    file = filp_open(FILE_PATH, O_RDONLY, 0);
    if (IS_ERR(file)) {
        printk(KERN_ERR "Failed to open file: %s\n", FILE_PATH);
        return PTR_ERR(file);
    }

    // Read from the file
    oldfs = get_fs();
    set_fs(KERNEL_DS);
    bytes_read = vfs_read(file, buffer, BUFFER_SIZE, &file->f_pos);
    set_fs(oldfs);

    if (bytes_read < 0) {
        printk(KERN_ERR "Failed to read from file: %s\n", FILE_PATH);
        filp_close(file, NULL);
        return bytes_read;
    }

    // Close the file
    filp_close(file, NULL);

    // Print the read data
    printk(KERN_INFO "Read %d bytes: %s\n", bytes_read, buffer);

    return 0;
}

static int write_file(void) {
    struct file *file;
    char buffer[] = "Hello, world!";
    mm_segment_t oldfs;
    int bytes_written = 0;

    // Open the file
    file = filp_open(FILE_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (IS_ERR(file)) {
        printk(KERN_ERR "Failed to open file: %s\n", FILE_PATH);
        return PTR_ERR(file);
    }

    // Write to the file
    oldfs = get_fs();
    set_fs(KERNEL_DS);
    bytes_written = vfs_write(file, buffer, strlen(buffer), &file->f_pos);
    set_fs(oldfs);

    if (bytes_written < 0) {
        printk(KERN_ERR "Failed to write to file: %s\n", FILE_PATH);
        filp_close(file, NULL);
        return bytes_written;
    }

    // Close the file
    filp_close(file, NULL);

    printk(KERN_INFO "Wrote %d bytes to file: %s\n", bytes_written, FILE_PATH);

    return 0;
}

static int __init file_io_init(void) {
    printk(KERN_INFO "File IO module initialized\n");
    read_file(); // Example: read from file during module initialization
    write_file(); // Example: write to file during module initialization
    return 0;
}

static void __exit file_io_exit(void) {
    printk(KERN_INFO "File IO module exited\n");
}

module_init(file_io_init);
module_exit(file_io_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple Linux kernel module for file I/O operations");
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值