如何恢复被dup2覆盖的stdin?

Yi *_*Liu 4 c unix file-descriptor dup2

我试图用另一个管道替换stdin,然后将原始stdin放回到fd#0.

例如

dup2(p, 0); // p is a pre-existing fd of a pipe
exec(/* some commands */);

//what will be here in order to have the original stdin back?

scanf(...) //continue processing with original stdin.
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 5

一旦被覆盖(关闭),您就无法恢复原始状态.您可以做的是在覆盖它之前保存它的副本(当然需要提前计划):

int old_stdin = dup(STDIN_FILENO);

dup2(p, STDIN_FILENO);
close(p);               // Usually correct when you dup to a standard I/O file descriptor.

…code using stdin…

dup2(old_stdin, STDIN_FILENO);
close(old_stdin);       // Probably correct
scanf(…);
Run Code Online (Sandbox Code Playgroud)

但是,您的代码提到exec(…some commands…);- 如果这是POSIX execve()系列函数之一,那么除非调用失败,否则您将无法到达scanf()(或第二个dup2())调用exec*().