Is it necessary to use a lock for the accept function when doing socket programming?

333 views Asked by At

I have created a preforking web server which creates the server socket, binds it, listens to an address and port and it preforks a specified number of workers (child processes) which act as workers serving client requests.

All workers inherit the socket descriptor of the parent server and use it to accept client requests. Child processes run as autonomous processes at "parallel" and use accept function with server socket descriptor. Do I have to use lock and unlock mechanism for the accept function when accepting a client request or the operating system does this for me? The idea is here that multiple processes use the common server socket descriptor for accepting client requests. Do I have to shield this with a mutual exclusion mechanism to avoid race conditions or deadlocks?

Please take account that I use I/O nonblocking in the accept function.

I have the following code:

for(;;) {
    int client = accept(...);
    if (client < 0) continue;
    ...
}

Should I use something like:

for(;;) {
    lock();
    int client = accept(...);
    unlock();
    if (client < 0) continue;
    ...
}

??

1

There are 1 answers

4
user207421 On BEST ANSWER

No. It's a system call, and therefore atomic.