使用dup2从文件到另一个文件

时间:2015-04-29 12:37:25

标签: c linux shell dup2

我正在尝试执行命令sort< in.txt> out.txt,所以我使用的是dup2。 这是我的代码:

    int fdin = open("in.txt",O_RDWR);
    int fdout = open("out.txt",O_RDWR);

    dup2(fdin,fdout);
    //close(fdin);
    //close(fdout);
    //execvp...

dup2究竟是如何工作的?我无法得到它...... 谢谢!

1 个答案:

答案 0 :(得分:0)

您使用它的方式会再次关闭fdout,删除与fdout的连接,然后将其连接到fdin。因此,如果fdinfdout可能是4和5,则4和5现在都指向in.txt

而不是那样,你应该做像

这样的事情
dup2(fdin, 0) // now 0 will point to the same as fdin
dup2(fdout, 1) // now 1 will point to the same as fdout
close(fdin); // as we don't need these any longer - if they are not 0 or 1! That should be checked.
close(fdout);
execvp(...);

然而,还有一些其他陷阱需要注意。例如,如果您希望您的流程能够继续执行它的工作,那么您应该在此之前fork()

为何在close()以上的评论?好吧,当你的进程没有fd 0和/或1开放时(什么是不寻常的,但并非不可能),fdin可能是0或1而fdout可能是1.这些情况你有应付。

更好的方法是

if (fdin > 0) {
    dup2(fdin, 0); // now 0 will point to the same as fdin
    close(fdin);
}
if (fdout > 1) { // cannot be 0!
    dup2(fdout, 1) // now 1 will point to the same as fdout
    close(fdout);
}
execvp(...);