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);
         }
}

你可能感兴趣的:(Linux无名管道编程)