将stderr重定向到另一个文件描述符

时间:2011-02-23 19:12:22

标签: c++ unix pipe stderr dup2

我的程序调用打印到stderr的库函数。我想进行干预,以便对文件描述符#2的所有写入调用都将被发送到其他地方。

这是我的第一次尝试:

bool redirect_stderr (int fd)
{
    return dup2 (2, fd) > 0;
}

此处,fd已成功从open("/foo/bar",O_APPEND|O_CREAT)

获得

此函数返回true后,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

到stdout,给定的文件为空。 (如果它不存在,则会正确创建。)

2 个答案:

答案 0 :(得分:2)

你颠倒了论点:它是

dup2(from_fd, to_fd)

dup2(fd, 2)

(请参阅POSIX.2008或您的联机帮助页。)

答案 1 :(得分:0)

为了完整性:您甚至可以使用freopen(name, mode, stderr)实现目标,这是标准/ ANSI / ISO C89和C99功能。

相关问题