qfedu-linux-advanced-level/day2/d9.c

43 lines
1.1 KiB
C
Raw Permalink Normal View History

2023-08-15 19:05:13 +08:00
#include <stdio.h> // perror
#include <sys/types.h> // pid_t
#include <unistd.h> // fork
#include <sys/wait.h> // wait
int main(int argc, char const *argv[])
{
int pid = fork();
if (pid < 0)
{
perror("fork");
return -1;
}
if (pid == 0)
{
printf("%d 子进程准备睡眠 3 秒\n", getpid());
sleep(3);
printf("%d 子进程结束", getpid());
return 10;
}
else
{
// status 用来保存子进程的退出状态
int status;
int pid2 = waitpid(pid, &status, WUNTRACED); // 等待子进程结束
printf("\n%d 父进程中, 等到了子进程 %d 结束, status = %d \n", getpid(), pid, status >> 8);
// WIFEXITED(status) 为真表示子进程正常退出
if (WIFEXITED(status) & 0xff00 >> 8) // 子进程是否正常退出
{
// WEXITSTATUS(status) 获取子进程的退出码
printf("%d", WEXITSTATUS(status));
}
else
{
printf("子进程异常退出, status = %d", status >> 8);
}
}
return 0;
}