且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-23 11:09:10

您应该意识到应该尽可能避免在 Linux 内核中进行文件 I/O.主要思想是更深一层"并调用 VFS 级别函数而不是系统调用处理程序直接:

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

包括:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

打开文件(类似于打开):

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

关闭文件(类似于关闭):

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

从文件中读取数据(类似于pread):

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

将数据写入文件(类似于 pwrite):

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

同步更改文件(类似于 fsync):

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

最初,我建议使用 file_fsync,它在较新的内核版本中已消失.感谢可怜的家伙建议更改,但他的更改被拒绝.编辑在我审核之前就被拒绝了.

Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.