start service tasks separately in-case platforms need to perform additional set-up...
[AROS.git] / compiler / posixc / dup2.c
blob993d6286b8c85a42cdd4c5c654b923bcb8c6f06f
1 /*
2 Copyright © 1995-2014, The AROS Development Team. All rights reserved.
3 $Id$
5 POSIX.1-2008 function dup2().
6 */
8 #include <stdlib.h>
9 #include <errno.h>
10 #include "__fdesc.h"
12 /*****************************************************************************
14 NAME */
15 #include <unistd.h>
17 int dup2(
19 /* SYNOPSIS */
20 int oldfd,
21 int newfd
24 /* FUNCTION
25 Duplicates a file descriptor.
27 The object referenced by the descriptor does not distinguish between
28 oldfd and newfd in any way. Thus if newfd and oldfd are duplicate
29 references to an open file, read(), write() and lseek() calls all
30 move a single pointer into the file, and append mode, non-blocking
31 I/O and asynchronous I/O options are shared between the references.
32 If a separate pointer into the file is desired, a different object
33 reference to the file must be obtained by issuing an additional
34 open(2) call.
36 The close-on-exec flag on the new file descriptor is unset.
38 If oldfd is valid and has the same integer value as newfd, nothing is
39 done, and newfd is returned unchanged.
41 If newfd is already valid when this function is called, its old
42 descriptor is deallocated before this function returns.
44 This function fails gracefully if oldfd is invalid.
46 INPUTS
47 oldfd - The file descriptor to be duplicated
48 newfd - The value of the new descriptor we want the old one to be
49 duplicated in
51 RESULT
52 -1 for error or newfd on success
54 NOTES
55 This function must not be used in a shared library or
56 in a threaded application.
58 EXAMPLE
60 BUGS
62 SEE ALSO
63 bsdsocket.library/accept(), open(), close(), fcntl(), pipe()
64 bsdsocket.library/socket()
66 INTERNALS
68 ******************************************************************************/
70 fdesc *oldfdesc, *newfdesc;
72 /* Fail if old FD is invalid */
73 oldfdesc = __getfdesc(oldfd);
74 if (!oldfdesc)
76 errno = EBADF;
77 return -1;
80 /* Do nothing if FDs are identical */
81 if (oldfd == newfd)
82 return newfd;
84 /* Allocate new FD or fail */
85 newfdesc = __alloc_fdesc();
86 if (!newfdesc)
88 errno = ENOMEM;
89 return -1;
92 /* Initialise new FD */
93 newfdesc->fdflags = 0;
94 newfdesc->fcb = oldfdesc->fcb;
96 /* Put new FD into its slot (and deallocate any FD previously there) */
97 newfd =__getfdslot(newfd);
98 if (newfd != -1)
100 newfdesc->fcb->opencount++;
101 __setfdesc(newfd, newfdesc);
104 return newfd;