首页 > 代码库 > linux知识复习1-dup dup2
linux知识复习1-dup dup2
#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); //复制用于后续恢复
/*
redirect standard output to DUMMY.FIL
by duplicating the file handle onto the
file handle for standard output.
*/
dup2(nul, STDOUT); //将标准输出重定向到nul
/* close the handle for DUMMY.FIL */
close(nul);
/* will be redirected into DUMMY.FIL */
write(STDOUT, msg, strlen(msg));
/* restore original standard output
handle */
dup2(oldstdout, STDOUT); //将标准输出重定向到之前保存的标准输出
/* close duplicate handle for STDOUT */
close(oldstdout);
return 0;
}
--------------------------------
fd ---- 文件表----vnode
-------------------------------
指向关系改变:
dup(oldstdout, STDOUT)
oldstdout指向了STDOUT的文件表;
dup2(nul, STDOUT)
STDOUT指向了nul的文件表;
dup2(oldstdout, STDOUT)
STDOUT指向了oldstdout保存的文件表;
详细参考:
http://www.cnblogs.com/GODYCA/archive/2013/01/05/2846197.html
linux知识复习1-dup dup2