一、作用
函数原型
1
2
3
4
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
dup
函数:给 oldfd
指向的“文件”再分配一个新的文件描述符。返回的新描述符是当前进程可用的最小数值,并且源 oldfd
不会被关闭。
dup2
函数:将 oldfd
重定向到 newfd
,并关闭 oldfd
。如果 newfd
处于开启状态则先关闭 newfd
再进行重定向。如果 newfd == oldfd
,直接返回 newfd
且不关闭文件。
0,1,2 这三个文件描述符默认分别为标准输入,标准输出,标准错误
二、案例
把标准输出文件描述符重定向到指定的文件中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
int fd = open("output.txt", O_WRONLY | O_CREAT, 0644);
int saved_stdout = dup(STDOUT_FILENO); // 备份原标准输出
close(STDOUT_FILENO);
int fd2 = dup(fd); // 重定向到文件
printf("写入文件\n");
fflush(stdout); // 强制刷新缓冲区
dup2(saved_stdout, STDOUT_FILENO); // 恢复标准输出
printf("回到终端\n");
close(fd);
return 0;
}