Lien000034
2014-08-23
UNIX provides two functions DUP and dup2 for copying an existing file descriptor.
# Include <unistd. h>
Int DUP (INT filedes );
Int dup2 (INT filedes, int filedes2 );
Returned value: If successful, a new file descriptor is returned. If an error occurs,-1 is returned.
The file descriptor returned by the DUP function must be the minimum descriptor in the currently available file descriptor.. You can use the dup2 function to specify the target file descriptor through the filedes2 parameter. If filedes2 is enabled, disable it first. If filedes is equal to filedes2, The dup2 function returns filedes2 without disabling it.
The following program uses open to open the file foo.txt and uses lseek to obtain the current offset of the file descriptor. Then, call the DUP file descriptor and call lseek to set the current offset of the new file descriptor to 10 bytes from the beginning of the file. Finally, use lseek to obtain and print the current offset of the two file descriptors.
#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <fcntl.h>#define FILE_MODE S_IRUSR | S_IWUSR | S_IRGRPintmain(void){ int fd, fddup; off_t fdoff, fddupoff; if ((fd = open("foo.txt", O_WRONLY | O_CREAT | O_TRUNC, FILE_MODE)) < 0) { printf("open error"); exit(-1); } if ((fdoff = lseek(fd, 0L, SEEK_CUR)) == -1) { printf("lseek error"); exit(-1); } printf("fd offset(before dup): %d\n", fdoff); if ((fddup = dup(fd)) == -1) { printf("dup error"); exit(-1); } if ((fddupoff = lseek(fddup, 10L, SEEK_SET)) == -1) { printf("lseek error"); exit(-1); } printf("fddup offset(after dup): %d\n", fddupoff); if ((fdoff = lseek(fd, 0L, SEEK_CUR)) == -1) { printf("lseek error"); exit(-1); } printf("fd offset(after dup): %d\n", fdoff); exit(0);}
Compile the program to generate dupdemo, and then run the dupdemo file,
lienhua34:demo$ gcc -o dupdemo dup_demo.clienhua34:demo$ ./dupdemofd offset(before dup): 0fddup offset(after dup): 10fd offset(after dup): 10
The running result of dupdemo shows that the current file offset is set for the file descriptor obtained by DUP, and the current offset of the original file descriptor is also affected. This is because the new file descriptor obtained by the DUP function shares the same file table item with the original file descriptor, as shown in kernel data structure 1.
Figure 1: DUP kernel data structure
In addition, each file descriptor has its own set of file descriptor flag. When the new file descriptor obtained by DUP is executed, close-on-exec indicates that the DUP function is always cleared.
Unix programming learning notes (4) -- dup copy file descriptor for file I/O