如以下代码所示:
#include
#include
#include
#include
#include
#include
#include
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"