在内核中读写文件(linux)

关于如何在内核中保存文件的问题网络上已经有很多资料:内容比较详细
写这篇博客是因为在实际使用过程中,发现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”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值