1 /* Invoke popen, but avoid some glitches.
3 Copyright (C) 2009-2011 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 <http://www.gnu.org/licenses/>. */
18 /* Written by Eric Blake. */
22 #include "stdio-safer.h"
30 /* Like open (name, flags | O_CLOEXEC), although not necessarily
31 atomic. FLAGS must not include O_CREAT. */
34 open_noinherit (char const *name, int flags)
38 /* 0 = unknown, 1 = yes, -1 = no. */
39 static int have_cloexec;
40 if (have_cloexec >= 0)
42 fd = open (name, flags | O_CLOEXEC);
43 if (have_cloexec == 0 && (0 <= fd || errno == EINVAL))
44 have_cloexec = (0 <= fd ? 1 : -1);
45 if (have_cloexec == 1)
50 fd = open (name, flags);
51 if (0 <= fd && set_cloexec_flag (fd, true) != 0)
53 int saved_errno = errno;
61 /* Like popen, but do not return stdin, stdout, or stderr. */
64 popen_safer (char const *cmd, char const *mode)
66 /* Unfortunately, we cannot use the fopen_safer approach of using
67 fdopen (dup_safer (fileno (popen (cmd, mode)))), because stdio
68 libraries maintain hidden state tying the original fd to the pid
69 to wait on when using pclose (this hidden state is also used to
70 avoid fd leaks in subsequent popen calls). So, we instead
71 guarantee that all standard streams are open prior to the popen
72 call (even though this puts more pressure on open fds), so that
73 the original fd created by popen is safe. */
75 int fd = open_noinherit ("/dev/null", O_RDONLY);
76 if (0 <= fd && fd <= STDERR_FILENO)
78 /* Maximum recursion depth is 3. */
80 fp = popen_safer (cmd, mode);
87 /* Either all fd's are tied up, or fd is safe and the real popen
90 fp = popen (cmd, mode);