C 从文件到另一个文件使用dup2
我正在尝试执行命令sortC 从文件到另一个文件使用dup2,c,linux,shell,dup2,C,Linux,Shell,Dup2,我正在尝试执行命令sortout.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,删除它与f
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(...);
然而,还有其他一些陷阱需要注意。例如,如果您希望您的流程继续执行它所做的事情,那么您应该在这一步之前进行分叉
为什么在上面的结尾处发表这样的评论?好的,当您的进程没有fd0和/或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(...);
是的,我的朋友,这就是我之所以在这里发帖的原因,因为我觉得很难理解。我正在使用你推荐的,但仍然不起作用。我在评论中加上了结束语,因为我真的不知道什么时候结束它们。顺便说一下,我以前用过叉子。即使使用代码,程序也会在屏幕上输出in.txt的排序内容