关于如何在内核中保存文件的问题网络上已经有很多资料:内容比较详细
写这篇博客是因为在实际使用过程中,发现linux内核中已有相关读写函数实现,但不同的是在一些版本的内核中没有将这些函数导出。
下面就给出读写函数在内核中的具体实现代码:
写文件:
ssize_t kernel_write(struct file *file, const char *buf, size_t count,
loff_t pos)
{
mm_segment_t old_fs;
ssize_t res;
old_fs = get_fs();
set_fs(get_ds());
/* The cast to a user pointer is valid due to the set_fs() */
res = vfs_write(file, (const char __user *)buf, count, &pos);
set_fs(old_fs);
return res;
}
参数说明:
file:文件句柄
buf:要写入文件的内容的首地址
count:写入数据长度,单位“byte”
pos:偏移量
读文件:
int kernel_read(struct file *file, loff_t offset,
char *addr, unsigned long count)
{
mm_segment_t old_fs;
loff_t pos = offset;
int result;
old_fs = get_fs();
set_fs(get_ds());
/* The cast to a user pointer is valid due to the set_fs() */
result = vfs_read(file, (void __user *)addr, count, &pos);
set_fs(old_fs);
return result;
}
参数说明:
file:文件句柄
offset:偏移量
addr:存放从文件中读出内容的首地址
count:要读出数据长度,单位“byte”