Here is the code:
int main()
{
std::cout << "In stdout" << std::endl;
int stdoutBack = dup(1);
close(1);
int output = open("buffer.txt", O_RDWR|O_CREAT|O_APPEND, 0777);
dup2(output, 1);
std::cout << "In buffer" << std::endl;
dup2(output, stdoutBack);
close(output);
std::cout << "In stdout" << std::endl;
}
What I'd like to happen is "In stdout" be printed to stdout, "In buffer" be printed to buffer.txt, and then "In stdout" be printed to stdout again.
What actually happens in the code above is "In stdout" is printed to stdout, "In buffer" is printed to buffer.txt", but the last "In stdout" message is nowhere to be found.
All you need to do is change the last dup2()
from:
dup2(output, stdoutBack);
to...
dup2(stdoutBack, 1);
What you actually need to do is copy your backup of the old stdout back onto the stdout file descriptor (1), not change your backup (which is on a different descriptor) to refer to the file (which is what you're currently doing).
Afterwards, you can close stdoutBack
. Also, there's no need to explicitly close stdout before dup2()
, since dup2()
will do that anyway if it's still open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With