#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");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…