linux内核中打开文件

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

首先分析一下sys_read系统调用(内核版本为2.6.19.4)。

源代码如下(摘自fs/read_write.c)

[c-sharp]view plaincopy

1.SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)

2.{

3.struct file *file;

4. ssize_t ret = -EBADF;

5.int fput_needed;

6. file = fget_light(fd, &fput_needed);

7.if (file) {

8. loff_t pos = file_pos_read(file);

9. ret = vfs_read(file, buf, count, &pos);

10. file_pos_write(file, pos);

11. fput_light(file, fput_needed);

12. }

13.return ret;

14.}

这里用到了fget_light(),file_pos_read(),vfs_read(),file_pos_write(),fput_light()。

∙file_pos_read()和file_pos_write()(均位于fs/read_write.c)用来读取当前文件指针(即当前文件操作的位置)

∙fget_light()和fput_light()(位于fs/file_table.c和include/linux/file.h)必须是成对出现的!fget_light在当前进程的struct files_struct中根据所谓的用户空间文件描述符fd来获取文件描述符。另外,根据当前fs_struct是否被多各进程共享来判断是否需要对文件描述符进行加锁,并将加锁结果存到一个int中返回, fput_light则根据该结果来判断是否需要对文件描述符解锁

∙vfs_read()(位于fs/read_write.c)调用具体文件系统的read函数来完成读操作,代码如下:

[cpp]view plaincopy

1.ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *

pos)

2.{

3. ssize_t ret;

4.if (!(file->f_mode & FMODE_READ))

5.return -EBADF;

6.if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read))

7.return -EINVAL;

8.if (unlikely(!access_ok(VERIFY_WRITE, buf, count)))

9.return -EFAULT;

10. ret = rw_verify_area(READ, file, pos, count);

11.if (ret >= 0) {

12. count = ret;

13.if (file->f_op->read)

14. ret = file->f_op->read(file, buf, count, pos);

15.else

16. ret = do_sync_read(file, buf, count, pos);

17.if (ret > 0) {

18. fsnotify_access(file->f_path.dentry);

19. add_rchar(current, ret);

20. }

21. inc_syscr(current);

22. }

23.return ret;

24.}

通过源码可以看出,内核中无法直接使用sys_read()来进行文件操作,因为sys_read()总会在当前进程的struct files_struct中查找文件。

(除非内核想对当前进程打开的某个文件进行操作,不知道这种情况是否存在)

内核可以使用vfs_read()来进行文件操作,一个例子如下

[cpp]view plaincopy

1.ssize_t nread;

2.loff_t pos;

3.mm_segment_t old_fs;

4.struct file *file=NULL;

5.old_fs = get_fs();

6.set_fs(KERNEL_DS);

7.file = filp_open("filename", O_RDONLY, 0);

8.if(IS_ERR(file))

9.{

10. printk(KERN_INFO"filp open error/n");

11. set_fs(old_fs);

12.return -1;

13.}

14.else

15. printk(KERN_INFO"filp open succeeded/n");

16.pos=0;

17.nread = vfs_read(file, (char __user *)buffer, len, &pos);

18.if(nread < 0)

19. printk(KERN_INFO"vfs_read failed!/n");

20.else if(nread < len)

21. printk(KERN_INFO"vfs_read PART data/n");

22.else

23. printk(KERN_INFO"vfs_read succeeded/n");

24.if(file)filp_close(file, NULL);

25.

26.set_fs(old_fs);

主要区别就是在操作前调用set_fs()(位于arch/x86/boot/boot.h)将当前fs段寄存器设为KERNEL_DS,在完成后再调用该函数将fs段寄存器设为原来的值,这样做的原因尚不明,希望高手指点。

问题:

1.内核中atomic_read()加锁是怎么进行的

2.还可调用kernel_read()(位于fs/exec.c,在include/linux/fs.h中声明)来直接读文件,该函数中完成了fs段期存期的保存,但找不到对应的kernel_write()函数

相关文档
最新文档