#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
for (int i = 0; i < 5; i++)
{
pid = fork();
if (pid == 0)
break;
}
if (pid > 0)
{
while (1)
{
sleep(1);
printf("PARENT, pid: %d\n", getpid());
int st;
int ret = waitpid(-1, &st, WNOHANG);
if (ret == -1)
{
break;
}
else if (ret == 0)
{
continue;
}
else if (ret > 0)
{
if (WIFEXITED(st))
{
printf("退出的状态码是: %d\n", WEXITSTATUS(st));
}
if (WIFSIGNALED(st))
{
printf("被 %d 信号终止了\n", WTERMSIG(st));
}
printf("child dead, pid = %d\n", ret);
}
}
}
if (pid == 0)
{
while (1)
{
sleep(1);
printf("CHILD, pid: %d\n", getpid());
}
}
return 0;
}
|