管道

管道:俩个进程间进行单向通信的机制;pipe:无名管道 :父子进程;pipe[0]写端;pipe[1]读端;命名管道:无关系进程;

 1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<string.h>
  4 #include<unistd.h>
  5
  6 int main()
  7 {
  8     char *parent_talk[] = {"Hello", "Can you tell me, what is time?","OMG, i     have to go. Bye.",NULL};
  9     char *child_talk[] = {"Hi","No problem.","See you Again.",NULL};
 10
 11     int fd1[2];
 12     int fd2[2];
 13
 14     int res = pipe(fd1);
 15     if(res == -1)
 16     {
 17         printf("create pipe1 error.\n");
 18         exit(1);
 19     }
 20     res = pipe(fd2);
 21     if(res == -1)
 22     {
 23         printf("create pipe2 error.\n");
 24         exit(1);
 25     }
 26
 27     pid_t pid;
 28     pid = fork();
 29     if(pid == 0) //child
 30     {
 31         close(fd1[1]);
 32         close(fd2[0]);
 33
 34         char buf[256];
 35         int i = 0;
 36         char *talk = child_talk[i];
 37         while(talk != NULL)
38         {
 39             sleep(5);
 40             read(fd1[0],buf, 256);
 41             printf("Parent:> %s\n",buf);
 42             write(fd2[1],talk, strlen(talk)+1);
 43             i++;
 44             talk = child_talk[i];
 45         }
 46
 47         close(fd1[0]);
 48         close(fd2[1]);
 49     }
 50     else if(pid > 0)//parent
 51     {
 52         close(fd1[0]);
 53         close(fd2[1]);
 54
 55         char buf[256];
 56         int i = 0;
 57         char *talk = parent_talk[i];
 58         while(talk != NULL)
 59         {
 60             write(fd1[1], talk, strlen(talk)+1);
 61             read(fd2[0],buf,256);
 62             printf("Child:> %s\n",buf);
 63             i++;
 64             talk = parent_talk[i];
 65         }
 66
 67         close(fd1[1]);
 68         close(fd2[0]);
 69         int status;
 70         wait(&status);
 71     }
 72
 73     return 0;
 74 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值