linux知识复习1-dup dup2

 

复制代码
 1 #include <sys/stat.h>
 2 #include <string.h>
 3 #include <fcntl.h>
 4 #include <stdio.h>
 5 #include <unistd.h>
 6 int main(void)
 7 {
 8     #define STDOUT 1 
 9     int nul, oldstdout;
10     char msg[] = "This is a test";
11     /* create a file */
12     nul = open("DUMMY.FIL", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
13     /* create a duplicate handle for standard
14     output */
15 
16     oldstdout = dup(STDOUT); //复制用于后续恢复
17     /*
18     redirect standard output to DUMMY.FIL
19     by duplicating the file handle onto the
20     file handle for standard output.
21     */
22     dup2(nul, STDOUT); //将标准输出重定向到nul
23     /* close the handle for DUMMY.FIL */
24     close(nul);
25     /* will be redirected into DUMMY.FIL */
26     write(STDOUT, msg, strlen(msg));
27     /* restore original standard output
28     handle */
29     dup2(oldstdout, STDOUT); //将标准输出重定向到之前保存的标准输出
30     /* close duplicate handle for STDOUT */
31     close(oldstdout);
32     return 0;
33 }
复制代码

 

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

进程fd表 ---- 文件表----v节点表

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

指向关系改变:

dup2(nul, STDOUT)

STDOUT指向了nul的文件表;

dup2(oldstdout, STDOUT)

STDOUT指向了oldstdout保存的文件表;

 

打开文件的每个进程都有独立的文件表项,可以使每个进程都有自己对于该文件的当前偏移;

 

详细参考:

http://www.cnblogs.com/GODYCA/archive/2013/01/05/2846197.html

posted @   AlexAlex  阅读(387)  评论(0)    收藏  举报
编辑推荐:
· C# 模式匹配全解:原理、用法与易错点
· 记一次SSD性能瓶颈排查之路——寿命与性能之间的取舍
· 理解 .NET 结构体字段的内存布局
· .NET 9中的异常处理性能提升分析:为什么过去慢,未来快
· 字符集、编码的前世今生
阅读排行:
· 记一次SSD性能瓶颈排查之路——寿命与性能之间的取舍
· 2025 年实用、全面的 VS Code 插件推荐!
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(五):使用.NET为树莓派
· C#实现Stdio通信方式的MCP Server
· dify打造数据可视化图表
点击右上角即可分享
微信分享提示