<aside>
💡 wait()
等待任意一个子进程结束,任意一个子进程结束时,此函数会回收子进程的资源
</aside>
参数
int *wstatus
:一个传出参数,传入一个int类型的地址,获取进程退出时的状态信息
返回值
调用wait函数的进程会被挂起(阻塞)
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
// 有一个父进程,创建5个子进程(兄弟)
pid_t pid;
// 创建5个子进程
for (int i = 0; i < 5; i++)
{
pid = fork();
// 避免子进程进一步产生子进程
if (pid == 0)
{
break;
}
}
if (pid > 0)
{
// 父进程
while (1)
{
printf("parent, pid = %d\\n", getpid());
// int ret = wait(NULL);
// st为接收子进程退出状态信息的传出参数
int st;
int ret = wait(&st);
// 没有子进程时父进程退出循环
if (ret == -1)
{
break;
}
if (WIFEXITED(st))
{
// 是不是正常退出
printf("退出的状态码:%d\\n", WEXITSTATUS(st));
}
if (WIFSIGNALED(st))
{
// 是不是异常终止
printf("被哪个信号干掉了:%d\\n", WTERMSIG(st));
}
printf("child die, pid = %d\\n", ret);
sleep(1);
}
}
else if (pid == 0)
{
// 子进程
// 子进程循环执行,之后通过kill指令杀死
while (1)
{
printf("child, pid = %d\\n", getpid());
sleep(1);
}
exit(0);
}
return 0; // exit(0)
}
<aside>
💡 waitpid
回收指定进程号的子进程,可以设置是否阻塞
</aside>