进程间管道通信基础

练习:使用管道实现兄弟进程间通信。 兄:ls 弟: wc -l 父:等待回收子进程。
要求,使用“循环创建N个子进程”模型创建兄弟进程,使用循环因子i标示。注意管道读写行为


#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>


int main()
{
    int ret,i,num =2;
    int fd[2];
    pid_t pid,w_pid;
    int status;

    if ( -1 == (ret = pipe(fd) ))  
    {
        perror("pipe faile");
        exit(1);
    }
    for(i = 1; i < 3; i++)
    {
        pid = fork();
        if(0 == pid)
            break;
   }
//兄 写,弟 读
    if( 0 == pid )
    {
//兄
        if(1 == i)
        {
            close(fd[0]);
            dup2(fd[1],STDOUT_FILENO);//作为管道输入
            execlp("ls","ls",NULL);
        }
//弟
        if( 2 == i)
        {
            close(fd[1]);
            dup2(fd[0],STDIN_FILENO);
            execlp("wc","wc",NULL);
        }
    }
    else
    {
#if 0
        close(fd[0]);
        close(fd[1]);
        for(i=0; i<2; i++)
            wait(NULL);
#endif
#if 1
//轮循方式回收子进程
        do
        {
            close(fd[0]);
            close(fd[1]);
            w_pid = waitpid(-1,NULL,WNOHANG);
            if(w_pid > 0)
                num--;
        }while(num>0);
        printf("finished\n");
#endif
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值