Redirection is typically done at the command line by outputting data that was originally output to the screen to a specified file. Such as
1 $ pwd > Workdir.txt
The output of the PWD command is stored in the Workdir.txt, and the current working directory
By default, printf always outputs the content to the process's open file descriptor number 1 in the corresponding file (0-standard input, 1-standard output, 2-standard error output), which can be used to find the corresponding entry in the Open File table of the process. Implement input and output redirection simply replace the table entry corresponding to the standard input and output. Can be done through the DUP,DUP2 system call. They do this by copying a copy of the file descriptor corresponding to the specified index, returning the corresponding index in the open File table after the copy. Only DUP2 can specify this target index (if the corresponding index already has an open file descriptor, it is closed first), and the DUP is the system to select an unused location for the user. The DUP (2) process can refer to a copy of the Linux early source code description: http://blog.sina.com.cn/s/blog_60c00c780100tc4n.html
int fd = open ("output.txt"0666); int replaced = dup2 (FD, Stdout_fileno);
The above code redirects the program output to a output.txt file. The Stdout_fileno corresponding table entry was replaced with the Open File Table entry for FD. If successful, the replaced value should be consistent with Stdout_fileno.
Give a slightly complete code:
1#include <stdio.h>2#include <unistd.h>3#include <errno.h>4#include <fcntl.h>5 6 intMain () {7 intFD = open ("Data.out", O_RDWR | O_creat,0666);8printf"file fd:%d\n", FD);9 Ten intBackup =DUP (Stdout_fileno); One intreplaced =dup2 (FD, Stdout_fileno); A -printf"duplicated file descriptor:%d\n", replaced); -Perror ("Duplicate Status"); the -printf"haha\n"); - - dup2 (Backup, Stdout_fileno); + -Perror ("Restore Status"); + Close (FD); APerror ("Close Status"); at return 0; -}
Terminal output:
file 3 duplicate Status:successrestore status:successclose status:success
File contents:
Catfile1haha
UNIX system call: DUP,DUP2 Implementation redirect