Brayden Willenborg
Brayden Willenborg

Reputation: 71

Use dup2 to swap stdout with file descriptor and back again

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.

Upvotes: 5

Views: 3880

Answers (1)

Dmitri
Dmitri

Reputation: 9375

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.

Upvotes: 5

Related Questions