使用 dup2 从文件到另一个文件
Using dup2 from file to another file
我正在尝试执行命令 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 究竟是如何工作的?我无法得到它...
谢谢!
您使用它的方式再次关闭 fdout
,删除它与 fdout
的连接,然后将其连接到 fdin
。因此,如果 fdin
和 fdout
可能是 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 and/or 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(...);
我正在尝试执行命令 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 究竟是如何工作的?我无法得到它... 谢谢!
您使用它的方式再次关闭 fdout
,删除它与 fdout
的连接,然后将其连接到 fdin
。因此,如果 fdin
和 fdout
可能是 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 and/or 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(...);