]> git.cworth.org Git - tar/blob - gnu/cloexec.c
Imported Upstream version 1.24
[tar] / gnu / cloexec.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* closexec.c - set or clear the close-on-exec descriptor flag
4
5    Copyright (C) 1991, 2004-2006, 2009-2010 Free Software Foundation, Inc.
6
7    This program is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20    The code is taken from glibc/manual/llio.texi  */
21
22 #include <config.h>
23
24 #include "cloexec.h"
25
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29
30 /* Set the `FD_CLOEXEC' flag of DESC if VALUE is true,
31    or clear the flag if VALUE is false.
32    Return 0 on success, or -1 on error with `errno' set.
33
34    Note that on MingW, this function does NOT protect DESC from being
35    inherited into spawned children.  Instead, either use dup_cloexec
36    followed by closing the original DESC, or use interfaces such as
37    open or pipe2 that accept flags like O_CLOEXEC to create DESC
38    non-inheritable in the first place.  */
39
40 int
41 set_cloexec_flag (int desc, bool value)
42 {
43 #ifdef F_SETFD
44
45   int flags = fcntl (desc, F_GETFD, 0);
46
47   if (0 <= flags)
48     {
49       int newflags = (value ? flags | FD_CLOEXEC : flags & ~FD_CLOEXEC);
50
51       if (flags == newflags
52           || fcntl (desc, F_SETFD, newflags) != -1)
53         return 0;
54     }
55
56   return -1;
57
58 #else /* !F_SETFD */
59
60   /* Use dup2 to reject invalid file descriptors; the cloexec flag
61      will be unaffected.  */
62   if (desc < 0)
63     {
64       errno = EBADF;
65       return -1;
66     }
67   if (dup2 (desc, desc) < 0)
68     /* errno is EBADF here.  */
69     return -1;
70
71   /* There is nothing we can do on this kind of platform.  Punt.  */
72   return 0;
73 #endif /* !F_SETFD */
74 }
75
76
77 /* Duplicates a file handle FD, while marking the copy to be closed
78    prior to exec or spawn.  Returns -1 and sets errno if FD could not
79    be duplicated.  */
80
81 int
82 dup_cloexec (int fd)
83 {
84   return fcntl (fd, F_DUPFD_CLOEXEC, 0);
85 }