复制,但仍使用stdout [英] Duplicate, but still use stdout
本文介绍了复制,但仍使用stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用dup2
(或fcntl
)是否可以执行一些魔术操作,以便将stdout重定向到文件(即,写入描述符1的所有内容都将进入文件),但是如果我使用了一些其他机制,它将去终端输出吗?太松散了:
Is there some magic I can do with dup2
(or fcntl
), so that I redirect stdout to a file (i.e., anything written to descriptor 1 would go to a file), but then if I used some other mechanism, it would go to the terminal output? So loosely:
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
将执行保存.这是一个工作示例:
A simple call to dup
will perform the saving. Here is a working example:
#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;
}
这篇关于复制,但仍使用stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文