#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main (void)
{
#define STDOUT 1
int nul, oldstdout;
Char msg[] = "This is a test";
/* Create a file */
nul = open ("Dummy.fil", O_creat | O_rdwr, S_iread | S_iwrite);
/* Create a duplicate handle for standard
Output */
Oldstdout = DUP (STDOUT); Replication for subsequent recoveries
/*
REDIRECT standard output to Dummy.fil
By duplicating the file handle onto the
File handle for standard output.
*/
Dup2 (nul, STDOUT); REDIRECT standard output to Nul
/* Close the handle for Dummy.fil */
Close (NUL);
/* 'll be redirected into Dummy.fil */
Write (STDOUT, MSG, strlen (msg));
/* Restore original standard output
HANDLE * *
Dup2 (Oldstdout, STDOUT); REDIRECT standard output to previously saved standard output
/* Close duplicate handle for STDOUT */
Close (oldstdout);
return 0;
}
--------------------------------
FD----File Table----Vnode
-------------------------------
Point to relationship change:
DUP (Oldstdout, STDOUT)
Oldstdout points to the file table of the stdout;
Dup2 (nul, STDOUT)
StdOut points to the file table of the NUL;
Dup2 (Oldstdout, STDOUT)
StdOut points to the file table saved by Oldstdout;
Detailed reference:
Http://www.cnblogs.com/GODYCA/archive/2013/01/05/2846197.html
Linux Knowledge Review 1-dup dup2