Use dup2 to swap stdout to and from a file descriptor

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 would like to do is "To stdout" will be printed to stdout, "In buffer" will be printed to buffer.txt, and then "To stdout" will be printed to stdout again.

What actually happens in the above code: "In stdout" is printed to stdout, "In buffer" is printed in buffer.txt ", but the last message" In stdout "is nowhere to be found.

+3


source to share


1 answer


All you have to do is change the latter dup2()

to:

dup2(output, stdoutBack);

      

to ...



dup2(stdoutBack, 1);

      

What you really need to do is copy the backup of the old stdout back to the file descriptor stdout (1), don't modify your backup (which is on a different descriptor) to refer to the file (which is currently).

You can close afterwards stdoutBack

. Also, there is no need to explicitly close stdout before dup2()

, as it dup2()

will do so anyway if it is still open.

+4


source







All Articles