1

I'm currently on pset6 and I'm trying to read through the code for server.c to understand what it's doing. I've come across part of the code that I don't understand:

/**
 * Checks (without blocking) whether a client has connected to server. 
 * Returns true iff so.
 */
bool connected(void)
{
    struct sockaddr_in cli_addr;
    memset(&cli_addr, 0, sizeof(cli_addr));
    socklen_t cli_len = sizeof(cli_addr);
    cfd = accept(sfd, (struct sockaddr*) &cli_addr, &cli_len);
    if (cfd == -1)
    {
        return false;
    }
    return true;
}

The comment for this function says that it checks whether a client has connected without blocking, but I don't understand how it's doing that; as far as I understand, the socket has to be made into a non-blocking one by setting the O_NONBLOCK flag on with fcntl(), but nowhere in the code (as far as I could see) was sfd set to nonblocking. Can someone explain to me, then, why accept() doesn't just block connected() until the client connects to the server?

Any help would be much appreciated

1

I think this (found in this article) explains it:

Programs that use non-blocking I/O tend to follow the rule that every function has to return immediately, i.e. all the functions in such programs are nonblocking.

So "without blocking" describes the check itself, i.e. the function returns immediately. It doesn't mean the socket is non-blocking.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .