Both dup and dup2 can be used to copy an existing file descriptor. STDIN, STDOUT, and STDERR are often used to redirect processes.
Dup Function
The dup function is defined in <unistd. h>. The original function is:
Int dup (int filedes );
The function returns a new descriptor, which is a copy of the descriptor passed to it. If an error occurs,-1 is returned. The new file descriptor returned by dup must be the minimum value in the currently available file descriptor. The new file descriptor returned by this function shares the same file data structure with the filedes parameter.
Example:
# Include <stdio. h>
# Include <unistd. h>
# Include <sys/stat. h>
# Include <fcntl. h>
Int main (int argc, char * argv []) {
Int fd = open ("/home/darren/data. dat", O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR );
If (fd <0 ){
Printf ("Open Error !! \ N ");
Return 0;
}
Int nfd = dup (fd );
If (nfd <0 ){
Printf ("Error !! \ N ");
Return 0;
}
Char buf [1000];
Int n;
While (n = read (STDIN_FILENO, buf, 1000)> 0)
If (write (nfd, buf, n )! = N ){
Printf ("Write Error !! \ N ");
Return 0;
}
Return 0;
}
In the code above, nfd copies fd, so the write (nfd, buf, n) Statement writes to the file represented by nfd, that is, the file represented by fd. After the program is executed, you can view the output in data. dat of the corresponding directory.
Dup2 Functions
The dup2 function is defined in <unistd. h>. The original function is:
Int dup2 (int filedes, int filedes2)
Similarly, the function returns a new file descriptor. If an error occurs,-1 is returned. Unlike dup, dup2 can use the filedes2 parameter to specify the value of the new descriptor. If filedes2 is enabled, disable it first. If filedes is equal to filedes2, dup2 returns filedes2 without disabling it. Similarly, the new file descriptor returned shares the same file data structure with the filedes parameter.
Example:
# Include <stdio. h>
# Include <unistd. h>
# Include <sys/stat. h>
# Include <fcntl. h>
Int main (int argc, char * argv []) {
Int fd = open ("/home/darren/data. dat", O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR );
If (fd <0 ){
Printf ("Open Error !! \ N ");
Return 0;
}
Int nfd = dup2 (fd, STDOUT_FILENO );
If (nfd <0 ){
Printf ("Error !! \ N ");
Return 0;
}
Char buf [1000];
Int n;
While (n = read (STDIN_FILENO, buf, 1000)> 0)
If (write (STDOUT_FILENO, buf, n )! = N ){
Printf ("Write Error !! \ N ");
Return 0;
}
Return 0;
}