Linux无名管道编程

 无名管道只能用于父子进程间通信,pipe函数用一个数组作参数,数组fd中fd[0]用于读,fd[1]用于写。代码如下:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>

int main()
{
  int pipe1_fd[2], pipe2_fd[2];

      char * parent_talks[] = {"Hi, my baby","Can you tell daddy date and time?","Daddy have to leave here, bye!",NULL};
      char * child_talks[] = {"Hi, daddy","Sure,","Bye!",NULL};

      char parent_buf[256], child_buf[256];
      char * parent_ptr, * child_ptr;

      int i,j, len;
      int child_status;
      time_t curtime;

  if(pipe(pipe1_fd) < 0)
  {
   printf("pipe1 create error/n");
         return -1;
         }

  if(pipe(pipe2_fd) < 0)
         {
       printf("pipe2 create error/n");
       return -1;
         }

      if(fork() == 0)   //child
         {
       //pipe1_fd[0] is used to read, pipe2_fd[1] is used to write
         close(pipe1_fd[1]);
         close(pipe2_fd[0]);

         i = 0;
         child_ptr = child_talks[i];
         while(child_ptr != NULL)
                 {
          len = read(pipe1_fd[0],child_buf,255);
            child_buf[len] = '/0';
            printf("Parent: %s/n",child_buf);

            if(i == 1)
    {
             time(&curtime);
               len = sprintf(child_buf, "%s %s", child_ptr, ctime(&curtime));
               child_buf[len-1] = '/0';
               write(pipe2_fd[1],child_buf,strlen(child_buf));
                         }
            else
    {
             write(pipe2_fd[1],child_ptr,strlen(child_ptr));
                         }
          
    child_ptr = child_talks[++i];
                 }

         close(pipe1_fd[0]);
         close(pipe2_fd[1]);
         exit(0);
         }
      else   //parent
  {
       //pipe1_fd[1] is used to write, pipe2_fd[0] is used to read
         close(pipe1_fd[0]);
         close(pipe2_fd[1]);

         j = 0;
         parent_ptr = parent_talks[j];
         while(parent_ptr != NULL)
   {
          write(pipe1_fd[1],parent_ptr,strlen(parent_ptr));
            len = read(pipe2_fd[0],parent_buf,255);
            parent_buf[len] = '/0';
            printf("Child: %s/n", parent_buf);
            parent_ptr = parent_talks[++j];
                 }

         close(pipe1_fd[1]);
         close(pipe2_fd[0]);
         wait(&child_status);
         exit(0);
         }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值