1 /* Open a stream to a sub-process.
2 Copyright (C) 2009-2011 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. */
32 rpl_popen (const char *filename, const char *mode)
34 /* The mingw popen works fine, and all other platforms have fcntl.
35 The bug of the child clobbering its own file descriptors if stdin
36 or stdout was closed in the parent can be worked around by
37 opening those two fds as close-on-exec to begin with. */
38 /* Cygwin 1.5.x also has a bug where the popen fd is improperly
39 marked close-on-exec, and if the application undoes this, then
40 the fd leaks into subsequent popen calls. We could work around
41 this by maintaining a list of all fd's opened by popen, and
42 temporarily marking them cloexec around the real popen call, but
43 we would also have to override pclose, and the bookkeepping seems
44 extreme given that cygwin 1.7 no longer has the bug. */
46 int cloexec0 = fcntl (STDIN_FILENO, F_GETFD);
47 int cloexec1 = fcntl (STDOUT_FILENO, F_GETFD);
50 /* If either stdin or stdout was closed (that is, fcntl failed),
51 then we open a dummy close-on-exec fd to occupy that slot. That
52 way, popen's internal use of pipe() will not contain either fd 0
53 or 1, overcoming the fact that the child process blindly calls
54 close() on the parent's end of the pipe without first checking
55 whether it is clobbering the fd just placed there via dup2(); the
56 exec will get rid of the dummy fd's in the child. Fortunately,
57 closed stderr in the parent does not cause problems in the
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 = popen (filename, mode);
74 /* Now, close any dummy fd's created in the parent. */
79 close (STDOUT_FILENO);