如以下代码所示:
/***************************************************************************** * Copyright : All Rights Reserved. * * Date : 2013-03-14 15:11:48 * Author/Corporation : Dengzhaoqun * Email : dengzhaoqun@163.com *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <errno.h> int main(int argc, char *argv[]) { pid_t pid; int stat; int exit_code; pid = fork(); if(pid == 0) { sleep(3); exit(5); } else if( pid < 0 ) { fprintf(stderr, "fork failed: %s", strerror(errno)); return -1; } wait(&stat); // 等待一个子进程结束 if(WIFEXITED(stat)) // 如果子进程通过 return, exit, _exit 正常结束, WIFEXITED() 返回 true { exit_code = WEXITSTATUS(stat); printf("child's exit_code: %d\n", exit_code); } return 0; }
参考: "man 2 wait"