简体   繁体   中英

File read() function in Unix Systems

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;
}  

Regards.

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;
}

If errno == EINTR , it means that read was interrupted before it could read any data at all according to the man page. Ie from my reading, it is as if a read with status EINTR just didn't happen as far as the data in the stream is concerned. So it seems as if you can simply retry without worrying about having lost any bytes. I find this a bit surprising, and I haven't actually tested it, but that is what the manual says.

Here is the actual text from the man page:

EINTR The call was interrupted by a signal before any data was read; see signal(7).

Edit: I tested this now, and I found that if I interrupted the read, EINTR would only be returned if the read was interrupted before anything had been read. Otherwise, it would return successfully, having read less than the requested number of bytes. So to get the number of bytes you want, you will need something that restarts, as the other answer indicates.

There is no "EOF character" as such, there is the end-of-file condition which is indicated as a read of 0 bytes. The EINTR error is set only if read is interrupted while waiting for something to happen, ie before the underlying resource produces any data.

Since EOF normally causes read to stop waiting and return a value, read cannot be interrupted doing that, and if it does, it will just return what it has—the EOF indicator. If read is interrupted while waiting for EOF (before it is announced by the underlying resource), it will of course return -1 and set EINTR.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM