在文件成功打开之后,进程将使用内核提供的read和write系统调用,来读取或修改文件的数据。内核中文件读写操作的系统调用实现基本都一样,下面我们看看文件的读取。
/*sys_read()*/ SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; /*从fd中获取相应文件对象地址*/ 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; }
ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { ssize_t ret; /*如果标志中不允许所请求的访问,则返回*/ if (!(file->f_mode & FMODE_READ)) return -EBADF; /*如果没有相关的操作,则返回*/ if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read)) return -EINVAL; /*检查参数*/ if (unlikely(!access_ok(VERIFY_WRITE, buf, count))) return -EFAULT; /*对要访问的文件部分检查是否有冲突的强制锁*/ ret = rw_verify_area(READ, file, pos, count); if (ret >= 0) { count = ret; /*下面的方法返回实际传送的字节数,文件指针被适当的修改*/ if (file->f_op->read)/*如果定义,则用他来传送数据*/ ret = file->f_op->read(file, buf, count, pos); else /*通用读取例程*/ ret = do_sync_read(file, buf, count, pos); if (ret > 0) { fsnotify_access(file->f_path.dentry); add_rchar(current, ret); } inc_syscr(current); } /*返回实际传送字节数*/ return ret; }