linux 循环fork并等待其结束

来源:互联网 发布:智能遥控器软件 编辑:程序博客网 时间:2024/06/12 08:57

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.

0 0
原创粉丝点击