Žiga Golob
Žiga Golob

Reputation: 37

How to associate stderr with output stream

When I try to get file descriptor for stderr with fileno(stderr), the result is -2 instead of 2. The documentation for fileno says that that is probably because in a Windows application without a console window stderr is not associated with an output stream.

I need stderr file descriptor because I would like to redirect stderr to pipe using _dup2(), so everything written with fprintf(stderr, "...") and std::cerr << "..." will be redirected to the pipe.

My question is if it is possible to get the file descriptor for stderr in gui application, where there is no console window? Can I somehow open the default stderr file descriptor before calling fileno(stderr)?

EDIT:
I manage to make it work to redirect fprintf(stderr, "...") to pipe by first calling freopen("temp.txt", "w",stderr) and then calling fileno(stderr) to get the file descriptor, based on the idea proposed by @darune.

I wish to do this, because I would like to redirect data from external libraries which are not under my control.

Upvotes: 0

Views: 428

Answers (2)

darune
darune

Reputation: 10982

std::cerr can be redirected inside your program, but stderr cannot (at least not in any portable or standard way I am aware about).

You can first use std::freopen and after that the valid file descriptor can be obtained with std::_fileno(). That may or may not be enough, so if you need anything else to happen after that point, you are stuck with having to monitor the file from inside your own program (eg. ala. tailing the file) and doing your custom handling.

Upvotes: 1

ctrl-alt-delor
ctrl-alt-delor

Reputation: 7745

The way that it works in Unix is that 2 refers to row 2 in a table with in the kernel. This entry in the table can point to and file or file like thing (socket, pipe, file, device, nothing,…). Therefore if there is nothing there, the table slot will still remain, and can be populated with a new value (using dup?).

However this is Unix, and Microsoft's Windows is not Unix.

Upvotes: 0

Related Questions