您应该注意,如果可能的话,应该避免在 Linux 内核中使用文件 I/O。主要思想是“深入一层”,直接调用 VFS 级函数而不是 syscall 处理程序:

包括:

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

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

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;
}

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

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

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

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) :

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) :

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

[Edit] 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.

Since version 4.14 of Linux kernel, vfs_read and vfs_write functions are 不再出口 for use in modules. Instead, functions exclusively for kernel's file access are provided:

# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);


# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
loff_t *pos);

此外,filp_open不再接受用户空间字符串,因此它可以用于内核访问 直接(不与 set_fs共舞)。