maint: update all copyright year number ranges
[gnulib.git] / lib / dup3.c
1 /* Copy a file descriptor, applying specific flags.
2    Copyright (C) 2009-2013 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
14    You should have received a copy of the GNU General Public License along
15    with this program; if not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 /* Specification.  */
20 #include <unistd.h>
21
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25
26 #include "binary-io.h"
27
28 int
29 dup3 (int oldfd, int newfd, int flags)
30 {
31 #if HAVE_DUP3
32 # undef dup3
33   /* Try the system call first, if it exists.  (We may be running with a glibc
34      that has the function but with an older kernel that lacks it.)  */
35   {
36     /* Cache the information whether the system call really exists.  */
37     static int have_dup3_really; /* 0 = unknown, 1 = yes, -1 = no */
38     if (have_dup3_really >= 0)
39       {
40         int result = dup3 (oldfd, newfd, flags);
41         if (!(result < 0 && errno == ENOSYS))
42           {
43             have_dup3_really = 1;
44 # if REPLACE_FCHDIR
45             if (0 <= result)
46               result = _gl_register_dup (oldfd, newfd);
47 # endif
48             return result;
49           }
50         have_dup3_really = -1;
51       }
52   }
53 #endif
54
55   if (newfd < 0 || newfd >= getdtablesize () || fcntl (oldfd, F_GETFD) == -1)
56     {
57       errno = EBADF;
58       return -1;
59     }
60
61   if (newfd == oldfd)
62     {
63       errno = EINVAL;
64       return -1;
65     }
66
67   /* Check the supported flags.
68      Note that O_NONBLOCK is not supported, because setting it on newfd
69      would implicitly also set it on oldfd.  */
70   if ((flags & ~(O_CLOEXEC | O_BINARY | O_TEXT)) != 0)
71     {
72       errno = EINVAL;
73       return -1;
74     }
75
76   if (flags & O_CLOEXEC)
77     {
78       int result;
79       close (newfd);
80       result = fcntl (oldfd, F_DUPFD_CLOEXEC, newfd);
81       if (newfd < result)
82         {
83           close (result);
84           errno = EIO;
85           result = -1;
86         }
87       if (result < 0)
88         return -1;
89     }
90   else if (dup2 (oldfd, newfd) < 0)
91     return -1;
92
93 #if O_BINARY
94   if (flags & O_BINARY)
95     setmode (newfd, O_BINARY);
96   else if (flags & O_TEXT)
97     setmode (newfd, O_TEXT);
98 #endif
99
100   return newfd;
101 }