Redirect FROM stderr to another file descriptor
Asked Answered
H

2

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.

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.)

Heritor answered 23/2, 2011 at 19:12 Comment(1)
Please accept some answers before you post your next question. Click the checkmark next to the best answer for your previous questions.Favoritism
F
2

You reversed the arguments: it's

dup2(from_fd, to_fd)

i.e.

dup2(fd, 2)

(see POSIX.2008 or your manpages.)

Favoritism answered 23/2, 2011 at 19:15 Comment(2)
man page says int dup2(int oldfd, int newfd); and 2 is the old fd, no?Heritor
No: oldfd is the fd copied from, and newfd is the fd copied to. (oldfd and newfd aren't very good names for the arguments. Is that a Linux manpage?)Favoritism
G
0

Just for completeness: You could even achieve your goal with freopen(name, mode, stderr), which is a Standard/ANSI/ISO C89 and C99 function.

Guardi answered 29/8, 2011 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.