简介
用户空间 内核空间
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