您的位置:首页 > 运维架构 > Linux

linux 循环fork并等待其结束

2015-12-13 10:43 666 查看
fork子进程,在父进程里等待其结束,然后再fork下一个子进程,如此循环往复!

/* description: fork child process.
*
*
* date : 2015/11/15
*
*
*/

#include <stdio.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
struct timeval tvbegin, tvend;
gettimeofday(&tvbegin, NULL);

int i;
for(i = 1; i <= 3; i++)
{
//-----------------fork child process
int status;
int child = fork();
if(child == -1)
{
printf("error\n");
}
else if(child == 0)
{
printf("---Child %d began.\n", i);
exit(0);
}
else
{
pid_t ret;
do
{
ret = waitpid(child, &status, WNOHANG);
printf("Parent waiting...\n");
usleep(1000);
} while (ret == 0);

printf("Child %d (pid:%d) ended.\n", i, child);
}
}

gettimeofday(&tvend, NULL);
printf("cost %d ms.\n", (tvend.tv_sec-tvbegin.tv_sec)*1000+(tvend.tv_usec-tvbegin.tv_usec)/1000);

return 0;
}


运行结果

[root@localhost training]# ./test

Parent waiting…

—Child 1 began.

Parent waiting…

Child 1 (pid:2795) ended.

Parent waiting…

—Child 2 began.

Parent waiting…

Child 2 (pid:2796) ended.

Parent waiting…

—Child 3 began.

Parent waiting…

Child 3 (pid:2797) ended.

cost 7 ms.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: