歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux虛擬文件系統之文件讀取(sys_read())

Linux虛擬文件系統之文件讀取(sys_read())

日期:2017/2/28 15:56:41   编辑:Linux教程

在文件成功打開之後,進程將使用內核提供的read和write系統調用,來讀取或修改文件的數據。內核中文件讀寫操作的系統調用實現基本都一樣,下面我們看看文件的讀取。

[cpp]

  1. /*sys_read()*/
  2. SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
  3. {
  4. struct file *file;
  5. ssize_t ret = -EBADF;
  6. int fput_needed;
  7. /*從fd中獲取相應文件對象地址*/
  8. file = fget_light(fd, &fput_needed);
  9. if (file) {
  10. /*獲取文件訪問指針*/
  11. loff_t pos = file_pos_read(file);
[cpp]
  1. /*實現*/
  2. ret = vfs_read(file, buf, count, &pos);
  3. /*位置指針移動*/
  4. file_pos_write(file, pos);
  5. /*釋放文件對象*/
  6. fput_light(file, fput_needed);
  7. }
  8. /*返回讀取的字節數*/
  9. return ret;
  10. }

讀取實現,返回讀取字節數
[cpp]
  1. ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
  2. {
  3. ssize_t ret;
  4. /*如果標志中不允許所請求的訪問,則返回*/
  5. if (!(file->f_mode & FMODE_READ))
  6. return -EBADF;
  7. /*如果沒有相關的操作,則返回*/
  8. if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read))
  9. return -EINVAL;
  10. /*檢查參數*/
  11. if (unlikely(!access_ok(VERIFY_WRITE, buf, count)))
  12. return -EFAULT;
  13. /*對要訪問的文件部分檢查是否有沖突的強制鎖*/
  14. ret = rw_verify_area(READ, file, pos, count);
  15. if (ret >= 0) {
  16. count = ret;
  17. /*下面的方法返回實際傳送的字節數,文件指針被適當的修改*/
  18. if (file->f_op->read)/*如果定義,則用他來傳送數據*/
  19. ret = file->f_op->read(file, buf, count, pos);
  20. else
  21. /*通用讀取例程*/
  22. ret = do_sync_read(file, buf, count, pos);
  23. if (ret > 0) {
  24. fsnotify_access(file->f_path.dentry);
  25. add_rchar(current, ret);
  26. }
  27. inc_syscr(current);
  28. }
  29. /*返回實際傳送字節數*/
  30. return ret;
  31. }
Copyright © Linux教程網 All Rights Reserved