//管道是父进程和子进程间单向的通信机制,即一个进程发送数据到管道,另一个进程从管道中读取数据。如果需要双向的通信机制则需要建立两个管道
//系统负责两件事情:一是写入管道的数据和读出管道的数据的顺序是相同的。
// 二是数据不会再管道中丢失,除非这个管道过早地退出。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void read_data(int pipes[])
{
int c;
int rc;
//关闭写的一端
close(pipes[1]);
//读数据并打印
while((rc=read(pipes[0],&c,1))>0){
putchar(c);
}
exit(0);
}
//父进程写数据
void write_data(int pipes[])
{
int c;
int rc;
//关闭读的一端
close(pipes[0]);
//从控制台读数据并向管道写数据
while((c=getchar())>0){
rc=write(pipes[1],&c,1);
if(rc==-1){
perror("Parent:write");
close(pipes[1]);
exit(1);
}
}
//关闭写一遍
close(pipes[1]);
exit(0);
}
int main(int argc,char *argv[])
{
int pipes[2];
pid_t pid; //fork返回的进程号
int rc;
//建立管道
rc=pipes(pipes);
if(rc==-1){
perror("pipe");
exit(1);
}
//建立子进程
pid=fork();
switch(pid){
//失败
case -1:
perror("fork");
exit(1);
//子进程
case 0:
read_data(pipes);
//不能到这里
//父进程
default:
write_data(pipes);
//不能到这里/
}
return 0;
}
转载于:https://my.oschina.net/liubin/blog/23816