简体   繁体   English

从Linux C中的文件描述符重定向标准输入

[英]redirect stdin from file descriptor in linux c

I can't understand what's wrong with the following code. 我不明白以下代码有什么问题。 I perform exactly the same actions twice. 我两次执行完全相同的动作。 It works for the first time, and fails for the second. 它第一次工作,而第二次失败。

  1. open FD 开放FD
  2. duplicate to stdin. 复制到标准输入。
  3. close stdin 关闭标准输入
  4. close the original fd 关闭原始fd

At the second time I get an error, at stage 4, which means the FD is already closed. 第二次,在阶段4,我得到一个错误,这意味着FD已经关闭。

  int fd =open("/path/to/some/file",0,"r");
  if (dup2(fd,STDIN_FILENO)<0)
    perror("dup_in");
  if (close(STDIN_FILENO)<0)
    perror("close_in");
  if (close(fd)<0)
    perror("close_fd");

  //Up to here it works fine.

  fd =open("/path/to/some/file",0,"r");
  if (dup2(fd,STDIN_FILENO)<0)
    perror("dup_in2");
  if (close(STDIN_FILENO)<0)
    perror("close_in2");
  if (close(fd)<0) //<-- ERROR!
    perror("close_fd2"); //<--close_fd2: Bad file descriptor

As per the man page 按照手册页

int dup2(int oldfd, int newfd);

If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing, and returns newfd . 如果oldfd是有效的文件描述符,并且newfdnewfd具有相同的值,则dup2()不执行任何操作,并返回newfd

So, in your second case, open() uses the least available FD, 0 [free'd by last call to close() ]. 因此,在第二种情况下, open()使用的可用FD最少,为0 [最后一次调用close()释放的FD]。 That's how oldFD and newFD becomes the same, creating the error. 这就是oldFDnewFD变为相同的方式,从而产生错误。

Note: Before using the fd returned by open() , you should always verify the sucess of open() call. 注意:在使用open()返回的fd之前,您应该始终验证open()调用的成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM