#include <stdio.h>
#include <stdlib.h>
#include <sys/unistd.h>
#include <sys/wait.h>
#define PROSSESS_NUM 3
int main(int argc, char *argv[])
{
char * cmd[PROSSESS_NUM][PROSSESS_NUM] =
{
{"any", "11111111111", 0},
{"enjoyyouself", "22222222222", 0},
{"any", "33333333333", 0}
};
int i, j, status;
pid_t pid[PROSSESS_NUM] = {0};
pid_t wpid = 0;
unsigned char sta[PROSSESS_NUM];
for (i = 0; i < PROSSESS_NUM; i++)
sta[i] = 1;
for (i = 0; i < PROSSESS_NUM; i++)
{
if ((pid[i] = fork()) > 0)
{
printf("parent | child's pid=[%d]\n", pid[i]);
while (i == PROSSESS_NUM -1)
{
if (sta[0] == 0 && sta[1] == 0 && sta[2] == 0)
{
break;
}
for (j = 0; j < 3; j++)
{
if (sta[j])
{
wpid = waitpid(pid[j], NULL, WNOHANG); //指定回收一个pid的进程
if (wpid == -1)
{
perror("waitpid error : ");
exit(1);
}
else if (wpid == pid[j])
{
printf("EXIT : pid=[%d]\n", pid[j]);
sta[j] = 0;
}
}
}
}
}
else
{
printf("----------------child | pid [%d]\n", getpid());
execv("/bin/echo",cmd[i]);
exit(EXIT_SUCCESS);
}
}
return EXIT_SUCCESS;
}
[C]for循环创建多进程execv并waitpid指定子进程退出
最新推荐文章于 2024-05-29 21:29:09 发布