How does C judge the tcp socket is closed? on the other end?

< H1 > current solution < / H1 >
// server
bool is_server_disconnected(int client_socket)
{
    // 
    set_flag(client_socket, O_NONBLOCK);
    char buffer[10];
    int length = recv(client_socket, buffer, 10, 0);
    clr_flag(client_socket, O_NONBLOCK);
    return length == 0;
}

set client_socket to non-blocking, and then if recv returns 0, it means remote socket is closed.

When a stream socket peer has performed an orderly shutdown, the
return value will be 0 (the traditional "end-of-file" return).

Linux man

< H1 > other methods < / H1 >

tcp disconnect is not considered for the time being. I wonder if there is a simpler and better way?

Mar.18,2021

poll man
you can skip the system buffer to detect socket status, and you can easily supervise all child threads.

POLLHUP for closes normally
POLLERR for program failed

if you want to detect that the network cable is down, you can only send a heartbeat packet, SO_KEEPALIVE .

Menu