1 /* Invoke popen, but avoid some glitches.
3 Copyright (C) 2009 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 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
31 # define O_CLOEXEC O_NOINHERIT
32 #elif !defined O_CLOEXEC
36 /* Like open (name, flags | O_CLOEXEC), although not necessarily
37 atomic. FLAGS must not include O_CREAT. */
40 open_noinherit (char const *name, int flags)
42 int fd = open (name, flags | O_CLOEXEC);
43 if (0 <= fd && !O_CLOEXEC && set_cloexec_flag (fd, true) != 0)
45 int saved_errno = errno;
53 /* Like popen, but do not return stdin, stdout, or stderr. */
56 popen_safer (char const *cmd, char const *mode)
58 /* Unfortunately, we cannot use the fopen_safer approach of using
59 fdopen (dup_safer (fileno (popen (cmd, mode)))), because stdio
60 libraries maintain hidden state tying the original fd to the pid
61 to wait on when using pclose (this hidden state is also used to
62 avoid fd leaks in subsequent popen calls). So, we instead
63 guarantee that all standard streams are open prior to the popen
64 call (even though this puts more pressure on open fds), so that
65 the original fd created by popen is safe. */
67 int fd = open_noinherit ("/dev/null", O_RDONLY);
68 if (0 <= fd && fd <= STDERR_FILENO)
70 /* Maximum recursion depth is 3. */
72 fp = popen_safer (cmd, mode);
79 /* Either all fd's are tied up, or fd is safe and the real popen
82 fp = popen (cmd, mode);