1 /* Open a stream to a sub-process.
2 Copyright (C) 2009 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 <http://www.gnu.org/licenses/>. */
17 /* Written by Eric Blake <ebb9@byu.net>, 2009. */
21 /* Get the original definition of popen. It might be defined as a macro. */
27 orig_popen (const char *filename, const char *mode)
29 return popen (filename, mode);
41 rpl_popen (const char *filename, const char *mode)
43 /* The mingw popen works fine, and all other platforms have fcntl.
44 The bug of the child clobbering its own file descriptors if stdin
45 or stdout was closed in the parent can be worked around by
46 opening those two fds as close-on-exec to begin with. */
47 /* Cygwin 1.5.x also has a bug where the popen fd is improperly
48 marked close-on-exec, and if the application undoes this, then
49 the fd leaks into subsequent popen calls. We could work around
50 this by maintaining a list of all fd's opened by popen, and
51 temporarily marking them cloexec around the real popen call, but
52 we would also have to override pclose, and the bookkeepping seems
53 extreme given that cygwin 1.7 no longer has the bug. */
55 int cloexec0 = fcntl (STDIN_FILENO, F_GETFD);
56 int cloexec1 = fcntl (STDOUT_FILENO, F_GETFD);
61 if (open ("/dev/null", O_RDONLY) != STDIN_FILENO
62 || fcntl (STDIN_FILENO, F_SETFD,
63 fcntl (STDIN_FILENO, F_GETFD) | FD_CLOEXEC) == -1)
68 if (open ("/dev/null", O_RDONLY) != STDOUT_FILENO
69 || fcntl (STDOUT_FILENO, F_SETFD,
70 fcntl (STDOUT_FILENO, F_GETFD) | FD_CLOEXEC) == -1)
73 result = orig_popen (filename, mode);
78 close (STDOUT_FILENO);