使用dup和dup2重定向和还原
源于开发一个应用将数据写的设备节点中,但是设备节点具有可变性,所以不在写死,而是先确定好,打开fd再将内容写进去,最终写入fd中的是一个开源程序,没有办法传递fd,不过它会把它要输出的东西输出到stdout中,开启这个开源程序之前把stdout重定向到fd上就可以完成了对接。铺垫完了,下面就开始正题。
其实这个APUE上有讲这个两个函数,但是说的太标准了的书面语,也没有给例子,就没有办法快速理解和使用了。看到一个10年前的好贴《使用dup2重定向了标准输出后,使用什么方法恢复对终端的输出??-4楼》解决了问题。完整代码如下:
- #include <stdio.h>;
- #include <unistd.h>;
- #include <stdlib.h>;
- #include <fcntl.h>;
- #include <sys/types.h>;
- #include <sys/stat.h>;
- #include <string.h>;
- #include <strings.h>;
-
- int main()
- {
- int sfd = dup(STDOUT_FILENO), testfd;
-
- printf("sfd = [%d]\n", sfd);
-
- testfd = open("./temp",O_CREAT | O_RDWR | O_APPEND);
- if (-1 == testfd)
- {
- printf("open file error.\n");
- exit(1);
- }
-
-
- if (-1 == dup2(testfd,STDOUT_FILENO) ) {
- printf("can't redirect fd error\n");
- exit(1);
- }
-
-
- write(STDOUT_FILENO,"file\n",5);
-
-
- if (-1 != dup2(sfd,STDOUT_FILENO) ) {
- printf("recover fd ok \n");
-
-
- write(STDOUT_FILENO,"stdout\n",7);
- }
-
- printf("gogogogogogo!\n");
- close(testfd);
- }
总结:重定向好似抗战片中的将铁轨移到别的路上,或者走向深谷/dev/null,或者走向想让其走的地方fd。再说下,一开始以为我还以为dup2(STDOUT_FILENO, STDOUT_FILENO);就恢复了呢,结果关闭fd时候,显示关闭成功,但是设备却再也打不开了,因为我并没有真正还原。

版权声明:本文为博主原创文章,未经博主允许不得转载。