将stdout / stderr重定向到unix c ++下的文件 - 再次 [英] redirect stdout/stderr to file under unix c++ - again
问题描述
我想做什么
将stdout和stderr重定向到c ++中的一个或多个文件
redirect stdout and stderr to one or more files from inside c++
为什么我需要它
我使用的是一个外部预编译的第三方库,它产生了大量的荒谬输出,我想重定向到日志文件以保持控制台清洁。
I am using an external, precompiled third-party library that produces a ridiculous amount of output, which I would like to redirect to a log file to keep the console clean.
条件
兼容性不是问题,代码只能在Unix系统上运行。重定向不仅应该影响c ++风格的打印(std :: cout<<hello world<< std :: endl),还应该影响c风格的打印(printf(hello world \ n)) )。
Compatibility is not a problem, the code will only run on Unix systems. The redirection should not only affect c++-style printing (std::cout << "hello world" << std::endl), but also c-style printing (printf("hello world\n")).
到目前为止我尝试了什么
我一直在浏览stackoverflow半天,阅读有类似问题的人的多个答案。在这些答案的帮助下,我已经能够汇总以下代码:
I have been browsing on stackoverflow for half a day, reading multiple answers to people having similar problems. With the help of these answers, I have been able to put together the following piece of code:
#include <stdio.h>
#include <iostream>
#include <fcntl.h>
#include "unistd.h"
const int stdoutfd(dup(fileno(stdout)));
int redirect_stdout(const char* fname){
fflush(stdout);
int newstdout = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
dup2(newstdout, fileno(stdout));
close(newstdout);
}
int restore_stdout(){
fflush(stdout);
dup2(stdoutfd, fileno(stdout));
close(stdoutfd);
return stdoutfd;
}
int main(){
redirect_stdout("/dev/null");
std::cout << "invisible 1" << std::endl;
restore_stdout();
std::cout << "visible 1" << std::endl;
redirect_stdout("/dev/null");
std::cout << "invisible 2" << std::endl;
restore_stdout();
std::cout << "visible 2" << std::endl;
return 0;
}
我期望什么见:
What I would expect to see:
visible 1
visible 2
我实际看到的是什么
visible 1
也就是说,第一次使用这种机制时,它可以正常工作 - 但如果再次使用,恢复输出将无效。
有人可以向我指出我需要改变什么才能使机制无限次地工作吗?
That is, when using this mechanism for the first time, it works - but if used again, restoring the output will not work. Can somebody point out to me what I need to change in order to have the mechanism work infinitely often?
推荐答案
如果您希望能够重复使用它,请不要在 restore_stdout
中关闭 stdoutfd
。
If you want to be able to reuse it, don't close stdoutfd
in restore_stdout
.
这篇关于将stdout / stderr重定向到unix c ++下的文件 - 再次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!