dup() — Duplicate an open file descriptor
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1
XPG4 XPG4.2 Single UNIX Specification, Version 3 |
both |
Format
#define _POSIX_SOURCE
#include <unistd.h>
int dup(int fildes);
General description
Returns a new file descriptor that is the lowest numbered available descriptor. 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 further information,
see fcntl() — Control open file descriptors.Note: When fildes is
an XTI endpoint, the lowest numbered available file descriptor must
not exceed 65535.
Returned value
If successful, dup() returns a new file descriptor.
If unsuccessful, dup() returns -1 and
sets errno to one of the following values:
- Error Code
- Description
- EBADF
- fildes is not a valid open file descriptor.
- EMFILE
- The process has already reached its maximum number of open file descriptors.
Example
CELEBD05
/* CELEBD05
This example duplicates an open file descriptor, using dup().
*/
#define _POSIX_SOURCE
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#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.