The Linux Programming Interface

(nextflipdebug5) #1
Monitoring Child Processes 547

if (msg != NULL)
printf("%s", msg);


if (WIFEXITED(status)) {
printf("child exited, status=%d\n", WEXITSTATUS(status));


} else if (WIFSIGNALED(status)) {
printf("child killed by signal %d (%s)",
WTERMSIG(status), strsignal(WTERMSIG(status)));
#ifdef WCOREDUMP / Not in SUSv3, may be absent on some systems /
if (WCOREDUMP(status))
printf(" (core dumped)");
#endif
printf("\n");


} else if (WIFSTOPPED(status)) {
printf("child stopped by signal %d (%s)\n",
WSTOPSIG(status), strsignal(WSTOPSIG(status)));


#ifdef WIFCONTINUED / SUSv3 has this, but older Linux versions and
some other UNIX implementations don't
/
} else if (WIFCONTINUED(status)) {
printf("child continued\n");
#endif


} else { / Should never happen /
printf("what happened to this child? (status=%x)\n",
(unsigned int) status);
}
}
––––––––––––––––––––––––––––––––––––––––––––––– procexec/print_wait_status.c


The printWaitStatus() function is used in Listing 26-3. This program creates a child
process that either loops continuously calling pause() (during which time signals
can be sent to the child) or, if an integer command-line argument was supplied,
exits immediately using this integer as the exit status. In the meantime, the parent
monitors the child via waitpid(), printing the returned status value and passing this
value to printWaitStatus(). The parent exits when it detects that the child has either
exited normally or been terminated by a signal.
The following shell session shows a few example runs of the program in
Listing 26-3. We begin by creating a child that immediately exits with a status of 23:


$ ./child_status 23
Child started with PID = 15807
waitpid() returned: PID=15807; status=0x1700 (23,0)
child exited, status=23

In the next run, we start the program in the background, and then send SIGSTOP and
SIGCONT signals to the child:


$ ./child_status &
[1] 15870
$ Child started with PID = 15871
Free download pdf