内核文件打开读写操作代码
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
相关文章推荐
- python小点心--globals函数
- asp.net生成N组指定位数随机数都一样的解决办法
- java代码动态设置控件的颜色
- java 数据类型对应的字节长度
- QT TextEdit的一些总结
- PHP实现基于文本的摩斯电码生成器
- Struts2拦截器Interceptor执行顺序理解
- python爬山算法
- 编程的智慧
- Java EE V7.0学习笔记-WAS Liberty启动时间:10秒以内
- QT 多线程事件通讯
- 风格指南--C++
- 自上而下的编程方法
- [C#基础知识] ReadOnly关键字修饰的变量可以修改,只是不能重新分配
- Python堡垒机实现之基础知识
- python enumerate()用法
- Spring-注解控件介绍
- eclipse快捷键 转载
- Leetcode 13 - Roman to Integer
- qt&gdal