栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux编程练习:利用无名管道实现父进程从管道读取数据,子进程从终端设备上向管道写入数据。

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux编程练习:利用无名管道实现父进程从管道读取数据,子进程从终端设备上向管道写入数据。

实现代码: 

  1 #include
  2 #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会把回车符按字符存储起来。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/741686.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号