我可以施展一些魔法吗dup2
(or fcntl
),这样我将 stdout 重定向到一个文件(即,写入描述符 1 的任何内容都会转到一个文件),但是如果我使用其他机制,它会转到终端输出吗?如此松散:
int original_stdout;
// some magic to save the original stdout
int fd;
open(fd, ...);
dup2(fd, 1);
write(1, ...); // goes to the file open on fd
write(original_stdout, ...); // still goes to the terminal
一个简单的调用dup
将执行保存。这是一个工作示例:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
// error checking omitted for brevity
int original_stdout = dup(1); // magic
int fd = open("foo", O_WRONLY | O_CREAT);
dup2(fd, 1);
close(fd); // not needed any more
write(1, "hello foo\n", 10); // goes to the file open on fd
write(original_stdout, "hello terminal\n", 15); // still goes to the terminal
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)