1 /* Filtering of data through a subprocess.
2 Copyright (C) 2001-2003, 2008-2013 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2009.
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/>. */
20 #include "pipe-filter.h"
28 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
32 # include <sys/select.h>
36 #include "spawn-pipe.h"
37 #include "wait-process.h"
40 #define _(str) gettext (str)
42 #include "pipe-filter-aux.h"
44 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
48 /* Arguments passed to pipe_filter_ii_execute. */
49 prepare_write_fn prepare_write;
50 done_write_fn done_write;
51 prepare_read_fn prepare_read;
52 done_read_fn done_read;
54 /* Management of the subprocess. */
58 /* Status of the writer part. */
59 volatile bool writer_terminated;
60 volatile int writer_errno;
61 /* Status of the reader part. */
62 volatile bool reader_terminated;
63 volatile int reader_errno;
66 static unsigned int WINAPI
67 writer_thread_func (void *thread_arg)
69 struct locals *l = (struct locals *) thread_arg;
74 const void *buf = l->prepare_write (&bufsize, l->private_data);
78 write (l->fd[1], buf, bufsize > SSIZE_MAX ? SSIZE_MAX : bufsize);
81 /* Don't assume that the gnulib modules 'write' and 'sigpipe' are
83 if (GetLastError () == ERROR_NO_DATA)
85 l->writer_errno = errno;
88 else if (nwritten > 0)
89 l->done_write ((void *) buf, nwritten, l->private_data);
95 l->writer_terminated = true;
96 _endthreadex (0); /* calls ExitThread (0) */
100 static unsigned int WINAPI
101 reader_thread_func (void *thread_arg)
103 struct locals *l = (struct locals *) thread_arg;
108 void *buf = l->prepare_read (&bufsize, l->private_data);
109 if (!(buf != NULL && bufsize > 0))
110 /* prepare_read returned wrong values. */
114 read (l->fd[0], buf, bufsize > SSIZE_MAX ? SSIZE_MAX : bufsize);
117 l->reader_errno = errno;
121 l->done_read (buf, nread, l->private_data);
122 else /* nread == 0 */
127 l->reader_terminated = true;
128 _endthreadex (0); /* calls ExitThread (0) */
135 pipe_filter_ii_execute (const char *progname,
136 const char *prog_path, const char **prog_argv,
137 bool null_stderr, bool exit_on_error,
138 prepare_write_fn prepare_write,
139 done_write_fn done_write,
140 prepare_read_fn prepare_read,
141 done_read_fn done_read,
146 #if !((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
147 struct sigaction orig_sigpipe_action;
150 /* Open a bidirectional pipe to a subprocess. */
151 child = create_pipe_bidi (progname, prog_path, (char **) prog_argv,
152 null_stderr, true, exit_on_error,
157 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
158 /* Native Windows API. */
159 /* Pipes have a non-blocking mode, see function SetNamedPipeHandleState and
160 the article "Named Pipe Type, Read, and Wait Modes", but Microsoft's
161 documentation discourages its use. So don't use it.
162 Asynchronous I/O is also not suitable because it notifies the caller only
163 about completion of the I/O request, not about intermediate progress.
164 So do the writing and the reading in separate threads. */
168 #define writer_thread_handle handles[0]
169 #define reader_thread_handle handles[1]
170 bool writer_cleaned_up;
171 bool reader_cleaned_up;
173 l.prepare_write = prepare_write;
174 l.done_write = done_write;
175 l.prepare_read = prepare_read;
176 l.done_read = done_read;
177 l.private_data = private_data;
180 l.writer_terminated = false;
182 l.reader_terminated = false;
185 writer_thread_handle =
186 (HANDLE) _beginthreadex (NULL, 100000, writer_thread_func, &l, 0, NULL);
187 reader_thread_handle =
188 (HANDLE) _beginthreadex (NULL, 100000, reader_thread_func, &l, 0, NULL);
189 if (writer_thread_handle == NULL || reader_thread_handle == NULL)
192 error (EXIT_FAILURE, 0, _("creation of threads failed"));
193 if (reader_thread_handle != NULL)
194 CloseHandle (reader_thread_handle);
195 if (writer_thread_handle != NULL)
196 CloseHandle (writer_thread_handle);
199 writer_cleaned_up = false;
200 reader_cleaned_up = false;
205 /* Here !(writer_cleaned_up && reader_cleaned_up). */
206 if (writer_cleaned_up)
207 ret = WaitForSingleObject (reader_thread_handle, INFINITE);
208 else if (reader_cleaned_up)
209 ret = WaitForSingleObject (writer_thread_handle, INFINITE);
211 ret = WaitForMultipleObjects (2, handles, FALSE, INFINITE);
212 if (!(ret == WAIT_OBJECT_0 + 0 || ret == WAIT_OBJECT_0 + 1))
215 if (l.writer_terminated)
217 /* The writer thread has just terminated. */
218 l.writer_terminated = false;
219 CloseHandle (writer_thread_handle);
223 error (EXIT_FAILURE, l.writer_errno,
224 _("write to %s subprocess failed"), progname);
225 if (!reader_cleaned_up)
227 TerminateThread (reader_thread_handle, 1);
228 CloseHandle (reader_thread_handle);
232 /* Tell the child there is nothing more the parent will send. */
234 writer_cleaned_up = true;
236 if (l.reader_terminated)
238 /* The reader thread has just terminated. */
239 l.reader_terminated = false;
240 CloseHandle (reader_thread_handle);
244 error (EXIT_FAILURE, l.reader_errno,
245 _("read from %s subprocess failed"), progname);
246 if (!writer_cleaned_up)
248 TerminateThread (writer_thread_handle, 1);
249 CloseHandle (writer_thread_handle);
253 reader_cleaned_up = true;
255 if (writer_cleaned_up && reader_cleaned_up)
260 /* When we write to the child process and it has just terminated,
261 we don't want to die from a SIGPIPE signal. So set the SIGPIPE
262 handler to SIG_IGN, and handle EPIPE error codes in write(). */
264 struct sigaction sigpipe_action;
266 sigpipe_action.sa_handler = SIG_IGN;
267 sigpipe_action.sa_flags = 0;
268 sigemptyset (&sigpipe_action.sa_mask);
269 if (sigaction (SIGPIPE, &sigpipe_action, &orig_sigpipe_action) < 0)
275 fd_set readfds; /* All bits except fd[0] are always cleared. */
276 fd_set writefds; /* All bits except fd[1] are always cleared. */
280 /* Enable non-blocking I/O. This permits the read() and write() calls
281 to return -1/EAGAIN without blocking; this is important for polling
282 if HAVE_SELECT is not defined. It also permits the read() and write()
283 calls to return after partial reads/writes; this is important if
284 HAVE_SELECT is defined, because select() only says that some data
285 can be read or written, not how many. Without non-blocking I/O,
286 Linux 2.2.17 and BSD systems prefer to block instead of returning
287 with partial results. */
291 if ((fcntl_flags = fcntl (fd[1], F_GETFL, 0)) < 0
292 || fcntl (fd[1], F_SETFL, fcntl_flags | O_NONBLOCK) == -1
293 || (fcntl_flags = fcntl (fd[0], F_GETFL, 0)) < 0
294 || fcntl (fd[0], F_SETFL, fcntl_flags | O_NONBLOCK) == -1)
297 error (EXIT_FAILURE, errno,
298 _("cannot set up nonblocking I/O to %s subprocess"),
308 done_writing = false;
314 FD_SET (fd[0], &readfds);
318 FD_SET (fd[1], &writefds);
323 n = select (n, &readfds, (!done_writing ? &writefds : NULL), NULL,
328 error (EXIT_FAILURE, errno,
329 _("communication with %s subprocess failed"), progname);
332 if (!done_writing && FD_ISSET (fd[1], &writefds))
334 if (FD_ISSET (fd[0], &readfds))
336 /* How could select() return if none of the two descriptors is ready? */
340 /* Attempt to write. */
347 const void *buf = prepare_write (&bufsize, private_data);
350 /* Writing to a pipe in non-blocking mode is tricky: The
351 write() call may fail with EAGAIN, simply because sufficient
352 space is not available in the pipe. See POSIX:2008
353 <http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html>.
354 This happens actually on AIX and IRIX, when bufsize >= 8192
355 (even though PIPE_BUF and pathconf ("/", _PC_PIPE_BUF) are
357 size_t attempt_to_write =
358 (bufsize > SSIZE_MAX ? SSIZE_MAX : bufsize);
361 ssize_t nwritten = write (fd[1], buf, attempt_to_write);
366 attempt_to_write = attempt_to_write / 2;
367 if (attempt_to_write == 0)
370 else if (!IS_EAGAIN (errno))
373 error (EXIT_FAILURE, errno,
374 _("write to %s subprocess failed"),
382 done_write ((void *) buf, nwritten, private_data);
389 /* Tell the child there is nothing more the parent will send. */
398 /* Attempt to read. */
404 void *buf = prepare_read (&bufsize, private_data);
405 if (!(buf != NULL && bufsize > 0))
406 /* prepare_read returned wrong values. */
410 read (fd[0], buf, bufsize > SSIZE_MAX ? SSIZE_MAX : bufsize);
413 if (!IS_EAGAIN (errno))
416 error (EXIT_FAILURE, errno,
417 _("read from %s subprocess failed"), progname);
422 done_read (buf, nread, private_data);
423 else /* nread == 0 */
436 /* Restore SIGPIPE signal handler. */
437 if (sigaction (SIGPIPE, &orig_sigpipe_action, NULL) < 0)
443 /* Remove zombie process from process list. */
446 wait_subprocess (child, progname, false, null_stderr,
447 true, exit_on_error, NULL);
448 if (exitstatus != 0 && exit_on_error)
449 error (EXIT_FAILURE, 0, _("%s subprocess terminated with exit code %d"),
450 progname, exitstatus);
456 int saved_errno = errno;
458 #if !((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
459 if (sigaction (SIGPIPE, &orig_sigpipe_action, NULL) < 0)
463 wait_subprocess (child, progname, true, true, true, false, NULL);