我的程序调用了打印到 stderr 的库函数。我想进行干预,以便所有对文件描述符 #2 的写入调用都将发送到其他地方。
这是我的第一次尝试:
bool redirect_stderr (int fd)
{
return dup2 (2, fd) > 0;
}
这里,fd是从open("/foo/bar",O_APPEND|O_CREAT)
成功获取到的
此函数返回真后,std::cerr<<"blah"
转到终端而不是文件。
我做错了什么?
谢谢。
更新
谢谢,larsmans,但我还没有...
void redirect_stderr_to (const char * output_file)
{
int fd = open (output_file, O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
if (fd < 0) {
throw RUNTIME_ERROR;
}
else {
if (-1 == dup2 (fd, STDERR_FILENO))
throw RUNTIME_ERROR;
std :: cout << (std::cerr ? "Fine\n" : "Bad\n");
char x [100];
std :: cerr
<< "Output to " << getcwd (x, 100) << " / " << output_file
<< " yields " << fd << " errno: " << errno << "\n";
std :: cout << (std::cerr ? "Fine\n" : "Bad\n");
}
}
这输出
Fine
Bad
到标准输出,给定的文件是空的。 (如果不存在则正确创建。)
最佳答案
关于c++ - 将 FROM stderr 重定向到另一个文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5095839/