3

If I got a file descriptor (socket fd), how to check this fd is avaiable for read/write? In my situation, the client has connected to server and we know the fd. However, the server will disconnect the socket, are there any clues to check it ?

Akshit Khurana
  • 594
  • 5
  • 14
qrtt1
  • 7,276
  • 8
  • 37
  • 56

5 Answers5

4

You want fcntl() to check for read/write settings on the fd:

#include <unistd.h>
#include <fcntl.h>

int    r;

r = fcntl(fd, F_GETFL);
if (r == -1)
        /* Error */
if (r & O_RDONLY)
    /* Read Only */
else if (r & O_WRONLY)
    /* Write Only */
else if (r & O_RDWR)
    /* Read/Write */

But this is a separate issue from when the socket is no longer connected. If you are already using select() or poll() then you're almost there. poll() will return status nicely if you specify POLLERR in events and check for it in revents.

If you're doing normal blocking I/O then just handle the read/write errors as they come in and recover gracefully.

dwc
  • 21,894
  • 6
  • 41
  • 54
0

You can use select() or poll() for this.

qrdl
  • 31,423
  • 13
  • 52
  • 82
0

In C#, this question is answered here

In general, socket disconnect is asynchronous and needs to be polled for in some manner. An async read on the socket will typically return if it's closed as well, giving you a chance to pick up on the status change quicker. Winsock (Windows) has the ability to register to receive notification of a disconnect (but again, this may not happen for a long time after the other side "goes away", unless you use some type of 'keepalive' (SO_KEEPALIVE, which by default may not notice for hours, or an application-level heartbeat).

Community
  • 1
  • 1
jesup
  • 6,220
  • 23
  • 30
0

I found the recv can check. when socket fd is bad, some errno is set.

ret = recv(socket_fd, buffer, bufferSize, MSG_PEEK); 
if(EPIPE == errno){
// something wrong
}
qrtt1
  • 7,276
  • 8
  • 37
  • 56
-1

Well, you could call select(). If the server has disconnected, I believe you'll eventually get an error code returned... If not, you can use select() to tell whether you're network stack is ready to send more data (or receive it).

dicroce
  • 41,038
  • 26
  • 94
  • 136
  • I think `select` may trigger the *exceptfds* argument if the remote end disconnected, but not return any error. – Ben Voigt Apr 12 '11 at 12:53