#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()后子进程先运行,由于此时管道无数据,子进程被阻塞。当父进程开始执行,并将数据写入管道后,子进程才运行,读出管道内数据。