exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / popen-safer.c
blob069753a77d0c7a2e935e58d3f4ceeaf4a312c0e8
1 /* Invoke popen, but avoid some glitches.
3 Copyright (C) 2009-2024 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 <https://www.gnu.org/licenses/>. */
18 /* Written by Eric Blake. */
20 #include <config.h>
22 #include "stdio-safer.h"
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <unistd.h>
28 /* Like popen, but do not return stdin, stdout, or stderr. */
30 FILE *
31 popen_safer (char const *cmd, char const *mode)
33 /* Unfortunately, we cannot use the fopen_safer approach of using
34 fdopen (dup_safer (fileno (popen (cmd, mode)))), because stdio
35 libraries maintain hidden state tying the original fd to the pid
36 to wait on when using pclose (this hidden state is also used to
37 avoid fd leaks in subsequent popen calls). So, we instead
38 guarantee that all standard streams are open prior to the popen
39 call (even though this puts more pressure on open fds), so that
40 the original fd created by popen is safe. */
41 FILE *fp;
42 int fd = open ("/dev/null", O_RDONLY | O_CLOEXEC);
43 if (0 <= fd && fd <= STDERR_FILENO)
45 /* Maximum recursion depth is 3. */
46 int saved_errno;
47 fp = popen_safer (cmd, mode);
48 saved_errno = errno;
49 close (fd);
50 errno = saved_errno;
52 else
54 /* Either all fd's are tied up, or fd is safe and the real popen
55 will reuse it. */
56 close (fd);
57 fp = popen (cmd, mode);
59 return fp;