文件的read()在Unix系统功能 [英] File read() function in Unix Systems

查看:98
本文介绍了文件的read()在Unix系统功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下code。如果失败归因于信号中断重新启动阅读()功能。在阅读()继续从那里被打断了阅读。所以,如果阅读()刚刚看完 EOF 字符前中断,会是什么回报,这多少字节读?

The code below restarts the read() function if it fails due to interruption by signal. The read() resumes its reading from where it was interrupted. So if read() is interrupted just before reading EOF character, what will it return that how many bytes it read?

int r_read(int fd, void *buf, int size)
{
   while((retval=read(fd,buf,size))==-1 && errno ==EINTR);
   return retval;
}  

问候。

推荐答案

这就是为什么读取的字节的数量应保持作为一个整体,以避免中断的问题。这也是有益的非阻塞I / O。

This is why the number of bytes read should be kept as a total, to avoid interrupt issues. It's also useful for non-blocking I/O.

{
    int ret = 0, nread;
    char *nbuf = (char *) buf;

    while ((nread = read(fd, nbuf, size)) != 0)
    {
        if (nread > 0)
            ret += nread, nbuf += nread, size -= nread;
        elif (errno != EINTR)
            break;
    }

    return ret;
}

这篇关于文件的read()在Unix系统功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆