理解重定向之dup,dup2

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章