[英]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.
它第一次工作,而第二次失败。
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
int dup2(int oldfd, int newfd);
If
oldfd
is a valid file descriptor, andnewfd
has the same value as oldfd, thendup2()
does nothing, and returnsnewfd
.如果
oldfd
是有效的文件描述符,并且newfd
与newfd
具有相同的值,则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. 这就是
oldFD
和newFD
变为相同的方式,从而产生错误。
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.