1 /* Synchronous subprocess invocation for XEmacs.
2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95 Free Software Foundation, Inc.
4 This file is part of XEmacs.
6 XEmacs is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 XEmacs is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with XEmacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* Synched up with: Mule 2.0, FSF 19.30. */
22 /* Partly sync'ed with 19.36.4 */
35 #include "file-coding.h"
40 #include "sysfile.h" /* Always include after sysproc.h */
41 #include "syssignal.h" /* Always include before systty.h */
45 #define _P_NOWAIT 1 /* from process.h */
50 /* When we are starting external processes we need to know whether they
51 take binary input (no conversion) or text input (\n is converted to
52 \r\n). Similarly for output: if newlines are written as \r\n then it's
53 text process output, otherwise it's binary. */
54 Lisp_Object Vbinary_process_input;
55 Lisp_Object Vbinary_process_output;
56 #endif /* WIN32_NATIVE */
58 Lisp_Object Vshell_file_name;
60 /* The environment to pass to all subprocesses when they are started.
61 This is in the semi-bogus format of ("VAR=VAL" "VAR2=VAL2" ... )
63 Lisp_Object Vprocess_environment;
65 /* True iff we are about to fork off a synchronous process or if we
66 are waiting for it. */
67 volatile int synch_process_alive;
69 /* Nonzero => this is a string explaining death of synchronous subprocess. */
70 const char *synch_process_death;
72 /* If synch_process_death is zero,
73 this is exit code of synchronous subprocess. */
74 int synch_process_retcode;
76 /* Clean up when exiting Fcall_process_internal.
77 On Windows, delete the temporary file on any kind of termination.
78 On Unix, kill the process and any children on termination by signal. */
80 /* Nonzero if this is termination due to exit. */
81 static int call_process_exited;
83 Lisp_Object Vlisp_EXEC_SUFFIXES;
86 call_process_kill (Lisp_Object fdpid)
88 Lisp_Object fd = Fcar (fdpid);
89 Lisp_Object pid = Fcdr (fdpid);
95 EMACS_KILLPG (XINT (pid), SIGKILL);
97 synch_process_alive = 0;
102 call_process_cleanup (Lisp_Object fdpid)
104 int fd = XINT (Fcar (fdpid));
105 int pid = XINT (Fcdr (fdpid));
107 if (!call_process_exited &&
108 EMACS_KILLPG (pid, SIGINT) == 0)
110 int speccount = specpdl_depth ();
112 record_unwind_protect (call_process_kill, fdpid);
113 /* #### "c-G" -- need non-consing Single-key-description */
114 message ("Waiting for process to die...(type C-g again to kill it instantly)");
118 HANDLE pHandle = OpenProcess (PROCESS_ALL_ACCESS, 0, pid);
120 warn_when_safe (Qprocess, Qwarning,
121 "cannot open process (PID %d) for cleanup", pid);
123 wait_for_termination (pHandle);
126 wait_for_termination (pid);
129 /* "Discard" the unwind protect. */
132 unbind_to (speccount, Qnil);
134 message ("Waiting for process to die... done");
136 synch_process_alive = 0;
141 static Lisp_Object fork_error;
144 report_fork_error (char *string, Lisp_Object data)
146 Lisp_Object errstring = lisp_strerror (errno);
148 fork_error = Fcons (build_string (string), Fcons (errstring, data));
150 /* terminate this branch of the fork, without closing stdin/out/etc. */
155 DEFUN ("old-call-process-internal", Fold_call_process_internal, 1, MANY, 0, /*
156 Call PROGRAM synchronously in separate process, with coding-system specified.
158 (PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS).
159 The program's input comes from file INFILE (nil means `/dev/null').
160 Insert output in BUFFER before point; t means current buffer;
161 nil for BUFFER means discard it; 0 means discard and don't wait.
162 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
163 REAL-BUFFER says what to do with standard output, as above,
164 while STDERR-FILE says what to do with standard error in the child.
165 STDERR-FILE may be nil (discard standard error output),
166 t (mix it with ordinary output), or a file name string.
168 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
169 Remaining arguments are strings passed as command arguments to PROGRAM.
171 If BUFFER is 0, `call-process' returns immediately with value nil.
172 Otherwise it waits for PROGRAM to terminate and returns a numeric exit status
173 or a signal description string.
174 If you quit, the process is killed with SIGINT, or SIGKILL if you
177 (int nargs, Lisp_Object *args))
179 /* This function can GC */
180 Lisp_Object infile, buffer, current_dir, display, path;
190 int speccount = specpdl_depth ();
191 struct gcpro gcpro1, gcpro2, gcpro3;
192 char **new_argv = alloca_array (char *, max (2, nargs - 2));
194 /* File to use for stderr in the child.
195 t means use same as standard output. */
196 Lisp_Object error_file;
198 CHECK_STRING (args[0]);
202 #if defined (NO_SUBPROCESSES)
203 /* Without asynchronous processes we cannot have BUFFER == 0. */
204 if (nargs >= 3 && !INTP (args[2]))
205 error ("Operating system cannot handle asynchronous subprocesses");
206 #endif /* NO_SUBPROCESSES */
208 /* Do this before building new_argv because GC in Lisp code
209 * called by various filename-hacking routines might relocate strings */
210 locate_file (Vexec_path, args[0], Vlisp_EXEC_SUFFIXES, &path, X_OK);
212 /* Make sure that the child will be able to chdir to the current
213 buffer's current directory, or its unhandled equivalent. We
214 can't just have the child check for an error when it does the
215 chdir, since it's in a vfork. */
217 struct gcpro ngcpro1, ngcpro2;
218 /* Do this test before building new_argv because GC in Lisp code
219 * called by various filename-hacking routines might relocate strings */
220 /* Make sure that the child will be able to chdir to the current
221 buffer's current directory. We can't just have the child check
222 for an error when it does the chdir, since it's in a vfork. */
224 NGCPRO2 (current_dir, path); /* Caller gcprotects args[] */
225 current_dir = current_buffer->directory;
226 current_dir = Funhandled_file_name_directory (current_dir);
227 current_dir = expand_and_dir_to_file (current_dir, Qnil);
229 /* This is in FSF, but it breaks everything in the presence of
230 ange-ftp-visited files, so away with it. */
231 if (NILP (Ffile_accessible_directory_p (current_dir)))
232 report_file_error ("Setting current directory",
233 Fcons (current_buffer->directory, Qnil));
238 GCPRO2 (current_dir, path);
240 if (nargs >= 2 && ! NILP (args[1]))
242 struct gcpro ngcpro1;
243 NGCPRO1 (current_buffer->directory);
244 infile = Fexpand_file_name (args[1], current_buffer->directory);
246 CHECK_STRING (infile);
249 infile = build_string (NULL_DEVICE);
253 GCPRO3 (infile, current_dir, path); /* Fexpand_file_name might trash it */
259 /* If BUFFER is a list, its meaning is
260 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
263 if (CONSP (XCDR (buffer)))
265 Lisp_Object file_for_stderr = XCAR (XCDR (buffer));
267 if (NILP (file_for_stderr) || EQ (Qt, file_for_stderr))
268 error_file = file_for_stderr;
270 error_file = Fexpand_file_name (file_for_stderr, Qnil);
273 buffer = XCAR (buffer);
276 if (!(EQ (buffer, Qnil)
280 Lisp_Object spec_buffer = buffer;
281 buffer = Fget_buffer (buffer);
282 /* Mention the buffer name for a better error message. */
284 CHECK_BUFFER (spec_buffer);
285 CHECK_BUFFER (buffer);
293 display = ((nargs >= 4) ? args[3] : Qnil);
295 /* From here we assume we won't GC (unless an error is signaled). */
298 for (i = 4; i < nargs; i++)
300 CHECK_STRING (args[i]);
301 new_argv[i - 3] = (char *) XSTRING_DATA (args[i]);
304 new_argv[max(nargs - 3,1)] = 0;
307 report_file_error ("Searching for program", Fcons (args[0], Qnil));
308 new_argv[0] = (char *) XSTRING_DATA (path);
310 filefd = open ((char *) XSTRING_DATA (infile), O_RDONLY | OPEN_BINARY, 0);
312 report_file_error ("Opening process input file", Fcons (infile, Qnil));
316 fd[1] = open (NULL_DEVICE, O_WRONLY | OPEN_BINARY, 0);
323 /* Replaced by close_process_descs */
324 set_exclusive_use (fd[0]);
329 /* child_setup must clobber environ in systems with true vfork.
330 Protect it from permanent change. */
331 REGISTER char **save_environ = environ;
332 REGISTER int fd1 = fd[1];
338 /* Record that we're about to create a synchronous process. */
339 synch_process_alive = 1;
341 /* These vars record information from process termination.
342 Clear them now before process can possibly terminate,
343 to avoid timing error if process terminates soon. */
344 synch_process_death = 0;
345 synch_process_retcode = 0;
347 if (NILP (error_file))
348 fd_error = open (NULL_DEVICE, O_WRONLY | OPEN_BINARY);
349 else if (STRINGP (error_file))
351 fd_error = open ((const char *) XSTRING_DATA (error_file),
353 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
355 #else /* not WIN32_NATIVE */
356 O_WRONLY | O_TRUNC | O_CREAT | OPEN_BINARY,
358 #endif /* not WIN32_NATIVE */
364 int save_errno = errno;
370 report_file_error ("Cannot open", Fcons(error_file, Qnil));
375 pid = child_setup (filefd, fd1, fd_error, new_argv,
376 (char *) XSTRING_DATA (current_dir));
379 /* OpenProcess() as soon after child_setup as possible. It's too
380 late once the process terminated. */
381 pHandle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
385 /* #### seems to cause crash in unbind_to(...) below. APA */
386 warn_when_safe (Qprocess, Qwarning,
387 "cannot open process to wait for");
391 /* Close STDERR into the parent process. We no longer need it. */
394 #else /* not WIN32_NATIVE */
401 /* This is necessary because some shells may attempt to
402 access the current controlling terminal and will hang
403 if they are run in the background, as will be the case
404 when XEmacs is started in the background. Martin
405 Buchholz observed this problem running a subprocess
406 that used zsh to call gzip to uncompress an info
408 disconnect_controlling_terminal ();
409 child_setup (filefd, fd1, fd_error, new_argv,
410 (char *) XSTRING_DATA (current_dir));
415 #endif /* not WIN32_NATIVE */
417 environ = save_environ;
419 /* Close most of our fd's, but not fd[0]
420 since we will use that to read input from. */
426 if (!NILP (fork_error))
427 signal_error (Qfile_error, fork_error);
432 int save_errno = errno;
436 report_file_error ("Doing fork", Qnil);
444 #if defined (NO_SUBPROCESSES)
445 /* If Emacs has been built with asynchronous subprocess support,
446 we don't need to do this, I think because it will then have
447 the facilities for handling SIGCHLD. */
448 wait_without_blocking ();
449 #endif /* NO_SUBPROCESSES */
457 Lisp_Object instream;
458 struct gcpro ngcpro1;
460 /* Enable sending signal if user quits below. */
461 call_process_exited = 0;
463 record_unwind_protect (call_process_cleanup,
464 Fcons (make_int (fd[0]), make_int (pid)));
466 /* FSFmacs calls Fset_buffer() here. We don't have to because
467 we can insert into buffers other than the current one. */
469 XSETBUFFER (buffer, current_buffer);
470 instream = make_filedesc_input_stream (fd[0], 0, -1, LSTR_ALLOW_QUIT);
473 make_decoding_input_stream
474 (XLSTREAM (instream),
475 Fget_coding_system (Vcoding_system_for_read));
476 Lstream_set_character_mode (XLSTREAM (instream));
482 /* Repeatedly read until we've filled as much as possible
483 of the buffer size we have. But don't read
484 less than 1024--save that for the next bufferfull. */
487 while (nread < bufsize - 1024)
490 = Lstream_read (XLSTREAM (instream), bufptr + nread,
504 /* Now NREAD is the total amount of data in the buffer. */
510 /* Until we pull out of MULE things like
511 make_decoding_input_stream(), we do the following which is
512 less elegant. --marcpa */
516 if (NILP (Vbinary_process_output)) {
517 nread = crlf_to_lf(nread, bufptr, &lf_count);
526 buffer_insert_raw_string (XBUFFER (buffer), (Bufbyte *) bufptr,
529 /* Make the buffer bigger as we continue to read more data,
531 if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
534 bufptr = (char *) alloca (bufsize);
537 if (!NILP (display) && INTERACTIVE)
544 Lstream_close (XLSTREAM (instream));
548 /* Wait for it to terminate, unless it already has. */
550 wait_for_termination (pHandle);
552 wait_for_termination (pid);
555 /* Don't kill any children that the subprocess may have left behind
557 call_process_exited = 1;
558 unbind_to (speccount, Qnil);
560 if (synch_process_death)
561 return build_string (synch_process_death);
562 return make_int (synch_process_retcode);
568 /* Move the file descriptor FD so that its number is not less than MIN. *
569 The original file descriptor remains open. */
571 relocate_fd (int fd, int min)
577 int newfd = dup (fd);
580 stderr_out ("Error while setting up child: %s\n",
584 return relocate_fd (newfd, min);
588 /* This is the last thing run in a newly forked inferior
589 either synchronous or asynchronous.
590 Copy descriptors IN, OUT and ERR
591 as descriptors STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO.
592 Initialize inferior's priority, pgrp, connected dir and environment.
593 then exec another program based on new_argv.
595 This function may change environ for the superior process.
596 Therefore, the superior process must save and restore the value
597 of environ around the fork and the call to this function.
599 ENV is the environment for the subprocess.
601 XEmacs: We've removed the SET_PGRP argument because it's already
602 done by the callers of child_setup.
604 CURRENT_DIR is an elisp string giving the path of the current
605 directory the subprocess should have. Since we can't really signal
606 a decent error from within the child, this should be verified as an
607 executable directory by the parent. */
614 child_setup (int in, int out, int err, char **new_argv,
615 const char *current_dir)
622 #endif /* WIN32_NATIVE */
624 #ifdef SET_EMACS_PRIORITY
625 if (emacs_priority != 0)
626 nice (- emacs_priority);
629 /* Under Windows, we are not in a child process at all, so we should
630 not close handles inherited from the parent -- we are the parent
631 and doing so will screw up all manner of things! Similarly, most
632 of the rest of the cleanup done in this function is not done
635 #### This entire child_setup() function is an utter and complete
636 piece of shit. I would rewrite it, at the very least splitting
637 out the Windows and non-Windows stuff into two completely
638 different functions; but instead I'm trying to make it go away
639 entirely, using the Lisp definition in process.el. What's left
640 is to fix up the routines in event-msw.c (and in event-Xt.c and
641 event-tty.c) to allow for stream devices to be handled correctly.
642 There isn't much to do, in fact, and I'll fix it shortly. That
643 way, the Lisp definition can be used non-interactively too. */
644 #if !defined (NO_SUBPROCESSES) && !defined (WIN32_NATIVE)
645 /* Close Emacs's descriptors that this process should not have. */
646 close_process_descs ();
647 #endif /* not NO_SUBPROCESSES */
652 /* Note that use of alloca is always safe here. It's obvious for systems
653 that do not have true vfork or that have true (stack) alloca.
654 If using vfork and C_ALLOCA it is safe because that changes
655 the superior's static variables as if the superior had done alloca
656 and will be cleaned up in the usual way. */
660 i = strlen (current_dir);
661 pwd = alloca_array (char, i + 6);
662 memcpy (pwd, "PWD=", 4);
663 memcpy (pwd + 4, current_dir, i);
665 if (!IS_DIRECTORY_SEP (pwd[i - 1]))
666 pwd[i++] = DIRECTORY_SEP;
669 /* We can't signal an Elisp error here; we're in a vfork. Since
670 the callers check the current directory before forking, this
671 should only return an error if the directory's permissions
672 are changed between the check and this chdir, but we should
674 if (chdir (pwd + 4) < 0)
676 /* Don't report the chdir error, or ange-ftp.el doesn't work. */
677 /* (FSFmacs does _exit (errno) here.) */
682 /* Strip trailing "/". Cretinous *[]&@$#^%@#$% Un*x */
683 /* leave "//" (from FSF) */
684 while (i > 6 && IS_DIRECTORY_SEP (pwd[i - 1]))
689 /* Set `env' to a vector of the strings in Vprocess_environment. */
690 /* + 2 to include PWD and terminating 0. */
691 env = alloca_array (char *, XINT (Flength (Vprocess_environment)) + 2);
693 REGISTER Lisp_Object tail;
694 char **new_env = env;
696 /* If we have a PWD envvar and we know the real current directory,
697 pass one down, but with corrected value. */
698 if (pwd && getenv ("PWD"))
701 /* Copy the Vprocess_environment strings into new_env. */
702 for (tail = Vprocess_environment;
703 CONSP (tail) && STRINGP (XCAR (tail));
707 char *envvar_external;
709 TO_EXTERNAL_FORMAT (LISP_STRING, XCAR (tail),
710 C_STRING_ALLOCA, envvar_external,
713 /* See if envvar_external duplicates any string already in the env.
714 If so, don't put it in.
715 When an env var has multiple definitions,
716 we keep the definition that comes first in process-environment. */
717 for (; ep != new_env; ep++)
719 char *p = *ep, *q = envvar_external;
723 /* The string is malformed; might as well drop it. */
732 if (pwd && !strncmp ("PWD=", envvar_external, 4))
738 *new_env++ = envvar_external;
746 prepare_standard_handles (in, out, err, handles);
747 set_process_dir (current_dir);
748 #else /* not WIN32_NATIVE */
749 /* Make sure that in, out, and err are not actually already in
750 descriptors zero, one, or two; this could happen if Emacs is
751 started with its standard in, out, or error closed, as might
753 in = relocate_fd (in, 3);
754 out = relocate_fd (out, 3);
755 err = relocate_fd (err, 3);
757 /* Set the standard input/output channels of the new process. */
758 close (STDIN_FILENO);
759 close (STDOUT_FILENO);
760 close (STDERR_FILENO);
762 dup2 (in, STDIN_FILENO);
763 dup2 (out, STDOUT_FILENO);
764 dup2 (err, STDERR_FILENO);
770 /* I can't think of any reason why child processes need any more
771 than the standard 3 file descriptors. It would be cleaner to
772 close just the ones that need to be, but the following brute
773 force approach is certainly effective, and not too slow. */
776 for (fd=3; fd<=64; fd++)
779 #endif /* not WIN32_NATIVE */
782 something missing here;
786 /* Spawn the child. (See ntproc.c:Spawnve). */
787 cpid = spawnve (_P_NOWAIT, new_argv[0], (const char* const*)new_argv,
788 (const char* const*)env);
790 /* An error occurred while trying to spawn the process. */
791 report_file_error ("Spawning child process", Qnil);
792 reset_standard_handles (in, out, err, handles);
794 #else /* not WIN32_NATIVE */
795 /* execvp does not accept an environment arg so the only way
796 to pass this environment is to set environ. Our caller
797 is responsible for restoring the ambient value of environ. */
799 execvp (new_argv[0], new_argv);
801 stdout_out ("Can't exec program %s\n", new_argv[0]);
803 #endif /* not WIN32_NATIVE */
807 getenv_internal (const Bufbyte *var,
814 for (scan = Vprocess_environment; CONSP (scan); scan = XCDR (scan))
816 Lisp_Object entry = XCAR (scan);
819 && XSTRING_LENGTH (entry) > varlen
820 && XSTRING_BYTE (entry, varlen) == '='
822 /* NT environment variables are case insensitive. */
823 && ! memicmp (XSTRING_DATA (entry), var, varlen)
824 #else /* not WIN32_NATIVE */
825 && ! memcmp (XSTRING_DATA (entry), var, varlen)
826 #endif /* not WIN32_NATIVE */
829 *value = XSTRING_DATA (entry) + (varlen + 1);
830 *valuelen = XSTRING_LENGTH (entry) - (varlen + 1);
838 DEFUN ("getenv", Fgetenv, 1, 2, "sEnvironment variable: \np", /*
839 Return the value of environment variable VAR, as a string.
840 VAR is a string, the name of the variable.
841 When invoked interactively, prints the value in the echo area.
847 Lisp_Object v = Qnil;
852 if (getenv_internal (XSTRING_DATA (var), XSTRING_LENGTH (var),
854 v = make_string (value, valuelen);
855 if (!NILP (interactivep))
858 message ("%s not defined in environment", XSTRING_DATA (var));
860 /* #### Should use Fprin1_to_string or Fprin1 to handle string
861 containing quotes correctly. */
862 message ("\"%s\"", value);
867 /* A version of getenv that consults process_environment, easily
870 egetenv (const char *var)
872 /* This cannot GC -- 7-28-00 ben */
876 if (getenv_internal ((const Bufbyte *) var, strlen (var), &value, &valuelen))
877 return (char *) value;
886 /* This function can GC */
889 /* jwz: always initialize Vprocess_environment, so that egetenv()
892 Vprocess_environment = Qnil;
893 for (envp = environ; envp && *envp; envp++)
894 Vprocess_environment =
895 Fcons (build_ext_string (*envp, Qfile_name), Vprocess_environment);
899 /* Initialize shell-file-name from environment variables or best guess. */
901 const char *shell = egetenv ("COMSPEC");
902 if (!shell) shell = "\\WINNT\\system32\\cmd.exe";
903 #else /* not WIN32_NATIVE */
904 const char *shell = egetenv ("SHELL");
905 if (!shell) shell = "/bin/sh";
908 Vshell_file_name = build_string (shell);
914 set_process_environment (void)
916 REGISTER char **envp;
918 Vprocess_environment = Qnil;
922 for (envp = environ; *envp; envp++)
923 Vprocess_environment = Fcons (build_string (*envp),
924 Vprocess_environment);
929 syms_of_callproc (void)
931 DEFSUBR (Fold_call_process_internal);
936 vars_of_callproc (void)
938 /* This function can GC */
940 DEFVAR_LISP ("binary-process-input", &Vbinary_process_input /*
941 *If non-nil then new subprocesses are assumed to take binary input.
943 Vbinary_process_input = Qnil;
945 DEFVAR_LISP ("binary-process-output", &Vbinary_process_output /*
946 *If non-nil then new subprocesses are assumed to produce binary output.
948 Vbinary_process_output = Qnil;
949 #endif /* WIN32_NATIVE */
951 DEFVAR_LISP ("shell-file-name", &Vshell_file_name /*
952 *File name to load inferior shells from.
953 Initialized from the SHELL environment variable.
956 DEFVAR_LISP ("process-environment", &Vprocess_environment /*
957 List of environment variables for subprocesses to inherit.
958 Each element should be a string of the form ENVVARNAME=VALUE.
959 The environment which Emacs inherits is placed in this variable
963 Vlisp_EXEC_SUFFIXES = build_string (EXEC_SUFFIXES);
964 staticpro (&Vlisp_EXEC_SUFFIXES);