tags:

views:

38

answers:

1
  stdinBackup = 4;
  dup2(0, stdinBackup);

Currently I am doing the above to 'backup' stdin so that it can be restored from backup later after it has been redirected somewhere else. I have a feeling that I am doing a lot wrong? (eg arbitrarily assigning 4 is surely not right). Anyone point me in the right direction?

+4  A: 

If you just want to make a general copy for your own use, there is no need to use dup2(). Just use a plain dup():

#include <stdio.h>

int stdinBackup = dup(STDIN_FILENO);

You only need to use dup2() when you care about the duplicate's actual value.

See here for the definition of the symbolic constant STDIN_FILENO, which is far better than using a naked 0 in the code.

unwind
I see no reason to use `STDIN_FILENO` in place of 0 when 0 is fixed for all-time by POSIX.
R..
@R..: Not even for readability? I'd say that STDIN_FILENO is a lot more helpful than a plain 0 when it comes to communicating what is going on. Avoid magical numbers, and all that.
unwind
I dunno about you, but my eyes/brain can more easily and quickly distinguish 0/1/2 than they can dig the xxx (IN/OUT/ERR) out of the ugly, all-caps STDxxx_FILENO.
R..