c - 如何恢复被 dup2 覆盖的标准输入?

标签 c unix file-descriptor dup2

我正在尝试用另一个管道替换标准输入,然后将原始标准输入放回 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.

最佳答案

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

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(…);

但是,您的代码提到了 exec(...some commands...); — 如果那是 POSIX execve() 之一函数族,那么除非 exec*()调用失败。

关于c - 如何恢复被 dup2 覆盖的标准输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53924800/

相关文章:

c - 为什么下面的循环展开会导致错误的结果?

c - 函数中返回文件/文件夹结构的指针

shell - 重命名 UNIX 目录中的文件 - shell 脚本

linux - grep 函数中的最大计数无效

c - C 中的文件描述符分配

c++ - 为什么 UNIX 文件描述符不是由它们自己的类型实现的,尤其是在 C++ 中?

java - Android文件描述符泄漏调试

c - 具有更高粒度的 UNIX alarm()

检查命令行参数是否为负数

linux - 当父进程和子进程读取同一个文件并写入另一个同一个文件时会发生什么?