1 /* gspawn-win32.c - Process launching on Win32
3 * Copyright 2000 Red Hat, Inc.
5 * GLib is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * GLib 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 GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with GLib; see the file COPYING.LIB. If not, write
17 * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
22 * Implementation details on Win32.
24 * - There is no way to set the no-inherit flag for
25 * a "file descriptor" in the MS C runtime. The flag is there,
26 * and the dospawn() function uses it, but unfortunately
27 * this flag can only be set when opening the file.
28 * - As there is no fork(), we cannot reliably change directory
29 * before starting the child process. (There might be several threads
30 * running, and the current directory is common for all threads.)
32 * Thus, we must in most cases use a helper program to handle closing
33 * of (inherited) file descriptors and changing of directory. In fact,
34 * we do it all the time.
37 /* Define this to get some logging all the time */
38 /* #define G_SPAWN_WIN32_DEBUG */
55 #ifdef G_SPAWN_WIN32_DEBUG
57 #define SETUP_DEBUG() /* empty */
60 static int debug = -1;
61 #define SETUP_DEBUG() \
66 if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
83 ARG_CHILD_ERR_REPORT = 1,
87 ARG_WORKING_DIRECTORY,
88 ARG_CLOSE_DESCRIPTORS,
92 ARG_COUNT = ARG_PROGRAM
97 static gboolean make_pipe (gint p[2],
99 static gboolean fork_exec_with_pipes (gboolean dont_wait,
100 const gchar *working_directory,
103 gboolean close_descriptors,
104 gboolean search_path,
105 gboolean stdout_to_null,
106 gboolean stderr_to_null,
107 gboolean child_inherits_stdin,
108 GSpawnChildSetupFunc child_setup,
110 gint *standard_input,
111 gint *standard_output,
112 gint *standard_error,
117 g_spawn_error_quark (void)
119 static GQuark quark = 0;
121 quark = g_quark_from_static_string ("g-exec-error-quark");
127 * @working_directory: child's current working directory, or %NULL to inherit parent's
128 * @argv: child's argument vector
129 * @envp: child's environment, or %NULL to inherit parent's
130 * @flags: flags from #GSpawnFlags
131 * @child_setup: function to run in the child just before <function>exec()</function>
132 * @user_data: user data for @child_setup
133 * @child_pid: return location for child process ID, or %NULL
134 * @error: return location for error
136 * See g_spawn_async_with_pipes() for a full description; this function
137 * simply calls the g_spawn_async_with_pipes() without any pipes.
139 * Return value: %TRUE on success, %FALSE if error is set
142 g_spawn_async (const gchar *working_directory,
146 GSpawnChildSetupFunc child_setup,
151 g_return_val_if_fail (argv != NULL, FALSE);
153 return g_spawn_async_with_pipes (working_directory,
163 /* Avoids a danger in threaded situations (calling close()
164 * on a file descriptor twice, and another thread has
165 * re-opened it since the first close)
168 close_and_invalidate (gint *fd)
180 READ_FAILED = 0, /* FALSE */
186 read_data (GString *str,
187 GIOChannel *iochannel,
196 gioerror = g_io_channel_read (iochannel, buf, sizeof (buf), &bytes);
202 g_string_append_len (str, buf, bytes);
205 else if (gioerror == G_IO_ERROR_AGAIN)
207 else if (gioerror != G_IO_ERROR_NONE)
212 _("Failed to read data from child process"));
222 * @working_directory: child's current working directory, or %NULL to inherit parent's
223 * @argv: child's argument vector
224 * @envp: child's environment, or %NULL to inherit parent's
225 * @flags: flags from #GSpawnFlags
226 * @child_setup: function to run in the child just before <function>exec()</function>
227 * @user_data: user data for @child_setup
228 * @standard_output: return location for child output
229 * @standard_error: return location for child error messages
230 * @exit_status: child exit status, as returned by <function>waitpid()</function>
231 * @error: return location for error
233 * Executes a child synchronously (waits for the child to exit before returning).
234 * All output from the child is stored in @standard_output and @standard_error,
235 * if those parameters are non-%NULL. If @exit_status is non-%NULL, the exit status
236 * of the child is stored there as it would be returned by <function>waitpid()</function>; standard UNIX
237 * macros such as <function>WIFEXITED()</function> and <function>WEXITSTATUS()</function> must be used to evaluate the
238 * exit status. If an error occurs, no data is returned in @standard_output,
239 * @standard_error, or @exit_status.
241 * This function calls g_spawn_async_with_pipes() internally; see that function
242 * for full details on the other parameters.
244 * Return value: %TRUE on success, %FALSE if an error was set.
247 g_spawn_sync (const gchar *working_directory,
251 GSpawnChildSetupFunc child_setup,
253 gchar **standard_output,
254 gchar **standard_error,
260 GIOChannel *outchannel = NULL;
261 GIOChannel *errchannel = NULL;
262 GPollFD outfd, errfd;
268 GString *outstr = NULL;
269 GString *errstr = NULL;
273 g_return_val_if_fail (argv != NULL, FALSE);
274 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
275 g_return_val_if_fail (standard_output == NULL ||
276 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
277 g_return_val_if_fail (standard_error == NULL ||
278 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
280 /* Just to ensure segfaults if callers try to use
281 * these when an error is reported.
284 *standard_output = NULL;
287 *standard_error = NULL;
289 if (!fork_exec_with_pipes (FALSE,
293 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
294 (flags & G_SPAWN_SEARCH_PATH) != 0,
295 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
296 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
297 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
301 standard_output ? &outpipe : NULL,
302 standard_error ? &errpipe : NULL,
307 /* Read data from child. */
313 outstr = g_string_new ("");
314 outchannel = g_io_channel_win32_new_fd (outpipe);
315 g_io_channel_win32_make_pollfd (outchannel,
316 G_IO_IN | G_IO_ERR | G_IO_HUP,
322 errstr = g_string_new ("");
323 errchannel = g_io_channel_win32_new_fd (errpipe);
324 g_io_channel_win32_make_pollfd (errchannel,
325 G_IO_IN | G_IO_ERR | G_IO_HUP,
329 /* Read data until we get EOF on both pipes. */
349 g_print ("%s:g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
352 ret = g_io_channel_win32_poll (fds, nfds, -1);
361 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
366 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
368 switch (read_data (outstr, outchannel, error))
372 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
377 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
378 g_io_channel_unref (outchannel);
380 close_and_invalidate (&outpipe);
384 g_print ("g_spawn_sync: outchannel: OK\n");
392 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
394 switch (read_data (errstr, errchannel, error))
398 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
403 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
404 g_io_channel_unref (errchannel);
406 close_and_invalidate (&errpipe);
410 g_print ("g_spawn_sync: errchannel: OK\n");
419 /* These should only be open still if we had an error. */
421 if (outchannel != NULL)
422 g_io_channel_unref (outchannel);
423 if (errchannel != NULL)
424 g_io_channel_unref (errchannel);
426 close_and_invalidate (&outpipe);
428 close_and_invalidate (&errpipe);
433 g_string_free (outstr, TRUE);
435 g_string_free (errstr, TRUE);
442 *exit_status = status;
445 *standard_output = g_string_free (outstr, FALSE);
448 *standard_error = g_string_free (errstr, FALSE);
455 * g_spawn_async_with_pipes:
456 * @working_directory: child's current working directory, or %NULL to inherit parent's
457 * @argv: child's argument vector
458 * @envp: child's environment, or %NULL to inherit parent's
459 * @flags: flags from #GSpawnFlags
460 * @child_setup: function to run in the child just before <function>exec()</function>
461 * @user_data: user data for @child_setup
462 * @child_pid: return location for child process ID, or %NULL
463 * @standard_input: return location for file descriptor to write to child's stdin, or %NULL
464 * @standard_output: return location for file descriptor to read child's stdout, or %NULL
465 * @standard_error: return location for file descriptor to read child's stderr, or %NULL
466 * @error: return location for error
468 * Executes a child program asynchronously (your program will not
469 * block waiting for the child to exit). The child program is
470 * specified by the only argument that must be provided, @argv. @argv
471 * should be a %NULL-terminated array of strings, to be passed as the
472 * argument vector for the child. The first string in @argv is of
473 * course the name of the program to execute. By default, the name of
474 * the program must be a full path; the <envar>PATH</envar> shell variable will only
475 * be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
477 * @envp is a %NULL-terminated array of strings, where each string
478 * has the form <literal>KEY=VALUE</literal>. This will become
479 * the child's environment. If @envp is %NULL, the child inherits its
480 * parent's environment.
482 * @flags should be the bitwise OR of any flags you want to affect the
483 * function's behavior. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
484 * child will not be automatically reaped; you must call
485 * <function>waitpid()</function> or handle %SIGCHLD yourself, or the
486 * child will become a zombie. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means
487 * that the parent's open file descriptors will be inherited by the child;
488 * otherwise all descriptors except stdin/stdout/stderr will be closed before
489 * calling <function>exec()</function> in the child. %G_SPAWN_SEARCH_PATH
490 * means that <literal>argv[0]</literal> need not be an absolute path, it
491 * will be looked for in the user's <envar>PATH</envar>.
492 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
493 * will be discarded, instead of going to the same location as the parent's
494 * standard output. %G_SPAWN_STDERR_TO_DEV_NULL means that the child's
495 * standard error will be discarded. %G_SPAWN_CHILD_INHERITS_STDIN means that
496 * the child will inherit the parent's standard input (by default,
497 * the child's standard input is attached to /dev/null).
499 * @child_setup and @user_data are a function and user data to be
500 * called in the child after GLib has performed all the setup it plans
501 * to perform (including creating pipes, closing file descriptors,
502 * etc.) but before calling <function>exec()</function>. That is, @child_setup
503 * is called just before calling <function>exec()</function> in the child.
504 * Obviously actions taken in this function will only affect the child, not
507 * If non-%NULL, @child_pid will be filled with the child's process
508 * ID. You can use the process ID to send signals to the child, or
509 * to <function>waitpid()</function> if you specified the
510 * %G_SPAWN_DO_NOT_REAP_CHILD flag.
512 * If non-%NULL, the @standard_input, @standard_output, @standard_error
513 * locations will be filled with file descriptors for writing to the child's
514 * standard input or reading from its standard output or standard error.
515 * The caller of g_spawn_async_with_pipes() must close these file descriptors
516 * when they are no longer in use. If these parameters are %NULL, the
517 * corresponding pipe won't be created.
519 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
520 * If an error is set, the function returns %FALSE. Errors
521 * are reported even if they occur in the child (for example if the
522 * executable in <literal>argv[0]</literal> is not found). Typically
523 * the <literal>message</literal> field of returned errors should be displayed
524 * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
526 * If an error occurs, @child_pid, @standard_input, @standard_output,
527 * and @standard_error will not be filled with valid values.
529 * Return value: %TRUE on success, %FALSE if an error was set
532 g_spawn_async_with_pipes (const gchar *working_directory,
536 GSpawnChildSetupFunc child_setup,
539 gint *standard_input,
540 gint *standard_output,
541 gint *standard_error,
544 g_return_val_if_fail (argv != NULL, FALSE);
545 g_return_val_if_fail (standard_output == NULL ||
546 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
547 g_return_val_if_fail (standard_error == NULL ||
548 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
549 /* can't inherit stdin if we have an input pipe. */
550 g_return_val_if_fail (standard_input == NULL ||
551 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
553 return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
557 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
558 (flags & G_SPAWN_SEARCH_PATH) != 0,
559 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
560 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
561 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
572 * g_spawn_command_line_sync:
573 * @command_line: a command line
574 * @standard_output: return location for child output
575 * @standard_error: return location for child errors
576 * @exit_status: return location for child exit status
577 * @error: return location for errors
579 * A simple version of g_spawn_sync() with little-used parameters
580 * removed, taking a command line instead of an argument vector. See
581 * g_spawn_sync() for full details. @command_line will be parsed by
582 * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
583 * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
584 * implications, so consider using g_spawn_sync() directly if
585 * appropriate. Possible errors are those from g_spawn_sync() and those
586 * from g_shell_parse_argv().
588 * Return value: %TRUE on success, %FALSE if an error was set
591 g_spawn_command_line_sync (const gchar *command_line,
592 gchar **standard_output,
593 gchar **standard_error,
600 g_return_val_if_fail (command_line != NULL, FALSE);
602 if (!g_shell_parse_argv (command_line,
607 retval = g_spawn_sync (NULL,
623 * g_spawn_command_line_async:
624 * @command_line: a command line
625 * @error: return location for errors
627 * A simple version of g_spawn_async() that parses a command line with
628 * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
629 * command line in the background. Unlike g_spawn_async(), the
630 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
631 * that %G_SPAWN_SEARCH_PATH can have security implications, so
632 * consider using g_spawn_async() directly if appropriate. Possible
633 * errors are those from g_shell_parse_argv() and g_spawn_async().
635 * Return value: %TRUE on success, %FALSE if error is set.
638 g_spawn_command_line_async (const gchar *command_line,
644 g_return_val_if_fail (command_line != NULL, FALSE);
646 if (!g_shell_parse_argv (command_line,
651 retval = g_spawn_async (NULL,
665 do_exec (gboolean dont_wait,
666 gint child_err_report_fd,
670 const gchar *working_directory,
673 gboolean close_descriptors,
674 gboolean search_path,
675 gboolean stdout_to_null,
676 gboolean stderr_to_null,
677 gboolean child_inherits_stdin,
678 GSpawnChildSetupFunc child_setup,
682 gchar args[ARG_COUNT][10];
691 new_argv = g_new (gchar *, argc + 1 + ARG_COUNT);
693 new_argv[0] = "gspawn-win32-helper";
694 sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_fd);
695 new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
699 sprintf (args[ARG_STDIN], "%d", stdin_fd);
700 new_argv[ARG_STDIN] = args[ARG_STDIN];
702 else if (child_inherits_stdin)
704 /* Let stdin be alone */
705 new_argv[ARG_STDIN] = "-";
709 /* Keep process from blocking on a read of stdin */
710 new_argv[ARG_STDIN] = "z";
715 sprintf (args[ARG_STDOUT], "%d", stdout_fd);
716 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
718 else if (stdout_to_null)
720 new_argv[ARG_STDOUT] = "z";
724 new_argv[ARG_STDOUT] = "-";
729 sprintf (args[ARG_STDERR], "%d", stderr_fd);
730 new_argv[ARG_STDERR] = args[ARG_STDERR];
732 else if (stderr_to_null)
734 new_argv[ARG_STDERR] = "z";
738 new_argv[ARG_STDERR] = "-";
741 if (working_directory && *working_directory)
742 new_argv[ARG_WORKING_DIRECTORY] = working_directory;
744 new_argv[ARG_WORKING_DIRECTORY] = "-";
746 if (close_descriptors)
747 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
749 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
752 new_argv[ARG_USE_PATH] = "y";
754 new_argv[ARG_USE_PATH] = "-";
757 new_argv[ARG_WAIT] = "-";
759 new_argv[ARG_WAIT] = "w";
761 for (i = 0; i <= argc; i++)
762 new_argv[ARG_PROGRAM + i] = argv[i];
764 /* Call user function just before we execute the helper program,
765 * which executes the program. Dunno what's the usefulness of this.
766 * A child setup function used on Unix probably isn't of much use
767 * as such on Win32, anyhow
771 (* child_setup) (user_data);
776 g_print ("calling gspawn-win32-helper with argv:\n");
777 for (i = 0; i < argc + 1 + ARG_COUNT; i++)
778 g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
782 /* Let's hope envp hasn't mucked with PATH so that
783 * gspawn-win32-helper.exe isn't found.
785 spawnvpe (P_NOWAIT, "gspawn-win32-helper", new_argv, envp);
787 spawnvp (P_NOWAIT, "gspawn-win32-helper", new_argv);
789 /* FIXME: What if gspawn-win32-helper.exe isn't found? */
791 /* Close the child_err_report_fd and the other process's ends of the
792 * pipes in this process, otherwise the reader will never get
795 close (child_err_report_fd);
817 while (bytes < sizeof(gint)*n_ints_in_buf)
822 g_print ("%s:read_ints: trying to read %d bytes from pipe...\n",
824 sizeof(gint)*n_ints_in_buf - bytes);
826 chunk = read (fd, ((gchar*)buf) + bytes,
827 sizeof(gint)*n_ints_in_buf - bytes);
830 g_print ("... got %d bytes\n", chunk);
834 /* Some weird shit happened, bail out */
838 G_SPAWN_ERROR_FAILED,
839 _("Failed to read from child pipe (%s)"),
850 *n_ints_read = bytes/sizeof(gint);
856 fork_exec_with_pipes (gboolean dont_wait,
857 const gchar *working_directory,
860 gboolean close_descriptors,
861 gboolean search_path,
862 gboolean stdout_to_null,
863 gboolean stderr_to_null,
864 gboolean child_inherits_stdin,
865 GSpawnChildSetupFunc child_setup,
867 gint *standard_input,
868 gint *standard_output,
869 gint *standard_error,
873 gint stdin_pipe[2] = { -1, -1 };
874 gint stdout_pipe[2] = { -1, -1 };
875 gint stderr_pipe[2] = { -1, -1 };
876 gint child_err_report_pipe[2] = { -1, -1 };
881 if (!make_pipe (child_err_report_pipe, error))
884 if (standard_input && !make_pipe (stdin_pipe, error))
885 goto cleanup_and_fail;
887 if (standard_output && !make_pipe (stdout_pipe, error))
888 goto cleanup_and_fail;
890 if (standard_error && !make_pipe (stderr_pipe, error))
891 goto cleanup_and_fail;
893 status = do_exec (dont_wait,
894 child_err_report_pipe[1],
905 child_inherits_stdin,
909 if (!read_ints (child_err_report_pipe[0],
912 goto cleanup_and_fail;
916 /* Error from the child. */
923 case CHILD_CHDIR_FAILED:
927 _("Failed to change to directory '%s' (%s)"),
929 g_strerror (buf[1]));
930 goto cleanup_and_fail;
932 case CHILD_SPAWN_FAILED:
935 G_SPAWN_ERROR_FAILED,
936 _("Failed to execute child process (%s)"),
937 g_strerror (buf[1]));
938 goto cleanup_and_fail;
942 /* Success against all odds! return the information */
945 *standard_input = stdin_pipe[1];
947 *standard_output = stdout_pipe[0];
949 *standard_error = stderr_pipe[0];
951 *exit_status = status;
956 close_and_invalidate (&child_err_report_pipe[0]);
957 close_and_invalidate (&child_err_report_pipe[1]);
958 close_and_invalidate (&stdin_pipe[0]);
959 close_and_invalidate (&stdin_pipe[1]);
960 close_and_invalidate (&stdout_pipe[0]);
961 close_and_invalidate (&stdout_pipe[1]);
962 close_and_invalidate (&stderr_pipe[0]);
963 close_and_invalidate (&stderr_pipe[1]);
969 make_pipe (gint p[2],
976 G_SPAWN_ERROR_FAILED,
977 _("Failed to create pipe for communicating with child process (%s)"),
985 #endif /* !GSPAWN_HELPER */