目录
sys_lseek
read
write
read_write.c主要是实现文件系统调用read(),write()和lseek()三个功能
read和write函数分别是调用file_dev.c/pipe.c/block_dev.c/char_dev.c实现相对应的函数
sys_lseek
lseek实现系统调用将对文件句柄对应文件结果体中的当前读写指针进行修改,对于读写指针不能移动的文件和管道文件,将返回错误
int sys_lseek(unsigned int fd,off_t offset, int origin)
{
struct file * file;
int tmp;
if (fd >= NR_OPEN || !(file=current->filp[fd]) || !(file->f_inode)
|| !IS_SEEKABLE(MAJOR(file->f_inode->i_dev)))
return -EBADF;
if (file->f_inode->i_pipe)
return -ESPIPE;
switch (origin) {
case 0://SEEK_SET,要求文件以起始处+offset
if (offset<0) return -EINVAL;
file->f_pos=offset;
break;
case 1://SEEK_CUR,以当前指针处+offset
if (file->f_pos+offset<0) return -EINVAL;
file->f_pos += offset;
break;
case 2://SEEK_END,文件末尾+offset
if ((tmp=file->f_inode->i_size+offset) < 0)
return -EINVAL;
file->f_pos = tmp;
break;
default:
return -EINVAL;
}
return file->f_pos;
}
read
read函数首先判断所有参数的有效性,然后根据文件的i节点信息判断文件的类型,若是管道则调用pipe.c,若是字符设备则调用char_dev.c,若是块设备则调用block_dev.c,若是目录或者正常文件就调用file_dev.c文章来源:https://www.toymoban.com/news/detail-543634.html
int sys_read(unsigned int fd,char * buf,int count)
{
struct file * file;
struct m_inode * inode;
if (fd>=NR_OPEN || count<0 || !(file=current->filp[fd]))
return -EINVAL;
if (!count)
return 0;
verify_area(buf,count);
inode = file->f_inode;
if (inode->i_pipe)
return (file->f_mode&1)?read_pipe(inode,buf,count):-EIO;
if (S_ISCHR(inode->i_mode))
return rw_char(READ,inode->i_zone[0],buf,count,&file->f_pos);
if (S_ISBLK(inode->i_mode))
return block_read(inode->i_zone[0],&file->f_pos,buf,count);
if (S_ISDIR(inode->i_mode) || S_ISREG(inode->i_mode)) {
if (count+file->f_pos > inode->i_size)
count = inode->i_size - file->f_pos;
if (count<=0)
return 0;
return file_read(inode,file,buf,count);
}
printk("(Read)inode->i_mode=%06o\n\r",inode->i_mode);
return -EINVAL;
}
write
与read一样文章来源地址https://www.toymoban.com/news/detail-543634.html
int sys_write(unsigned int fd,char * buf,int count)
{
struct file * file;
struct m_inode * inode;
if (fd>=NR_OPEN || count <0 || !(file=current->filp[fd]))
return -EINVAL;
if (!count)
return 0;
inode=file->f_inode;
if (inode->i_pipe)
return (file->f_mode&2)?write_pipe(inode,buf,count):-EIO;
if (S_ISCHR(inode->i_mode))
return rw_char(WRITE,inode->i_zone[0],buf,count,&file->f_pos);
if (S_ISBLK(inode->i_mode))
return block_write(inode->i_zone[0],&file->f_pos,buf,count);
if (S_ISREG(inode->i_mode))
return file_write(inode,file,buf,count);
printk("(Write)inode->i_mode=%06o\n\r",inode->i_mode);
return -EINVAL;
}
到了这里,关于Linux0.11内核源码解析-read_write.c的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!