内核读写文件

简介
用户空间        内核空间
open()            filp_open()
close()            filp_close()
read()             kernel_read()
write()             kernel_write()

环境
架构:ARM
内核版本:4.15

源码
file.c

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

#define FILENAME "/tmp/kernel_file"

static char buf[] = "5555\n";
static char buf1[10] = {0};

int hello_init(void)
{
	struct file *filp;
	loff_t pos;

	printk("hello enter\n");

	filp = filp_open(FILENAME, O_RDWR | O_CREAT, 0644);
	if (IS_ERR(filp)) {
		printk("create file error\n");
		return -1;
	}

	pos = 0;
	kernel_write(filp, buf, sizeof(buf), &pos);

	pos = 0;
	kernel_read(filp, buf1, sizeof(buf1) - 1, &pos);
	printk("read: %s", buf1);

	filp_close(filp, NULL);

	return 0;
}
void hello_exit(void)
{
	printk("hello exit\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");

Makefile

obj-m:=file.o  
  
KDIR=/home/liyongjun/project/board/buildroot/Vexpress_4.15/build/linux-4.15.1/
CROSS_COMPILE=/home/liyongjun/project/board/buildroot/Vexpress_4.15/host/bin/arm-linux-

all:
	make -C $(KDIR) M=$(PWD) ARCH=arm CROSS_COMPILE=$(CROSS_COMPILE) modules

clean:
	make -C $(KDIR) M=$(PWD) ARCH=arm CROSS_COMPILE=$(CROSS_COMPILE) clean

测试

# insmod file.ko 
hello enter
read: 5555
# 
# cat /tmp/kernel_file 
5555

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值