码迷,mamicode.com
首页 > 系统相关 > 详细

linux知识复习1-dup dup2

时间:2014-12-26 16:27:32      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

#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

标签:

原文地址:http://www.cnblogs.com/wanpengcoder/p/4186906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!