gtpc2m1q | C/C++ Language Support User's Guide |
This function duplicates an open file descriptor.
Format
#include <unistd.h> int dup(int fildes);
This function returns a new file descriptor, which is the lowest-numbered descriptor that is available. The new file descriptor refers to the same open file as fildes and shares any locks that may be associated with fildes.
The following operations are equivalent:
fd = dup(fildes); fd = fcntl(fildes,F_DUPFD,0);
For more information, see fcntl-Control Open File Descriptors.
Normal Return
If successful, the dup function returns a new file descriptor.
Error Return
If not successful, the dup function returns -1 and sets errno to one of the following:
Programming Considerations
None.
Examples
The following example duplicates an open file descriptor using the dup function.
#include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> void print_inode(int fd) { struct stat info; if (fstat(fd, &info) != 0) fprintf(stderr, "fstat() error for fd %d: %s\n", fd, strerror(errno)); else printf("The inode of fd %d is %d\n", fd, (int) info.st_ino); } main() { int fd; if ((fd = dup(0)) < 0) perror("&dupf error"); else { print_inode(0); print_inode(fd); puts("The file descriptors are different but"); puts("they point to the same file."); close(fd); } }
Output
The inode of fd 0 is 30 The inode of fd 3 is 30 The file descriptors are different but they point to the same file.
Related Information
See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.