socket accept() keeps looping

I'm using C/ C++ with gcc on Linux. I've a server socket where accept() is called on the socket inside a while() loop. The problem I am facing is that the first call to accept is blocking (i.e., the program waits for the first connection) but as soon as I fork afterwards (so that the child process can handle the communication of the new socket), and come back to the accept() call in the parent, accept() starts returning -1 as if it was a non-blocking call.

Can anyone explain the scenario? What could be the possible reasons for accept() to return -1?

A list of possible reasons is given in the man page for man accept (POSIX). What does man perror (POSIX) output?

1 Like

Thanks! I am new to *nix programming and didn't know the useful perror. It was giving me "Bad file descriptor", which hinted me that something was wrong with the socket I was passing to accept(). And then it dawned upon me that I was closing the socket in the child process. Problem solved.