linux 循环fork并等待其结束

本文通过C语言实现了一个简单的父子进程循环示例,演示了如何使用fork创建子进程,并在父进程中等待每个子进程结束。该示例还展示了如何测量整个循环过程所消耗的时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值