在文件成功打开之后,进程将使用内核提供的read和write系统调用,来读取或修改文件的数据。内核中文件读写操作的系统调用实现基本都一样,下面我们看看文件的读取。
SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_read(file, buf, count, &pos);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
return ret;
}
读取实现,返回读取字节数
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. }