理解重定向之dup,dup2
来源:互联网 发布:免费刷q币软件 编辑:程序博客网 时间:2024/05/29 19:49
Linux下当使用 ls > file 命令,可以将原本输出在屏幕上的文字重定向到file文件中(如果没有file文件则创建之)
我们可以利用dup,dup2函数也实现一下重定向。它们的接口如下:
#include <unistd.h>int dup(int oldfd);int dup2(int oldfd, int newfd);
dup(fd)是对fd进行一份拷贝,将当前最小未被使用的文件描述符返回。
dup2(fd)则是对fd进行拷贝,返回指定参数newfd,如果newfd已经打开,则先将其关闭。
如上图,当我们使用dup(1),它使用当前最小的可用文件描述符,此时为3,因此,3这个位置就指向了stdout。
1.如何实现重定向呢?
我们需要先关闭指向stdout的那个指针,然后让1这个位置的指针指向file,这样子当我们使用printf之类的函数,输出就显示到file文件中而非stdout文件。
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int main(){ int fd = open("./iofile", O_RDWR | O_CREAT, 0666); if (fd < 0) { fprintf(stderr, "open failure\n"); exit(1); } printf("-> stdout:\n"); printf("fd = %d\n", fd); // 开始重定向 close(1); int new_fd = dup(fd); printf("-> file :\n"); printf("new_fd = %d\n", new_fd); fflush(stdout); return 0;}
iofile文件显示如下:
-> file :
new_fd = 1
2.实现重定向呢并恢复
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int main(){ int fd = open("./iofile", O_RDWR | O_CREAT, 0666); if (fd < 0) { fprintf(stderr, "open failure\n"); exit(1); } printf("-> stdout:\n"); printf("fd = %d\n", fd); // 开始重定向 int recover_fd = dup(1);//用于恢复重定向 int new_fd = dup2(fd, 1); printf("-> file :\n"); printf("new_fd = %d\n", new_fd); fflush(stdout); //恢复,让printf可以输出到屏幕上 dup2(recover_fd, 1); close(recover_fd); printf("-> stdout:\n"); printf("hello world\n"); close(fd); return 0;}
阅读全文
0 0
- 理解重定向之dup,dup2
- 重定向之dup,dup2
- dup/dup2输出重定向
- Linux--重定向dup&&dup2
- linux句柄重定向之dup和dup2
- linux句柄重定向之dup和dup2
- APUE之dup,dup2函数重定向标准输出实例
- dup/dup2 标准输入输出重定向
- 利用dup/dup2重定向标准输入输出
- dup,dup2实现stdout重定向
- dup和dup2 与重定向
- 重定向编程 dup和dup2函数
- 【Linux】重定向函数dup/dup2
- 文件描述符重定向---dup&dup2
- 使用dup和dup2重定向和还原
- 关于dup和dup2函数的重定向与还原
- 使用dup和dup2重定向和还原
- # 2.1 linux文件系统dup/dup2重定向应用实例
- fastjson反序列化ZonedDateTime格式的时间
- Maven 参考知识
- 图形化mybatis代码生成工具
- Nginx环境下flush失效问题
- STM32->EXTI
- 理解重定向之dup,dup2
- gradle各版本下载地址
- JQUERY一键置顶小插件
- myeclipse中代码行数太多,在代码中加书签来快速定位
- 对于经常写支付接口的人提供一个比较好的小工具
- LESS的使用方法
- 【学习笔记】嵌入式Linux之内存管理
- 读取配置文件properties的方法
- nginx + lua环境搭建