C - 关闭管道并复制管道

  • 本文关键字:管道 复制 c linux pipe dup
  • 更新时间 :
  • 英文 :


我试图了解管道是如何工作的,当我在教科书中阅读这段代码时,这相当令人困惑。在行中

dup(fd2[0]); close(fd2[0]);

为什么我们要复制fd2[0],然后在复制后立即关闭它?

#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
  struct timespec ts1, ts2;
  pid_t newpid;
  int fd1[2], fd2[2];
  char m0[] = "nabout to fork....n";
  char m1[] = "message from parent to childn";
  char m2[] = "message from child to parentn";
  char m3[] = "ndone....n";
  char rbuf1[256];
  char rbuf2[256];
  int cn1, cn2;
  ts1.tv_sec=(time_t)1;
  ts1.tv_nsec=(long)1;
  ts2.tv_sec=(time_t)1;
  ts2.tv_nsec=(long)1;
  if ((pipe(fd1)==-1)) printf("errorn");
  if ((pipe(fd2)==-1)) printf("errorn");
  printf("fd1 %d %d fd2 %d %dn", fd1[0], fd1[1], fd2[0], fd2[1]);
  if ((newpid=fork()) ==-1) {
    printf("failed to forknn");
    return 0;
  }
  if (newpid > 0) { // parent ***************
    close(fd1[1]); close(fd2[0]); // closing 4 and 5
    dup(fd2[1]); close(fd2[1]); // taking 4 in place of 6
    write(4, m1, sizeof(m1)); // parent_to_child messg
    usleep(10000);
    cn1=read(3, rbuf1, 256);
    write(1, rbuf1, cn1);
  } else { // child ***************
    close(fd1[0]); close(fd2[1]); // closing 3 and 6
    dup(fd2[0]); close(fd2[0]); // taking 3 in place of 5
    write(4, m2, sizeof(m2)); // child_to_parent messg
    usleep(10000);
    cn2=read(3, rbuf2, 256);
    write(1, rbuf2, cn2);
  }
  write(2, m3, sizeof(m3));
  return 0;
}
但是

,您没有从dup()的手册页向我们展示您的代码

int dup(int oldfd);

dup() uses the lowest-numbered unused descriptor for the new descriptor.

这清楚地表明,dup()将为oldfd返回一个新的文件描述符。 您需要分配 dup() 的返回值才能获得新的fd。获取新fd后,您可以关闭旧fd并使用新返回的描述符访问该文件。

另一种常用的方法是关闭一个众所周知的文件描述符,然后调用dup(),它将最近关闭的fd分配为新的fd。[例 : STDIN_FILENO]

通常的顺序是在dup调用之前进行另一个close调用,或者分配dup的结果并使用它。

第一种变体是最常见的,例如,使用管道读取端作为您可以执行的新STDIN_FILENO

close(STDIN_FILENO);  // Close the current standard input descriptor
dup(pipefds[0]);      // Duplicate the pipe read-end, which will become our new standard input
close(pipefds[0);     // Close the old pipe descriptor, to save descriptor resources

这将起作用,因为dup将选择最低的可用描述符,在第一次close调用后将STDIN_FILENNO(描述符 0 )。

dup完全按照

它的意愿做,它会复制描述符,因此在调用 dup 后,您将有两个描述符引用相同的"文件",并且可以自由关闭其中一个。

我建议您阅读dup(2)手册页。

最新更新