Check Socket File Descriptor?

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

+3
source share
5 answers

You want to fcntl()check read / write settings on 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 when the socket is no longer connected. If you are already using select()or poll(), then you are almost there. poll()will return the status beautifully if you point POLLERRin eventsand check it in revents.

-, / .

+4

select() poll().

0

#

- . , , , , . Winsock (Windows) ( , , "", - "keepalive" (SO_KEEPALIVE, ).

0

, recv . fd , errno.

ret = recv(socket_fd, buffer, bufferSize, MSG_PEEK); 
if(EPIPE == errno){
// something wrong
}
0

Well, you can call select (). If the server is down, I believe that you will eventually receive the error code returned. If not, you can use select () to indicate whether the network stack is ready to send more data (or receive it).

-1
source

Source: https://habr.com/ru/post/1708813/


All Articles