程序代码:
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
void sig_chld(int); /* prototype for our SIGCHLD handler */
int main(void) {
struct sigaction act;
pid_t pid;
/* Assign sig_chld as our SIGCHLD handler */
act.sa_handler = sig_chld;
/* We don't want to block any other signals in this example*/
sigemptyset(&act.sa_mask);
/*
* We're only interested in children that have terminated,
* not ones which have been stopped(eg user pressing
* control-Z at terminal)
*/
act.sa_flags= SA_NOCLDSTOP;
/*
* Make these values effective. If we were writng
* a real application, we would probably save
* the old value instead of passing NULL.
*/
if( sigaction(SIGCHLD, &act, NULL) < 0) {
fprintf(stderr, "sigaction failed\n");
return 1;
}
/* Fork */
switch(pid = fork()) {
case -1:
fprintf(stderr, "ford failed\n");
return 1;
case 0: /* child-- finish straight away */
_exit(7) /* exit status = 7 */
default: /* parent */
sleep(10); /* give child time to finish */
}
return 0;
}
/*
* The signal handler function -- only gets called when
* a SIGCHLD is received, ie when a child terminate
*/
void sig_chld(int sigo) {
int status, child_val;
/* Wait for any child without blocking */
if(waitpid(-1, &status, WNOHANG) < 0) {
/*
* calling standard I/O functions like
* fprintf() in a signal handler is not
* recommended, but probably OK in
* toy programs like this one.
*/
fprintf(stderr, "waipid failed\n");
return;
}
/*
* We now have the info in 'status' and
* and manipulate it using the macros in
* wait.h.
*/
if(WIFEXITED(status)) {
child_val = WEXITSTATUS(status);
printf("child's exited normally with status %d\n", child_val);
}
}
程序执行结果就是立刻显示
child's exited normally with status 7
[ 本帖最后由 madfrogme 于 2012-8-10 20:50 编辑 ]