1 /* Duplicate an open file descriptor to a specified file descriptor.
3 Copyright (C) 1999, 2004-2007, 2009-2021 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* written by Paul Eggert */
30 #if defined _WIN32 && ! defined __CYGWIN__
32 /* Get declarations of the native Windows API functions. */
33 # define WIN32_LEAN_AND_MEAN
36 # if HAVE_MSVC_INVALID_PARAMETER_HANDLER
37 # include "msvc-inval.h"
40 /* Get _get_osfhandle. */
41 # if GNULIB_MSVC_NOTHROW
42 # include "msvc-nothrow.h"
47 # if HAVE_MSVC_INVALID_PARAMETER_HANDLER
49 dup2_nothrow (int fd, int desired_fd)
55 result = _dup2 (fd, desired_fd);
67 # define dup2_nothrow _dup2
71 ms_windows_dup2 (int fd, int desired_fd)
75 /* If fd is closed, mingw hangs on dup2 (fd, fd). If fd is open,
76 dup2 (fd, fd) returns 0, but all further attempts to use fd in
77 future dup2 calls will hang. */
80 if ((HANDLE) _get_osfhandle (fd) == INVALID_HANDLE_VALUE)
88 /* Wine 1.0.1 return 0 when desired_fd is negative but not -1:
89 https://bugs.winehq.org/show_bug.cgi?id=21289 */
96 result = dup2_nothrow (fd, desired_fd);
104 # define dup2 ms_windows_dup2
106 #elif defined __KLIBC__
108 # include <InnoTekLIBC/backend.h>
111 klibc_dup2dirfd (int fd, int desired_fd)
116 tempfd = open ("NUL", O_RDONLY);
120 if (tempfd == desired_fd)
124 char path[_MAX_PATH];
125 if (__libc_Back_ioFHToPath (fd, path, sizeof (path)))
128 return open(path, O_RDONLY);
131 dupfd = klibc_dup2dirfd (fd, desired_fd);
139 klibc_dup2 (int fd, int desired_fd)
144 dupfd = dup2 (fd, desired_fd);
145 if (dupfd == -1 && errno == ENOTSUP \
146 && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
150 return klibc_dup2dirfd (fd, desired_fd);
156 # define dup2 klibc_dup2
160 rpl_dup2 (int fd, int desired_fd)
165 /* On Linux kernels 2.6.26-2.6.29, dup2 (fd, fd) returns -EBADF.
166 On Cygwin 1.5.x, dup2 (1, 1) returns 0.
167 On Cygwin 1.7.17, dup2 (1, -1) dumps core.
168 On Cygwin 1.7.25, dup2 (1, 256) can dump core.
169 On Haiku, dup2 (fd, fd) mistakenly clears FD_CLOEXEC. */
170 # if HAVE_SETDTABLESIZE
171 setdtablesize (desired_fd + 1);
175 if (fd == desired_fd)
176 return fcntl (fd, F_GETFL) == -1 ? -1 : fd;
179 result = dup2 (fd, desired_fd);
181 /* Correct an errno value on FreeBSD 6.1 and Cygwin 1.5.x. */
182 if (result == -1 && errno == EMFILE)
185 if (fd != desired_fd && result != -1)
186 result = _gl_register_dup (fd, result);