重复的文件描述符指向管道

时间:2013-11-17 23:07:45

标签: c file-descriptor

我的程序会选择一个随机数,并猜测它是什么。我几乎完成了它,除了我需要复制文件描述符指向管道,我不完全确定如何做到这一点。我想我必须使用dup2,但我不完全确定如何实现它。一切都有帮助。到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int pid;
  int n;
  char buf[101];
  int pfdA[2];
  int pfdB[2];

  // CREATE FIRST PIPE
  if (pipe(pfdA) == -1)
  {
    perror("pipe failed");
    exit(-1);
  }

  // CREATE SECOND PIPE
  if (pipe(pfdB) == -1)
  {
    perror("pipe failed");
    exit(-1);
  }

  // FORK()
  if ((pid == fork()) < 0)
  {
    perror("fork failed");
    exit(-2);
  }

  if (pid == 0)
  {
    // duplicate file descriptor 0 to point to FIRST pipe

    // CLOSE ends of FIRST pipe you don't need anymore
    close(pfdA[0]);
    close(pdfA[1]);

    // duplicate file descriptor 1 to point to SECOND pipe

    // CLOSE ends of SECOND pipe you don't need anymore
    close(pfdB[0]);
    close(pfdB[1]);

    execlp("./A5_CHILD", "./A5_CHILD", (char *) 0);
    perror("execlp");
    exit(-3);
  }

  else
  {

    while (1)
    {
      char NUM[100];
      close(pfdA[0]);
      close(pfdB[1]);

      int r = 0;

      printf("Enter a Number: ");
      fflush(stdout);
      scanf("%s", NUM);

      // SEND   NUM   to Child process
      write(pdfA[1], NUM, strlen(NUM));

      // READ FROM CHILD THE RESPONSE into the variable buf and
      //      store the return value from read() into the variable r
      r = read(pfdB[0], buf, 100);

      if (r > 0)
      {
        buf[r] = '\0';
        printf("%s\n", buf);
        fflush(stdout);
      }
      else
      {
        printf("[PARENT] Reading from child: read() returned %d\n", r);
        break;
      }
    }
  }

  return (0);
}

1 个答案:

答案 0 :(得分:0)

  

我认为我必须使用dup2,但我并不完全确定如何使用   实施它。

你是对的。

    // duplicate file descriptor 0 to point to FIRST pipe
    dup2(pfdA[0], 0);

...

    // duplicate file descriptor 1 to point to SECOND pipe
    dup2(pfdB[1], 1);