1DUP(2)                     Linux Programmer's Manual                    DUP(2)
2
3
4

NAME

6       dup, dup2 - duplicate a file descriptor
7

SYNOPSIS

9       #include <unistd.h>
10
11       int dup(int oldfd);
12       int dup2(int oldfd, int newfd);
13

DESCRIPTION

15       dup() and dup2() create a copy of the file descriptor oldfd.
16
17       After  a  successful  return from dup() or dup2(), the old and new file
18       descriptors may be used interchangeably.  They refer to the  same  open
19       file description (see open(2)) and thus share file offset and file sta‐
20       tus flags; for example,  if  the  file  offset  is  modified  by  using
21       lseek(2)  on one of the descriptors, the offset is also changed for the
22       other.
23
24       The two descriptors do not share file descriptor flags  (the  close-on-
25       exec  flag).  The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the
26       duplicate descriptor is off.
27
28       dup() uses the lowest-numbered unused descriptor for the  new  descrip‐
29       tor.
30
31       dup2()  makes newfd be the copy of oldfd, closing newfd first if neces‐
32       sary.
33

RETURN VALUE

35       dup() and dup2() return the new descriptor, or -1 if an error  occurred
36       (in which case, errno is set appropriately).
37

ERRORS

39       EBADF  oldfd  isn't  an  open  file  descriptor, or newfd is out of the
40              allowed range for file descriptors.
41
42       EBUSY  (Linux only) This may be returned by dup2() during a race condi‐
43              tion with open() and dup().
44
45       EINTR  The dup2() call was interrupted by a signal.
46
47       EMFILE The  process  already has the maximum number of file descriptors
48              open and tried to open a new one.
49

WARNINGS

51       The error returned  by  dup2()  is  different  from  that  returned  by
52       fcntl(...,  F_DUPFD,  ...)  when newfd is out of range. On some systems
53       dup2() also sometimes returns EINVAL like F_DUPFD.
54
55       If newfd was open, any errors that would have been reported at  close()
56       time,  are lost. A careful programmer will not use dup2() without clos‐
57       ing newfd first.
58

CONFORMING TO

60       SVr4, 4.3BSD, POSIX.1-2001.
61

SEE ALSO

63       close(2), fcntl(2), open(2)
64
65
66
67Linux 1.1.46                      1994-08-21                            DUP(2)
Impressum