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"
34 /* Like open (name, flags | O_CLOEXEC), although not necessarily
35 atomic. FLAGS must not include O_CREAT. */
38 open_noinherit (char const *name, int flags)
40 int fd = open (name, flags | O_CLOEXEC);
41 if (0 <= fd && !O_CLOEXEC && set_cloexec_flag (fd, true) != 0)
43 int saved_errno = errno;
51 /* Like popen, but do not return stdin, stdout, or stderr. */
54 popen_safer (char const *cmd, char const *mode)
56 /* Unfortunately, we cannot use the fopen_safer approach of using
57 fdopen (dup_safer (fileno (popen (cmd, mode)))), because stdio
58 libraries maintain hidden state tying the original fd to the pid
59 to wait on when using pclose (this hidden state is also used to
60 avoid fd leaks in subsequent popen calls). So, we instead
61 guarantee that all standard streams are open prior to the popen
62 call (even though this puts more pressure on open fds), so that
63 the original fd created by popen is safe. */
65 int fd = open_noinherit ("/dev/null", O_RDONLY);
66 if (0 <= fd && fd <= STDERR_FILENO)
68 /* Maximum recursion depth is 3. */
70 fp = popen_safer (cmd, mode);
77 /* Either all fd's are tied up, or fd is safe and the real popen
80 fp = popen (cmd, mode);