循环创建多个子进程并回收进程资源
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
int main(int argc, char *argv[])
{
int i;
pid_t pid, wpid, tpid;
for(i=0; i<5; i++)
{
pid = fork();
if(pid == 0) break;
if(i == 2) tpid = pid;
}
if(5 == i)
{
sleep(5);
wpid = waitpid(tpid, NULL, WNOHANG);
if(wpid == -1)
{
perror("waitpid error");
exit(1);
}
printf("I am parent, wait a child finish: %d\n", wpid);
}
else
{
sleep(i);
printf("%d my pid:%d\n", i, getpid());
}
return 0;
}
执行结果
0 my pid:9223
1 my pid:9224
2 my pid:9225
3 my pid:9226
4 my pid:9227
I am parent, wait a child finish: 9225