通过(匿名)管道实现进程间通信

做实验的时候写的代码,有问题请指教.
运行的环境:WSL Ubuntu 18.04.4 LTS \n \l

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

#define ReadEnd  0
#define WriteEnd 1

void report_and_exit(const char* msg) {
  perror(msg);
  exit(-1);    /** failure **/
}

int main() {
    int pipe_fd[2];       
    char w_buffer[100],r_buffer[100];  
    pid_t cpid;

    //创建管道
    if (pipe(pipe_fd) < 0) 
        report_and_exit("pipefd");
    
    for(int i=0;i<2;i++){
        if((cpid=fork())==0){
            close(pipe_fd[ReadEnd]);
            sprintf(w_buffer,"Child %d process is sending message!\n",i+1);
            write(pipe_fd[WriteEnd],w_buffer,strlen(w_buffer));
            exit(0);
        }
        else if(cpid>0){                    //父进程执行序列
            waitpid(cpid,NULL,0);           //父子进程同步
            printf("pid%d:%d\n",i+1,cpid);        
        }

    }
    //不能在循环里就关闭写通道,不然第二个子进程无法向管道写入数据
    close(pipe_fd[WriteEnd]);   
    while(read(pipe_fd[0],r_buffer,sizeof(r_buffer))>0){
        printf("%s\n",r_buffer);
    }
    return 0;    
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值