多进程(父子进程)中的管道通信

#include<stdio.h>

#include<stdlib.h>

#include<errno.h>

#include<unistd.h>

#include<sys/types.h>

#include<string.h>

int main(int argc,char** argv)

{

        static const char mesg[] = "Hello world!";

        int pipefd[2];//pipefd[0]:读端口  pipdfd[1]:写端口

        pid_t pid;

        char buf[BUFSIZ];

        size_t len,n;

        if(pipe(pipefd)<0)

                perror("pipe error");

        if((pid = fork())<0)   // fork创建子进程    parent:pid>0     child:pid =0

                perror("fork error");

        else if(pid>0){  //父进程

                printf("PIPE(parent):Read end = fd %d, Write end = fd%d\n",pipefd[0],pipefd[1]);

                close(pipefd[0]);  //关闭父进程管道读端口

                len = strlen(mesg);

                if(write(pipefd[1],mesg,len)!=len){ //写父进程管道

                        fprintf(stderr, "write failed :%s\n", strerror(errno));       

                        exit(1);

                }            

                printf("Write %s to pipe\n",mesg);

                close(pipefd[1]);

        }

        else{  //子进程

                 printf("PIPE(Child):Read end = fd %d, Write end = fd%d\n",pipefd[0],pipefd[1]);

                 close(pipefd[1]); //关闭子进程管道写端口

                 n = read(pipefd[0], buf, BUFSIZ);

                 buf[n] = '\0';

                 printf("Read :%s from pipe\n",buf);

                 close(pipefd[0]);

        }  

       exit(0);

}

建立一条从父进程到子进程的管道,需要在父进程中关闭管道的读端,在子进程中关闭管道的写端。

fork()后子进程先运行,由于此时管道无数据,子进程被阻塞。当父进程开始执行,并将数据写入管道后,子进程才运行,读出管道内数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值