我正在编写一个函数,给定一个参数,它会将标准输出重定向到文件或从文件中读取标准输入。为此,我关闭了与 stdout 或 stdin 关联的文件描述符,这样当我打开文件时,它会在我刚刚关闭的描述符下打开。这行得通,但问题是一旦完成,我需要将标准输出和标准输入恢复到应有的状态。
我可以为标准输出做的是 open("/dev/tty",O_WRONLY);但我不确定为什么会这样,更重要的是我不知道标准输入的等效语句。
所以我有,对于标准输出
close(1);
if (creat(filePath, O_RDWR) == -1)
{
exit(1);
}
对于标准输入
close(0);
if (open(filePath, O_RDONLY) == -1)
{
exit(1);
}
最佳答案
您应该使用 dup() 和 dup2() 来克隆文件描述符。
int stdin_copy = dup(0);
int stdout_copy = dup(1);
close(0);
close(1);
int file1 = open(...);
int file2 = open(...);
< do your work. file1 and file2 must be 0 and 1, because open always returns lowest unused fd >
close(file1);
close(file2);
dup2(stdin_copy, 0);
dup2(stdout_copy, 1);
close(stdin_copy);
close(stdout_copy);
但是,您可能需要注意一个小细节(来自 man dup):
The two descriptors do not share file descriptor flags (the close-on-execflag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off.
如果这是一个问题,您可能必须恢复 close-on-exec 标志,可能使用 dup3() 而不是 dup2() 以避免竞争条件。
另外,请注意,如果您的程序是多线程的,其他线程可能会意外地写入/读取到您重新映射的标准输入/标准输出。
https://stackoverflow.com/questions/9084099/