实现代码:
1 #include2 #include 3 #include 4 #include 5 int main(int argc,char const *argv[]) 6 { 7 pid_t pid; 8 int fd[2]; 9 pipe(fd); 10 pid=fork(); 11 if(pid==-1) 12 { 13 perror("fail to fork"); 14 exit(1); 15 } 16 if(pid==0) 17 { 18 while(1) 19 { 20 char str_son[10]; 21 fgets(str_son,10,stdin); 22 //这里也可以用read从终端读取数据:read(0,str,10); 23 printf("ths son str is %sn",str_son); 24 write(fd[1],str_son,10);//向管道写入数据 25 } 26 } 27 else 28 { 29 while(1) 30 { 31 char str_par[10]; 32 read(fd[0],str_par,10);//从管道读取数据 33 printf("the parent str is %sn",str_par); 34 } 35 } 36 }
运行结果:
hello ths son str is hello the parent str is hello ^C
这里输出后有两次换行,一次是代码里写着的'/n',另一次是在终端按下回车后产生的,fegts会把回车符按字符存储起来。



