1 /* Copy a file descriptor, applying specific flags.
2 Copyright (C) 2009-2011 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
27 #include "binary-io.h"
30 dup3 (int oldfd, int newfd, int flags)
34 /* Try the system call first, if it exists. (We may be running with a glibc
35 that has the function but with an older kernel that lacks it.) */
37 /* Cache the information whether the system call really exists. */
38 static int have_dup3_really; /* 0 = unknown, 1 = yes, -1 = no */
39 if (have_dup3_really >= 0)
41 int result = dup3 (oldfd, newfd, flags);
42 if (!(result < 0 && errno == ENOSYS))
47 result = _gl_register_dup (oldfd, newfd);
51 have_dup3_really = -1;
56 if (newfd < 0 || newfd >= getdtablesize () || fcntl (oldfd, F_GETFD) == -1)
68 /* Check the supported flags.
69 Note that O_NONBLOCK is not supported, because setting it on newfd
70 would implicitly also set it on oldfd. */
71 if ((flags & ~(O_CLOEXEC | O_BINARY | O_TEXT)) != 0)
77 if (flags & O_CLOEXEC)
81 result = fcntl (oldfd, F_DUPFD_CLOEXEC, newfd);
91 else if (dup2 (oldfd, newfd) < 0)
96 setmode (newfd, O_BINARY);
97 else if (flags & O_TEXT)
98 setmode (newfd, O_TEXT);