Chinaunix首页 | 论坛 | 博客
  • 博客访问: 811108
  • 博文数量: 92
  • 博客积分: 1498
  • 博客等级: 上尉
  • 技术积分: 993
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-18 18:31
文章分类

全部博文(92)

文章存档

2013年(2)

2012年(3)

2011年(3)

2010年(61)

2009年(23)

分类: C/C++

2010-07-21 20:07:48

看到了牛涛的这篇文章,可能会用到,就转载了过来。

在VFS的支持下,用户态进程读写任何类型的文件系统都可以使用read和write着两个 系统调用,但是在linux内核中没有这样的系统调用我们如何操作文件呢?我们知道read和write在进入内核态之后,实际执行的是sys_read 和sys_write,但是查看内核源代码,发现这些操作文件的函数都没有导出(使用EXPORT_SYMBOL导出),也就是说在内核模块中是不能使用 的,那如何是好?

通过查看sys_open的源码我们发现,其主要使用了do_filp_open()函数, 该函数在fs/namei.c中,而在改文件中,filp_open函数也是调用了do_filp_open函数,并且接口和sys_open函数极为相 似,调用参数也和sys_open一样,并且使用EXPORT_SYMBOL导出了,所以我们猜想该函数可以打开文件,功能和open一样。使用同样的查 找方法,我们找出了一组在内核中操作文件的函数,如下:

功能 函数原型
打开文件 struct file *filp_open(const char *filename, int flags, int mode)
读取文件 ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
写文件 ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
关闭文件 int filp_close(struct file *filp, fl_owner_t id)

我们注意到在vfs_read和vfs_write函数中,其参数buf指向的用户空间的内 存地址,如果我们直接使用内核空间的指针,则会返回-EFALUT。所以我们需要使用
set_fs()和get_fs()宏来改变内核对内存地址检查的处理方式,所以在内核空间对文件的读写流程为:

  1. mm_segment_t fs = get_fs();
  2. set_fs(KERNEL_FS);
  3. //vfs_write();
  4. vfs_read();
  5. set_fs(fs);

下面为一个在内核中对文件操作的例子:

  1. #include <linux/module.h>
  2. #include <linux/init.h>
  3. #include <linux/fs.h>
  4. #include <linux/uaccess.h>
  5. static char buf[] = "你好";
  6. static char buf1[10];
  7.  
  8. int __init hello_init(void)
  9. {
  10.     struct file *fp;
  11.     mm_segment_t fs;
  12.     loff_t pos;
  13.     printk("hello enter\n");
  14.     fp = filp_open("/home/niutao/kernel_file", O_RDWR | O_CREAT, 0644);
  15.     if (IS_ERR(fp)) {
  16.         printk("create file error\n");
  17.         return -1;
  18.     }
  19.     fs = get_fs();
  20.     set_fs(KERNEL_DS);
  21.     pos = 0;
  22.     vfs_write(fp, buf, sizeof(buf), &pos);
  23.     pos = 0;
  24.     vfs_read(fp, buf1, sizeof(buf), &pos);
  25.     printk("read: %s\n", buf1);
  26.     filp_close(fp, NULL);
  27.     set_fs(fs);
  28.     return 0;
  29. }
  30. void __exit hello_exit(void)
  31. {
  32.     printk("hello exit\n");
  33. }
  34.  
  35. module_init(hello_init);
  36. module_exit(hello_exit);
  37.  
  38. MODULE_LICENSE("GPL");
阅读(1056) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~