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.