This source file includes following definitions.
- dup2_nothrow
- ms_windows_dup2
- klibc_dup2dirfd
- klibc_dup2
- rpl_dup2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 #include <config.h>
22
23
24 #include <unistd.h>
25
26 #include <errno.h>
27 #include <fcntl.h>
28
29 #undef dup2
30
31 #if defined _WIN32 && ! defined __CYGWIN__
32
33
34 # define WIN32_LEAN_AND_MEAN
35 # include <windows.h>
36
37 # if HAVE_MSVC_INVALID_PARAMETER_HANDLER
38 # include "msvc-inval.h"
39 # endif
40
41
42 # if GNULIB_MSVC_NOTHROW
43 # include "msvc-nothrow.h"
44 # else
45 # include <io.h>
46 # endif
47
48 # if HAVE_MSVC_INVALID_PARAMETER_HANDLER
49 static int
50 dup2_nothrow (int fd, int desired_fd)
51 {
52 int result;
53
54 TRY_MSVC_INVAL
55 {
56 result = _dup2 (fd, desired_fd);
57 }
58 CATCH_MSVC_INVAL
59 {
60 errno = EBADF;
61 result = -1;
62 }
63 DONE_MSVC_INVAL;
64
65 return result;
66 }
67 # else
68 # define dup2_nothrow _dup2
69 # endif
70
71 static int
72 ms_windows_dup2 (int fd, int desired_fd)
73 {
74 int result;
75
76
77
78
79 if (fd == desired_fd)
80 {
81 if ((HANDLE) _get_osfhandle (fd) == INVALID_HANDLE_VALUE)
82 {
83 errno = EBADF;
84 return -1;
85 }
86 return fd;
87 }
88
89
90
91 if (desired_fd < 0)
92 {
93 errno = EBADF;
94 return -1;
95 }
96
97 result = dup2_nothrow (fd, desired_fd);
98
99 if (result == 0)
100 result = desired_fd;
101
102 return result;
103 }
104
105 # define dup2 ms_windows_dup2
106
107 #elif defined __KLIBC__
108
109 # include <InnoTekLIBC/backend.h>
110
111 static int
112 klibc_dup2dirfd (int fd, int desired_fd)
113 {
114 int tempfd;
115 int dupfd;
116
117 tempfd = open ("NUL", O_RDONLY);
118 if (tempfd == -1)
119 return -1;
120
121 if (tempfd == desired_fd)
122 {
123 close (tempfd);
124
125 char path[_MAX_PATH];
126 if (__libc_Back_ioFHToPath (fd, path, sizeof (path)))
127 return -1;
128
129 return open(path, O_RDONLY);
130 }
131
132 dupfd = klibc_dup2dirfd (fd, desired_fd);
133
134 close (tempfd);
135
136 return dupfd;
137 }
138
139 static int
140 klibc_dup2 (int fd, int desired_fd)
141 {
142 int dupfd;
143 struct stat sbuf;
144
145 dupfd = dup2 (fd, desired_fd);
146 if (dupfd == -1 && errno == ENOTSUP \
147 && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
148 {
149 close (desired_fd);
150
151 return klibc_dup2dirfd (fd, desired_fd);
152 }
153
154 return dupfd;
155 }
156
157 # define dup2 klibc_dup2
158 #endif
159
160 int
161 rpl_dup2 (int fd, int desired_fd)
162 {
163 int result;
164
165 #ifdef F_GETFL
166
167
168
169
170
171 # if HAVE_SETDTABLESIZE
172 setdtablesize (desired_fd + 1);
173 # endif
174 if (desired_fd < 0)
175 fd = desired_fd;
176 if (fd == desired_fd)
177 return fcntl (fd, F_GETFL) == -1 ? -1 : fd;
178 #endif
179
180 result = dup2 (fd, desired_fd);
181
182
183 if (result == -1 && errno == EMFILE)
184 errno = EBADF;
185 #if REPLACE_FCHDIR
186 if (fd != desired_fd && result != -1)
187 result = _gl_register_dup (fd, result);
188 #endif
189 return result;
190 }