从 stderr 重定向到另一个文件描述符
我的程序调用打印到 stderr 的库函数。我想进行干预,以便对文件描述符 #2 的所有写入调用都将被发送到其他地方。
这是我的第一次尝试:
bool redirect_stderr (int fd)
{
return dup2 (2, fd) > 0;
}
这里,fd 已成功从 open("/foo/bar",O_APPEND|O_CREAT)
获得
,此函数返回 true 后,std::cerr<<" blah"
转到终端而不是文件。
我做错了什么?
谢谢。
更新
谢谢,拉斯曼,但我还没有到那里......
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
到标准输出并且给定的文件是空的。 (如果不存在则正确创建。)
My program calls library functions which print to stderr. I want to intervene so that all write calls to file descriptor #2 will instead get sent to somewhere else.
Here is my first attempt:
bool redirect_stderr (int fd)
{
return dup2 (2, fd) > 0;
}
Here, fd was successfully obtained from open("/foo/bar",O_APPEND|O_CREAT)
After this function returns true, std::cerr<<"blah"
goes to the terminal and not to the file.
What am I doing wrong?
Thanks.
UPDATE
Thanks, larsmans, but I'm not there yet...
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");
}
}
This outputs
Fine
Bad
to stdout and the given file is empty. (It is correctly created if it doesn't exist.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您颠倒了参数:即
(
参见 POSIX.2008 或您的联机帮助页.)
You reversed the arguments: it's
i.e.
(see POSIX.2008 or your manpages.)
只是为了完整起见:您甚至可以使用 freopen(name, mode, stderr) 来实现您的目标,这是一个标准/ANSI/ISO C89 和 C99 函数。
Just for completeness: You could even achieve your goal with
freopen(name, mode, stderr)
, which is a Standard/ANSI/ISO C89 and C99 function.