Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use dup2 to swap stdout with file descriptor and back again

Tags:

c++

c

stdout

dup2

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.

like image 290
Brayden Willenborg Avatar asked Oct 31 '14 01:10

Brayden Willenborg


Video Answer


1 Answers

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.

like image 127
Dmitri Avatar answered Oct 20 '22 20:10

Dmitri