You need to enable non-blocking behavior, by setting O_NONBLOCK
using fcntl
. One easy but non-standard way to do a non-blocking read would be to use:
recv(sock, &buf, 1, MSG_PEEK | MSG_DONTWAIT);
Afterwards, you must check errno if it fails. It can fail with EAGAIN
or it can fail with EBADF
or ENOTCONN
etc.
Obviously, the simplest and cleanest way to deal with this would be to avoid "forgetting" if the socket is connected or not. You'll notice if the socket becomes disconnected once a recv
returns 0 or a send
returns EPIPE
.