Liju Mathew
Liju Mathew

Reputation: 899

How can i direct "cout", "cerr", "stdout" and "stderr" to a single file from a C++ program

We have a C++ Web Service which spawns child process on every request. So, every child creates its own log file. We bind the cout and cerr stream to a file to capture all the "std::cout" and "std::cerr".

However, the service uses another "C" component to do some legacy actions. The C component uses "fprintf(stdout,xxx)" and "fprintf(stderr,xxx)" to print the logs.

Those messages are not getting printed into the "cout" and "cerr" log files. Instead it is getting printed in the prompt. We need those stdout/stderr messages also go to the corresponding childlog file.

Is there a way we could bind the "stdout" and "stderr" also to the same file where "cout" and "cerr" are bound.

There are similar questions but that doesn't have multiple language code mixed example.

Let me know.

Thanks

Upvotes: 6

Views: 3262

Answers (1)

Stephen M. Webb
Stephen M. Webb

Reputation: 1869

By default std::cin/std::cout/std::cerr/std::clog are tied to stdin, stdout, and stderr respectively. The right thing to do is to redirect the C layer and the C++ layer will look after itself.

If you're on a POSIX system, just use the dup2() system call to redirect fd's 0 (stdin), 1 (stdout), and 2 (stderr) to the files of your choice.

Upvotes: 2

Related Questions