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表 ---- 文件表----v节点表

-------------------------------

指向关系改变:

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)