1.\" Copyright (c) 1980, 1991, 1993 2.\" The Regents of the University of California. All rights reserved. 3.\" 4.\" %sccs.include.redist.man% 5.\" 6.\" @(#)dup.2 8.1 (Berkeley) 06/04/93 7.\" 8.Dd 9.Dt DUP 2 10.Os BSD 4 11.Sh NAME 12.Nm dup , 13.Nm dup2 14.Nd duplicate an existing file descriptor 15.Sh SYNOPSIS 16.Fd #include <unistd.h> 17.Ft int 18.Fn dup "int oldd" 19.Ft int 20.Fn dup2 "int oldd" "int newd" 21.Sh DESCRIPTION 22.Fn Dup 23duplicates an existing object descriptor and returns its value to 24the calling process 25.Fa ( newd 26= 27.Fn dup oldd ) . 28The argument 29.Fa oldd 30is a small non-negative integer index in 31the per-process descriptor table. The value must be less 32than the size of the table, which is returned by 33.Xr getdtablesize 2 . 34The new descriptor returned by the call 35is the lowest numbered descriptor 36currently not in use by the process. 37.Pp 38The object referenced by the descriptor does not distinguish 39between 40.Fa oldd 41and 42.Fa newd 43in any way. 44Thus if 45.Fa newd 46and 47.Fa oldd 48are duplicate references to an open 49file, 50.Xr read 2 , 51.Xr write 2 52and 53.Xr lseek 2 54calls all move a single pointer into the file, 55and append mode, non-blocking I/O and asynchronous I/O options 56are shared between the references. 57If a separate pointer into the file is desired, a different 58object reference to the file must be obtained by issuing an 59additional 60.Xr open 2 61call. 62The close-on-exec flag on the new file descriptor is unset. 63.Pp 64In 65.Fn dup2 , 66the value of the new descriptor 67.Fa newd 68is specified. If this descriptor is already 69in use, the descriptor is first deallocated as if a 70.Xr close 2 71call had been done first. 72.Sh RETURN VALUES 73The value -1 is returned if an error occurs in either call. 74The external variable 75.Va errno 76indicates the cause of the error. 77.Sh ERRORS 78.Fn Dup 79and 80.Fn dup2 81fail if: 82.Bl -tag -width Er 83.It Bq Er EBADF 84.Fa Oldd 85or 86.Fa newd 87is not a valid active descriptor 88.It Bq Er EMFILE 89Too many descriptors are active. 90.El 91.Sh SEE ALSO 92.Xr accept 2 , 93.Xr open 2 , 94.Xr close 2 , 95.Xr fcntl 2 , 96.Xr pipe 2 , 97.Xr socket 2 , 98.Xr socketpair 2 , 99.Xr getdtablesize 2 100.Sh STANDARDS 101.Fn Dup 102and 103.Fn dup2 104are expected to conform 105to IEEE Std 1003.1-1988 106.Pq Dq Tn POSIX . 107