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;
}