Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

backup file descriptor of stdout, to restore printing on to terminal later using only dup2, without using dup system call in C

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>


int main()
{
    int stdout_fd   = dup2(1, 1);
    printf("stdout_fd:%d
", stdout_fd);
    
    int fd_file     = open("file.txt", O_WRONLY|O_TRUNC);
    fd_file         = dup2(fd_file, 1);
    printf("file descriptor of file.txt : %d
", fd_file);
    
    fd_file         = dup2(fd_file, stdout_fd);
    printf("file descriptor of file.txt : %d
", fd_file);
    return 0;
}
O/P:
stdout
______
stdout_fd:1                                                                                                                                                 

file.txt
________
file descriptor of file.txt : 1
file descriptor of file.txt : 1

Here I am trying to print first time to required "file.txt" instead of stdout then for 2nd printf, I am trying to print on stdout i.e, restore file descriptor 0 from from file.txt to stdout again.

I want to implement it using only dup2, without using dup. I dont want to use something like below

int stdout_fd = dup(fd_file);
dup2(fd_file, 1);
printf("I am printing on file.txt");
dup2(fd_file, stdout_fd);
printf("I am printing on file.txt");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...