Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if cout and cerr go to the same place

Tags:

c++

stream

cout

Is there a way in C++ to tell if std::cout and std::cerr are pointing to the same destination?

That is, I'd like to be able to distinguish when the program is launched like

program or program > log 2>&1 or program &> log

versus

program > log or program 2> errors or program > log 2> errors

(The use case is a situation where we'd like error information to be printed to both stdout and stderr when they are separate, but want to print a slightly differently formatted output (not just a concatenation) if they both go to the same destination. -- Yes, I'm aware this isn't ideal, and isn't the officially recommended way to do things, and shouldn't be looked on as a standard way of doing things. But please just trust me, though, that we've taken time to think things through, and for our particular use case this is the best option.)

For our purposes, we can assume that nothing has been done with cout/cerr redirection within the program itself (just the typical shell-level command line redirection), so if there's C-level functionality which looks at stdout/stderr directly (rather than the std::cout and std::cerr streams proper), that would likely work too.

like image 785
R.M. Avatar asked Nov 17 '22 06:11

R.M.


1 Answers

This is another case of the XY Problem.

What you are really trying to accomplish is:

For our end-user use cases, we want to be sure that messages indicating what error has occurred end up in both stderr and stdout (because depending on how our users have or have not set up output redirection they may or may not see it in one or the other.) We could just print things once to each (effectively what we're doing currently), but if stdout and stderr go to the same location, it would be clearer and more user friendly if we could reformat things to remove the redundant printing.

Given that objective, a cleaner mechanism would be to allow the user to specify where they would like the error messages to go to. E.g.

the-program --error-destination "stdout"
the-program --error-destination "stderr"
the-program --error-destination "stdout,stderr"
the-program --error-destination "/tmp/errro-messages.txt"
the-program --error-destination "stdout,/tmp/errro-messages.txt"

With the understanding that "stdout" and "stderr" are special destinations. Anything else is a file.

like image 166
R Sahu Avatar answered Dec 19 '22 04:12

R Sahu