Reputation:
I have some questions on creating and reaping child processes.
Q1. Why Linux automatically reap child processes so programmers don't need to use waitpid(), which reduces programmers'workload?
Q2. What are the benefits of creating child processes and let child processes to execute programs e.g. web servers calls fork to create a child process and calls execve to run cgi programs? can't we let the parent processes to run cgi programs?
Upvotes: 1
Views: 1480
Reputation: 9885
Q1. Linux (or UNIX in general) reaps child processes only if the parent process dies before the child. In this case the kernel lets some implementation defined process (which used to be the init
process) adopt the orphaned process. Then this new parent process will react on the processes state changes.
Q2. Forking and handling one task per process is one way of handling seveal tasks in parallel. Depending on your requirements this often leads to much simpler code than handling several tasks in one process. In some cases it's the only feasible way. Using threads is a similar solution. A different solution would be to use select
before all possibly blocking calls and to make sure you handle a piece of every task one by one.
Running CGI programs means you have to run a script interpreter. If you don't implement the interpreter yourself this means you have to run a separate program which is difficult to control. When the script takes a long time or blocks for some reason you don't want to block all other tasks. So it's easier to run it in a child process in parallel to accepting and handling requests in the parent or in other child processes. In this case it is difficult or often impossible to prevent the separate program from blocking the other tasks, so it's better to do this in a child process.
Upvotes: 1
Reputation: 11374
Linux doesn't auto reap processes as you may want to fork a child process and terminate the parent process, ie, daemon-izing a process. You also need a way to obtain the exit code of the child process, without this mechanisim there would be no way to obtain it. If you don't care to wait on the child process, when you start your application call signal(SIGCHLD, SIG_IGN);
before forking any children.
For the record windows has the same usage pattern, calling WaitForSingleObject
to wait on a child thread to terminate, which you can omit, but is very bad practice to do so as it leaves handles and return codes hanging in memory.
The parent process unless you use multi-threading can not execute more then a single task at a time. Forking a child process to handle the incoming request allows you to handle multiple requests asynchronously, for example: https://jameshfisher.com/2017/02/25/tcp-server-fork.html
Upvotes: 0