Skip to content
Advertisement

issues using waitpid() with large number of child process

I have a c program to create a TCP socket and keep waiting for a connection in an infinite loop. Each time a client connected to the program, I would spawn a new child process to handle the client request. My program could only exit with signal interrupt (e.g. ctrl+c).

I don’t want the parent process hanging there and wait for a child and I hope they could work simultaneously. What the parent process should do after forking is to check if any children have finished, and if so, clean them up.

currently my approach is(no error checking at here to save space, there are a lot of error checking in my real code):

if (fork()==0){
    /* Child process. */
}
else{
    close(client);    /* <- Cut down the connection from parent with the client. */
    waitpid(0, &status_exit, WNOHANG|WUNTRACED);
    child_spawn++;    /* One parent int variable to count total number of child process. */
}

But this rise another issue, since the parent will always hang and waiting for a connection, there could always be one or two previous finished child process that cannot be cleaned up until the parent could fork another and clean them up.

Even though my program could clean every zombie once it receives a signal interrupt before exit, but I want it to clean up every finished child by itself.

Please help me with this, thanks. If I have anything that’s not clarified, please leave a comment so I could explain.

Advertisement

Answer

The best thing you can do is for the parent to wait in a loop of accept(2) calls, accepting the incoming connections of the clients and forking children to attend the connections. Register a signal handler for the SIGCHLD signal that simply makes a wait(2) call and queues the exit code on some queue for the parent process to handle when it has the time to do so. For example, the parent can accept a connection, fork a child and process all the exit codes enqueued by the interrupt handlers to clean the children data. After that, it comes back to accept(2) to welcome the new client.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement