/*
* function: 演示wait函数阻塞回收子进程
*
* pid_t wait(int *status); // 成功:清理掉的子进程 ID;失败: -1 (没有子进程)
*
* 三组宏函数:
* 1. WIFEXITED(status) 为非 0 → 进程正常结束
* WEXITSTATUS(status) 如上宏为真,使用此宏 → 获取进程退出状态 (exit 的参数)
*
* 2. WIFSIGNALED(status) 为非 0 → 进程异常终止
* WTERMSIG(status) 如上宏为真,使用此宏 → 取得使进程终止的那个信号的编号。
*
* *3. WIFSTOPPED(status) 为非 0 → 进程处于暂停状态
* WSTOPSIG(status) 如上宏为真,使用此宏 → 取得使进程暂停的那个信号的编号。
* WIFCONTINUED(status) 为真 → 进程暂停后已经继续运行
*
* 2020-12-01
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid = 0;
pid = fork();
if (pid < 0)
{
perror("fork faild");
exit(1);
}
else if (pid > 0) // 父进程
{
int status = 0;
printf("my Chile pid = %d\n", pid);
wait(&status); // 阻塞回收子进程同时关心子进程回收状态
if (WIFEXITED(status)) //
{
printf("子进程正常退出状态: %d\n", WEXITSTATUS(status));
}
if (WIFSIGNALED(status))
{
printf("子进程异常退出状态: %d\n", WTERMSIG(status));
}
printf("回收子进程成功\n");
}
else // 子进程
{
sleep(10);
printf("Child sleep 10s\n");
printf("I'm Child and I'm go to die\n");
}
return 98;
}
1.正常退出子进程

2.异常退出子进程

博客主要围绕子进程退出情况展开,包含正常退出子进程和异常退出子进程两方面内容,涉及 Linux、Unix 系统相关知识。
2818

被折叠的 条评论
为什么被折叠?



