从stderr重定向到另一个文件描述符 [英] Redirect FROM stderr to another file descriptor

查看:124
本文介绍了从stderr重定向到另一个文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的第一次尝试:

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

在这里,从open("/foo/bar",O_APPEND|O_CREAT)

此函数返回true后,std::cerr<<"blah"转到终端而不是文件.

After this function returns true, std::cerr<<"blah" goes to the terminal and not to the file.

我在做什么错了?

谢谢.

更新

谢谢,拉尔曼兄弟,但我还没到那里...

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");
    }
}

此输出

Fine
Bad

到标准输出,给定文件为空. (如果不存在,则会正确创建.)

to stdout and the given file is empty. (It is correctly created if it doesn't exist.)

推荐答案

您颠倒了参数:是

dup2(from_fd, to_fd)

dup2(fd, 2)

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

(see POSIX.2008 or your manpages.)

这篇关于从stderr重定向到另一个文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆