If I am correct, a process waits for its children to terminate or stop by calling the waitpid() or wait() function.
What is the relation between SIGCHLD signal and the waitpid() orwait() functions?
Is it correct that when a process calls the
waitpid()orwait()functions, the process suspends itself until a child process terminates/stops, which is the same as until a SIGCHLD signal is sent to it?(
pause()suspends the current process until any signal is sent to it. So I wonder ifwaitpid()is similar, except that until SIGCHLD is sent to it?)When SIGCHLD is sent to a process which has been suspended by calling
waitpid(), what is the order between executing SIGCHLD handler and resuming from suspension bywaitpid()?
( In the following example from Computer Systems: a Programmer's Perspective, the SIGCHLD handler callswaitpid().)
Thanks.
void handler(int sig)
{
int olderrno = errno;
while (waitpid(-1, NULL, 0) > 0) {
Sio_puts("Handler reaped child\n");
}
if (errno != ECHILD)
Sio_error("waitpid error");
Sleep(1);
errno = olderrno;
}
int main()
{
int i, n;
char buf[MAXBUF];
if (signal(SIGCHLD, handler1) == SIG_ERR)
unix_error("signal error");
/* Parent creates children */
for (i = 0; i < 3; i++) {
if (Fork() == 0) {
printf("Hello from child %d\n", (int)getpid());
exit(0);
}
}
/* Parent waits for terminal input and then processes it */
if ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0)
unix_error("read");
printf("Parent processing input\n");
while (1)
;
exit(0);
}