Force blocking read after EAGAIN?
I have a file descriptor that is open for reading which may be non-blocking. What I need to do is simply read all data until reaching EOF and write that data to a writable file descriptor. As the process that performs this copying is not "aware" of anything that is going on around it, I don't think that I can do something useful while waiting for data, and I don't want to use a while
loop (while errno
is not EAGAIN
) because I think that it would be wasteful. Is there a way to block or otherwise suspend 开发者_运维百科execution of the copying process until data becomes available?
Your other answer simply unsets O_NONBLOCK
, which sets the file back to blocking. That's perfectly fine, if that works in your situation; but if not, you can use select()
to block until your non-blocking file descriptor is readable.
Chapter 7 of the Linux SCSI Generic (sg) HOWTO gives an example of how to do this:
int flags = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, flags & (~O_NONBLOCK));
精彩评论