Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

c++ - Redirect FROM stderr to another file descriptor

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
" : "Bad
");
        char x [100];
        std :: cerr
            << "Output to " << getcwd (x, 100) << " / " << output_file
            <<  " yields " << fd << " errno: " << errno << "
";
        std :: cout << (std::cerr ? "Fine
" : "Bad
");
    }
}

This outputs

Fine
Bad

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You reversed the arguments: it's

dup2(from_fd, to_fd)

i.e.

dup2(fd, 2)

(see POSIX.2008 or your manpages.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...