进程间pipe通信

开始循环fork子进程,每个子进程等待前一个子进程结束后才结束

/* description: communicate between child process and parent processes
 *
 * fork every child process and arrange them being ended in order.
 *
 * date : 2015/11/23 
 *
 *
*/


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


int number = 3;
//-----------------for pipe communication
char cmdBegin[10] = "begin";
char cmdEnd[10] = "end";


int main(int argc, char *argv[])
{

    // calculate running time
    struct timeval tvbegin, tvend;
    gettimeofday(&tvbegin, NULL);

    //-----------------pipe
    int (* fd) [2] = (int (*)[2]) malloc (sizeof(int) * 2 * number);
    if(pipe(fd[0]) < 0)
    {
        printf("pipe [0] error\n");
        exit(1);
    }
    write(fd[0][1], cmdEnd, strlen(cmdEnd));

    int iChild;
    for(iChild = 0; iChild < number; iChild++)
    {
        if(pipe(fd[iChild]) < 0)
        {
            printf("pipe [%d] error\n", iChild);
            exit(1);
        }


        int child = fork();
        if(child == -1)
        {
            printf("fork [%d] child process error\n", iChild);
        }
        else if(child == 0)
        {
            printf ("----child:%d began.\n", iChild + 1);



            //-----------------wait the front child process to end
            if(iChild > 0)
            {
                close(fd[iChild - 1][1]);
                char cmd [10] = {0};
                read(fd[iChild - 1][0], cmd, sizeof(cmd));
                while(strcmp(cmd, cmdEnd) != 0)
                {
                    usleep(10);
                    read(fd[iChild - 1][0], cmd, sizeof(cmd));
                }
            }
            //-----------------write the pipe
            close(fd[iChild][0]);
            write(fd[iChild][1], cmdEnd, strlen(cmdEnd));


            printf ("----child:%d ended.\n", iChild + 1);
            exit(0);
        }
    }


    //-----------------wait the last child process to end
    close(fd[iChild - 1][1]);
    char cmd [10] = {0};
    read(fd[iChild - 1][0], cmd, sizeof(cmd));
    while(strcmp(cmd, cmdEnd) != 0)
    {
        usleep(10);
        read(fd[iChild - 1][0], cmd, sizeof(cmd));
    }

    printf ("all complete!\n");


    free(fd);

    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
—-child:2 began.
—-child:3 began.
—-child:1 began.
—-child:1 ended.
—-child:2 ended.
—-child:3 ended.
all complete!
cost 2 ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值