开发者

read and EAGAIN

I am using non-blocking client socket to read data from.

Sometimes read returns EAGAIN.

What is the proper way to handle it?

At the moment my code retries immediately forever. Little worried about it since there is the potential of an endless loop开发者_运维技巧 if read keeps returning EAGAIN.

s = socket(...);
ioctl(s, FIONBIO, ON);
select(s+1, r, NULL, e, NULL);
if (FD_ISSET(s, r)) {
  ret = read(...)
  ret = read(...)
  ret <---- is EAGAIN sometimes
}


After you get an EAGAIN, you should stop reading, and select on the socket again. select will tell you when you can read more.


From the tag of this post, I assume you tried this piece of code on iOS. EAGAIN means to try again on most of the platforms. However, it means Resource temporarily unavailable. You can find the reference here. http://www.ioplex.com/~miallen/errcmp.html

In terms of the proper way to handle it, you may find the way that CFNetwork applies. Please take a look at _SocketStreamRead in CFSocketStream.c http://www.opensource.apple.com/source/CFNetwork/CFNetwork-129.13/Stream/CFSocketStream.c

The idea of the handling is not to treat EAGAIN as a normal error. Instead, by clearing the read flag and continue the loop, the procedure will eventually leads to a POSIX Error 110. With this error, you can do the recovery from the upper stream level.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜