您的位置:首页 > 编程语言

内核文件打开读写操作代码

2016-01-11 16:22 477 查看
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/mm.h>
#include <linux/slab.h>

MODULE_LICENSE("Dual BSD/GPL");

static int doreadfile(void)
{
struct file *filp;
mm_segment_t fs;
loff_t pos = 0;
struct inode *inode;
char *filemm = NULL;
char *start;
char *end;

filp = filp_open("/etc/test.conf", O_RDONLY, 0);
if (IS_ERR_OR_NULL(filp))
return -1;

inode = filp->f_inode;
filemm = (char *)kmalloc(inode->i_size + 1, GFP_KERNEL);
if (IS_ERR_OR_NULL(filemm)) {
if (filp)
filp_close(filp, NULL);
return -1;
}

fs = get_fs();
set_fs(KERNEL_DS);

vfs_read(filp, filemm, inode->i_size, &pos);
filemm[inode->i_size] = '\0';

start = filemm;
end = strchr(start, '\n');
while (end) {
*end = '\0';
printk("read a line: %s\n", start);
start = end + 1;
end = strchr(start, '\n');
}

filp_close(filp, NULL);
set_fs(fs);

kfree(filemm);
return 0;
}

static int hello_init(void)
{
doreadfile();

return 0;
}

static void hello_exit(void)
{
}

module_init(hello_init);
module_exit(hello_exit);

我们注意到在vfs_read和vfs_write函数中,其参数buf指向的用户空间的内存地址,如果我们直接使用内核空间的指针,则会返回-EFALUT。所以我们需要使用

set_fs()和get_fs()宏来改变内核对内存地址检查的处理方式

# To build modules outside of the kernel tree, we run "make"
# in the kernel source tree; the Makefile these then includes this
# Makefile once again.
# This conditional selects whether we are being included from the
# kernel Makefile or not.
ifeq ($(KERNELRELEASE),)

# Assume the source tree is where the running kernel was built
# You should set KERNELDIR in the environment if it's elsewhere
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
# The current directory is passed to sub-makes as argument
PWD := $(shell pwd)
EXTRA_CFLAGS=-g
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

modules_install:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install

clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions Module.symvers modules.order

.PHONY: modules modules_install clean

else
EXTRA_CFLAGS=-g
# called from kernel build system: just declare what our modules are
obj-m := readfile.o
endif



参考文档:
http://blog.csdn.net/tommy_wxie/article/details/8194276 http://blog.csdn.net/leewenjin/article/details/7605179
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: