1 /* Open a stream to a sub-process.
2 Copyright (C) 2009-2020 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Eric Blake <ebb9@byu.net>, 2009. */
24 #if defined _WIN32 && ! defined __CYGWIN__
25 /* Native Windows API. */
30 popen (const char *filename
, const char *mode
)
32 /* Use binary mode by default. */
33 if (strcmp (mode
, "r") == 0)
35 else if (strcmp (mode
, "w") == 0)
38 return _popen (filename
, mode
);
51 rpl_popen (const char *filename
, const char *mode
)
53 /* All other platforms have popen and fcntl.
54 The bug of the child clobbering its own file descriptors if stdin
55 or stdout was closed in the parent can be worked around by
56 opening those two fds as close-on-exec to begin with. */
57 /* Cygwin 1.5.x also has a bug where the popen fd is improperly
58 marked close-on-exec, and if the application undoes this, then
59 the fd leaks into subsequent popen calls. We could work around
60 this by maintaining a list of all fd's opened by popen, and
61 temporarily marking them cloexec around the real popen call, but
62 we would also have to override pclose, and the bookkeeping seems
63 extreme given that cygwin 1.7 no longer has the bug. */
65 int cloexec0
= fcntl (STDIN_FILENO
, F_GETFD
);
66 int cloexec1
= fcntl (STDOUT_FILENO
, F_GETFD
);
69 /* If either stdin or stdout was closed (that is, fcntl failed),
70 then we open a dummy close-on-exec fd to occupy that slot. That
71 way, popen's internal use of pipe() will not contain either fd 0
72 or 1, overcoming the fact that the child process blindly calls
73 close() on the parent's end of the pipe without first checking
74 whether it is clobbering the fd just placed there via dup2(); the
75 exec will get rid of the dummy fd's in the child. Fortunately,
76 closed stderr in the parent does not cause problems in the
80 if (open ("/dev/null", O_RDONLY
) != STDIN_FILENO
81 || fcntl (STDIN_FILENO
, F_SETFD
,
82 fcntl (STDIN_FILENO
, F_GETFD
) | FD_CLOEXEC
) == -1)
87 if (open ("/dev/null", O_RDONLY
) != STDOUT_FILENO
88 || fcntl (STDOUT_FILENO
, F_SETFD
,
89 fcntl (STDOUT_FILENO
, F_GETFD
) | FD_CLOEXEC
) == -1)
92 result
= popen (filename
, mode
);
93 /* Now, close any dummy fd's created in the parent. */
98 close (STDOUT_FILENO
);