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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。