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 */
36 #include "file-coding.h"
41 #include "sysfile.h" /* Always include after sysproc.h */
42 #include "syssignal.h" /* Always include before systty.h */
46 #define _P_NOWAIT 1 /* from process.h */
52 /* When we are starting external processes we need to know whether they
53 take binary input (no conversion) or text input (\n is converted to
54 \r\n). Similarly for output: if newlines are written as \r\n then it's
55 text process output, otherwise it's binary. */
56 Lisp_Object Vbinary_process_input;
57 Lisp_Object Vbinary_process_output;
60 Lisp_Object Vshell_file_name;
62 /* The environment to pass to all subprocesses when they are started.
63 This is in the semi-bogus format of ("VAR=VAL" "VAR2=VAL2" ... )
65 Lisp_Object Vprocess_environment;
67 /* True iff we are about to fork off a synchronous process or if we
68 are waiting for it. */
69 volatile int synch_process_alive;
71 /* Nonzero => this is a string explaining death of synchronous subprocess. */
72 CONST char *synch_process_death;
74 /* If synch_process_death is zero,
75 this is exit code of synchronous subprocess. */
76 int synch_process_retcode;
78 /* Clean up when exiting Fcall_process_internal.
79 On MSDOS, delete the temporary file on any kind of termination.
80 On Unix, kill the process and any children on termination by signal. */
82 /* Nonzero if this is termination due to exit. */
83 static int call_process_exited;
87 call_process_kill (Lisp_Object fdpid)
89 Lisp_Object fd = Fcar (fdpid);
90 Lisp_Object pid = Fcdr (fdpid);
96 EMACS_KILLPG (XINT (pid), SIGKILL);
98 synch_process_alive = 0;
103 call_process_cleanup (Lisp_Object fdpid)
105 int fd = XINT (Fcar (fdpid));
106 int pid = XINT (Fcdr (fdpid));
108 if (!call_process_exited &&
109 EMACS_KILLPG (pid, SIGINT) == 0)
111 int speccount = specpdl_depth ();
113 record_unwind_protect (call_process_kill, fdpid);
114 /* #### "c-G" -- need non-consing Single-key-description */
115 message ("Waiting for process to die...(type C-g again to kill it instantly)");
117 wait_for_termination (pid);
119 /* "Discard" the unwind protect. */
122 unbind_to (speccount, Qnil);
124 message ("Waiting for process to die... done");
126 synch_process_alive = 0;
131 static Lisp_Object fork_error;
134 report_fork_error (char *string, Lisp_Object data)
136 Lisp_Object errstring = lisp_strerror (errno);
138 fork_error = Fcons (build_string (string), Fcons (errstring, data));
140 /* terminate this branch of the fork, without closing stdin/out/etc. */
145 DEFUN ("call-process-internal", Fcall_process_internal, 1, MANY, 0, /*
146 Call PROGRAM synchronously in separate process, with coding-system specified.
148 (PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS).
149 The program's input comes from file INFILE (nil means `/dev/null').
150 Insert output in BUFFER before point; t means current buffer;
151 nil for BUFFER means discard it; 0 means discard and don't wait.
152 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
153 REAL-BUFFER says what to do with standard output, as above,
154 while STDERR-FILE says what to do with standard error in the child.
155 STDERR-FILE may be nil (discard standard error output),
156 t (mix it with ordinary output), or a file name string.
158 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
159 Remaining arguments are strings passed as command arguments to PROGRAM.
161 If BUFFER is 0, `call-process' returns immediately with value nil.
162 Otherwise it waits for PROGRAM to terminate and returns a numeric exit status
163 or a signal description string.
164 If you quit, the process is killed with SIGINT, or SIGKILL if you
167 (int nargs, Lisp_Object *args))
169 /* This function can GC */
170 Lisp_Object infile, buffer, current_dir, display, path;
177 int speccount = specpdl_depth ();
178 struct gcpro gcpro1, gcpro2;
179 char **new_argv = alloca_array (char *, max (2, nargs - 2));
181 /* File to use for stderr in the child.
182 t means use same as standard output. */
183 Lisp_Object error_file;
185 CHECK_STRING (args[0]);
189 #if defined (NO_SUBPROCESSES)
190 /* Without asynchronous processes we cannot have BUFFER == 0. */
191 if (nargs >= 3 && !INTP (args[2]))
192 error ("Operating system cannot handle asynchronous subprocesses");
193 #endif /* NO_SUBPROCESSES */
195 /* Do this before building new_argv because GC in Lisp code
196 * called by various filename-hacking routines might relocate strings */
197 locate_file (Vexec_path, args[0], EXEC_SUFFIXES, &path, X_OK);
199 /* Make sure that the child will be able to chdir to the current
200 buffer's current directory, or its unhandled equivalent. We
201 can't just have the child check for an error when it does the
202 chdir, since it's in a vfork. */
204 struct gcpro ngcpro1, ngcpro2;
205 /* Do this test before building new_argv because GC in Lisp code
206 * called by various filename-hacking routines might relocate strings */
207 /* Make sure that the child will be able to chdir to the current
208 buffer's current directory. We can't just have the child check
209 for an error when it does the chdir, since it's in a vfork. */
211 NGCPRO2 (current_dir, path); /* Caller gcprotects args[] */
212 current_dir = current_buffer->directory;
213 current_dir = Funhandled_file_name_directory (current_dir);
214 current_dir = expand_and_dir_to_file (current_dir, Qnil);
216 /* This is in FSF, but it breaks everything in the presence of
217 ange-ftp-visited files, so away with it. */
218 if (NILP (Ffile_accessible_directory_p (current_dir)))
219 report_file_error ("Setting current directory",
220 Fcons (current_buffer->directory, Qnil));
225 GCPRO1 (current_dir);
227 if (nargs >= 2 && ! NILP (args[1]))
229 struct gcpro ngcpro1;
230 NGCPRO1 (current_buffer->directory);
231 infile = Fexpand_file_name (args[1], current_buffer->directory);
233 CHECK_STRING (infile);
236 infile = build_string (NULL_DEVICE);
240 GCPRO2 (infile, current_dir); /* Fexpand_file_name might trash it */
246 /* If BUFFER is a list, its meaning is
247 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
250 if (CONSP (XCDR (buffer)))
252 Lisp_Object file_for_stderr = XCAR (XCDR (buffer));
254 if (NILP (file_for_stderr) || EQ (Qt, file_for_stderr))
255 error_file = file_for_stderr;
257 error_file = Fexpand_file_name (file_for_stderr, Qnil);
260 buffer = XCAR (buffer);
263 if (!(EQ (buffer, Qnil)
267 Lisp_Object spec_buffer = buffer;
268 buffer = Fget_buffer (buffer);
269 /* Mention the buffer name for a better error message. */
271 CHECK_BUFFER (spec_buffer);
272 CHECK_BUFFER (buffer);
280 display = ((nargs >= 4) ? args[3] : Qnil);
282 /* From here we assume we won't GC (unless an error is signaled). */
285 for (i = 4; i < nargs; i++)
287 CHECK_STRING (args[i]);
288 new_argv[i - 3] = (char *) XSTRING_DATA (args[i]);
290 new_argv[nargs - 3] = 0;
294 report_file_error ("Searching for program", Fcons (args[0], Qnil));
295 new_argv[0] = (char *) XSTRING_DATA (path);
297 filefd = open ((char *) XSTRING_DATA (infile), O_RDONLY | OPEN_BINARY, 0);
299 report_file_error ("Opening process input file", Fcons (infile, Qnil));
303 fd[1] = open (NULL_DEVICE, O_WRONLY | OPEN_BINARY, 0);
310 /* Replaced by close_process_descs */
311 set_exclusive_use (fd[0]);
316 /* child_setup must clobber environ in systems with true vfork.
317 Protect it from permanent change. */
318 REGISTER char **save_environ = environ;
319 REGISTER int fd1 = fd[1];
324 /* when performance monitoring is on, turn it off before the vfork(),
325 as the child has no handler for the signal -- when back in the
326 parent process, turn it back on if it was really on when you "turned
328 int logging_on = cadillac_stop_logging ();
329 #endif /* EMACS_BTL */
333 /* Record that we're about to create a synchronous process. */
334 synch_process_alive = 1;
336 /* These vars record information from process termination.
337 Clear them now before process can possibly terminate,
338 to avoid timing error if process terminates soon. */
339 synch_process_death = 0;
340 synch_process_retcode = 0;
342 if (NILP (error_file))
343 fd_error = open (NULL_DEVICE, O_WRONLY | OPEN_BINARY);
344 else if (STRINGP (error_file))
346 fd_error = open ((CONST char *) XSTRING_DATA (error_file),
348 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
350 #else /* not DOS_NT */
351 O_WRONLY | O_TRUNC | O_CREAT | OPEN_BINARY,
353 #endif /* not DOS_NT */
363 report_file_error ("Cannot open", Fcons(error_file, Qnil));
368 pid = child_setup (filefd, fd1, fd_error, new_argv,
369 (char *) XSTRING_DATA (current_dir));
370 #else /* not WINDOWSNT */
377 /* This is necessary because some shells may attempt to
378 access the current controlling terminal and will hang
379 if they are run in the background, as will be the case
380 when XEmacs is started in the background. Martin
381 Buchholz observed this problem running a subprocess
382 that used zsh to call gzip to uncompress an info
384 disconnect_controlling_terminal ();
385 child_setup (filefd, fd1, fd_error, new_argv,
386 (char *) XSTRING_DATA (current_dir));
390 cadillac_start_logging ();
395 #endif /* not WINDOWSNT */
397 environ = save_environ;
399 /* Close most of our fd's, but not fd[0]
400 since we will use that to read input from. */
406 if (!NILP (fork_error))
407 signal_error (Qfile_error, fork_error);
413 report_file_error ("Doing fork", Qnil);
420 #if defined (NO_SUBPROCESSES)
421 /* If Emacs has been built with asynchronous subprocess support,
422 we don't need to do this, I think because it will then have
423 the facilities for handling SIGCHLD. */
424 wait_without_blocking ();
425 #endif /* NO_SUBPROCESSES */
433 Lisp_Object instream;
434 struct gcpro ngcpro1;
436 /* Enable sending signal if user quits below. */
437 call_process_exited = 0;
439 record_unwind_protect (call_process_cleanup,
440 Fcons (make_int (fd[0]), make_int (pid)));
442 /* FSFmacs calls Fset_buffer() here. We don't have to because
443 we can insert into buffers other than the current one. */
445 XSETBUFFER (buffer, current_buffer);
446 instream = make_filedesc_input_stream (fd[0], 0, -1, LSTR_ALLOW_QUIT);
449 make_decoding_input_stream
450 (XLSTREAM (instream),
451 Fget_coding_system (Vcoding_system_for_read));
452 Lstream_set_character_mode (XLSTREAM (instream));
458 /* Repeatedly read until we've filled as much as possible
459 of the buffer size we have. But don't read
460 less than 1024--save that for the next bufferfull. */
463 while (nread < bufsize - 1024)
466 = Lstream_read (XLSTREAM (instream), bufptr + nread,
480 /* Now NREAD is the total amount of data in the buffer. */
485 /* Until we pull out of MULE things like
486 make_decoding_input_stream(), we do the following which is
487 less elegant. --marcpa */
490 if (NILP (Vbinary_process_output)) {
491 nread = crlf_to_lf(nread, bufptr, &lf_count);
499 buffer_insert_raw_string (XBUFFER (buffer), (Bufbyte *) bufptr,
502 /* Make the buffer bigger as we continue to read more data,
504 if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
507 bufptr = (char *) alloca (bufsize);
510 if (!NILP (display) && INTERACTIVE)
517 Lstream_close (XLSTREAM (instream));
521 /* Wait for it to terminate, unless it already has. */
522 wait_for_termination (pid);
524 /* Don't kill any children that the subprocess may have left behind
526 call_process_exited = 1;
527 unbind_to (speccount, Qnil);
529 if (synch_process_death)
530 return build_string (synch_process_death);
531 return make_int (synch_process_retcode);
537 /* This is the last thing run in a newly forked inferior
538 either synchronous or asynchronous.
539 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
540 Initialize inferior's priority, pgrp, connected dir and environment.
541 then exec another program based on new_argv.
543 This function may change environ for the superior process.
544 Therefore, the superior process must save and restore the value
545 of environ around the fork and the call to this function.
547 ENV is the environment for the subprocess.
549 XEmacs: We've removed the SET_PGRP argument because it's already
550 done by the callers of child_setup.
552 CURRENT_DIR is an elisp string giving the path of the current
553 directory the subprocess should have. Since we can't really signal
554 a decent error from within the child, this should be verified as an
555 executable directory by the parent. */
557 static int relocate_fd (int fd, int min);
564 child_setup (int in, int out, int err, char **new_argv,
565 CONST char *current_dir)
572 #endif /* WINDOWSNT */
574 #ifdef SET_EMACS_PRIORITY
575 if (emacs_priority != 0)
576 nice (- emacs_priority);
579 #if !defined (NO_SUBPROCESSES) && !defined (WINDOWSNT)
580 /* Close Emacs's descriptors that this process should not have. */
581 close_process_descs ();
582 #endif /* not NO_SUBPROCESSES */
585 /* Note that use of alloca is always safe here. It's obvious for systems
586 that do not have true vfork or that have true (stack) alloca.
587 If using vfork and C_ALLOCA it is safe because that changes
588 the superior's static variables as if the superior had done alloca
589 and will be cleaned up in the usual way. */
593 i = strlen (current_dir);
594 pwd = alloca_array (char, i + 6);
595 memcpy (pwd, "PWD=", 4);
596 memcpy (pwd + 4, current_dir, i);
598 if (!IS_DIRECTORY_SEP (pwd[i - 1]))
599 pwd[i++] = DIRECTORY_SEP;
602 /* We can't signal an Elisp error here; we're in a vfork. Since
603 the callers check the current directory before forking, this
604 should only return an error if the directory's permissions
605 are changed between the check and this chdir, but we should
607 if (chdir (pwd + 4) < 0)
609 /* Don't report the chdir error, or ange-ftp.el doesn't work. */
610 /* (FSFmacs does _exit (errno) here.) */
615 /* Strip trailing "/". Cretinous *[]&@$#^%@#$% Un*x */
616 /* leave "//" (from FSF) */
617 while (i > 6 && IS_DIRECTORY_SEP (pwd[i - 1]))
622 /* Set `env' to a vector of the strings in Vprocess_environment. */
624 REGISTER Lisp_Object tem;
625 REGISTER char **new_env;
626 REGISTER int new_length = 0;
628 for (tem = Vprocess_environment;
630 && STRINGP (XCAR (tem)));
634 /* new_length + 2 to include PWD and terminating 0. */
635 env = new_env = alloca_array (char *, new_length + 2);
637 /* If we have a PWD envvar and we know the real current directory,
638 pass one down, but with corrected value. */
639 if (pwd && getenv ("PWD"))
642 /* Copy the Vprocess_environment strings into new_env. */
643 for (tem = Vprocess_environment;
645 && STRINGP (XCAR (tem)));
649 char *string = (char *) XSTRING_DATA (XCAR (tem));
650 /* See if this string duplicates any string already in the env.
651 If so, don't put it in.
652 When an env var has multiple definitions,
653 we keep the definition that comes first in process-environment. */
654 for (; ep != new_env; ep++)
656 char *p = *ep, *q = string;
660 /* The string is malformed; might as well drop it. */
669 if (pwd && !strncmp ("PWD=", string, 4))
681 prepare_standard_handles (in, out, err, handles);
682 set_process_dir (current_dir);
683 #else /* not WINDOWSNT */
684 /* Make sure that in, out, and err are not actually already in
685 descriptors zero, one, or two; this could happen if Emacs is
686 started with its standard in, out, or error closed, as might
689 int oin = in, oout = out;
691 /* We have to avoid relocating the same descriptor twice! */
693 in = relocate_fd (in, 3);
695 if (out == oin) out = in;
696 else out = relocate_fd (out, 3);
698 if (err == oin) err = in;
699 else if (err == oout) err = out;
700 else err = relocate_fd (err, 3);
715 /* I can't think of any reason why child processes need any more
716 than the standard 3 file descriptors. It would be cleaner to
717 close just the ones that need to be, but the following brute
718 force approach is certainly effective, and not too slow. */
721 for (fd=3; fd<=64; fd++)
726 #endif /* not WINDOWSNT */
729 something missing here;
733 /* Spawn the child. (See ntproc.c:Spawnve). */
734 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
736 /* An error occurred while trying to spawn the process. */
737 report_file_error ("Spawning child process", Qnil);
738 reset_standard_handles (in, out, err, handles);
740 #else /* not WINDOWSNT */
741 /* execvp does not accept an environment arg so the only way
742 to pass this environment is to set environ. Our caller
743 is responsible for restoring the ambient value of environ. */
745 execvp (new_argv[0], new_argv);
747 stdout_out ("Cant't exec program %s\n", new_argv[0]);
749 #endif /* not WINDOWSNT */
752 /* Move the file descriptor FD so that its number is not less than MIN.
753 If the file descriptor is moved at all, the original is freed. */
755 relocate_fd (int fd, int min)
764 stderr_out ("Error while setting up child: %s\n",
768 /* Note that we hold the original FD open while we recurse,
769 to guarantee we'll get a new FD if we need it. */
770 new = relocate_fd (new, min);
777 getenv_internal (CONST Bufbyte *var,
784 for (scan = Vprocess_environment; CONSP (scan); scan = XCDR (scan))
786 Lisp_Object entry = XCAR (scan);
789 && XSTRING_LENGTH (entry) > varlen
790 && XSTRING_BYTE (entry, varlen) == '='
792 /* NT environment variables are case insensitive. */
793 && ! memicmp (XSTRING_DATA (entry), var, varlen)
794 #else /* not WINDOWSNT */
795 && ! memcmp (XSTRING_DATA (entry), var, varlen)
796 #endif /* not WINDOWSNT */
799 *value = XSTRING_DATA (entry) + (varlen + 1);
800 *valuelen = XSTRING_LENGTH (entry) - (varlen + 1);
808 DEFUN ("getenv", Fgetenv, 1, 2, "sEnvironment variable: \np", /*
809 Return the value of environment variable VAR, as a string.
810 VAR is a string, the name of the variable.
811 When invoked interactively, prints the value in the echo area.
817 Lisp_Object v = Qnil;
822 if (getenv_internal (XSTRING_DATA (var), XSTRING_LENGTH (var),
824 v = make_string (value, valuelen);
825 if (!NILP (interactivep))
828 message ("%s not defined in environment", XSTRING_DATA (var));
830 /* #### Should use Fprin1_to_string or Fprin1 to handle string
831 containing quotes correctly. */
832 message ("\"%s\"", value);
837 /* A version of getenv that consults process_environment, easily
840 egetenv (CONST char *var)
845 if (getenv_internal ((CONST Bufbyte *) var, strlen (var), &value, &valuelen))
846 return (char *) value;
855 /* This function can GC */
858 Vprocess_environment = Qnil;
859 /* jwz: always initialize Vprocess_environment, so that egetenv() works
863 for (envp = environ; envp && *envp; envp++)
865 Vprocess_environment = Fcons (build_ext_string (*envp, FORMAT_OS),
866 Vprocess_environment);
871 /* Sync with FSF Emacs 19.34.6 note: this is not in 19.34.6. --marcpa */
873 ** If NT then we look at COMSPEC for the shell program.
875 sh = egetenv ("COMSPEC");
877 ** If COMSPEC has been set, then convert the
878 ** DOS formatted name into a UNIX format. Then
879 ** create a LISP object.
882 Vshell_file_name = build_string (sh);
884 ** Odd, no COMSPEC, so let's default to our
885 ** best guess for NT.
888 Vshell_file_name = build_string ("\\WINNT\\system32\\cmd.exe");
890 #else /* not WINDOWSNT */
892 sh = (char *) egetenv ("SHELL");
893 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
900 set_process_environment (void)
902 REGISTER char **envp;
904 Vprocess_environment = Qnil;
908 for (envp = environ; *envp; envp++)
909 Vprocess_environment = Fcons (build_string (*envp),
910 Vprocess_environment);
915 syms_of_callproc (void)
917 DEFSUBR (Fcall_process_internal);
922 vars_of_callproc (void)
924 /* This function can GC */
926 DEFVAR_LISP ("binary-process-input", &Vbinary_process_input /*
927 *If non-nil then new subprocesses are assumed to take binary input.
929 Vbinary_process_input = Qnil;
931 DEFVAR_LISP ("binary-process-output", &Vbinary_process_output /*
932 *If non-nil then new subprocesses are assumed to produce binary output.
934 Vbinary_process_output = Qnil;
937 DEFVAR_LISP ("shell-file-name", &Vshell_file_name /*
938 *File name to load inferior shells from.
939 Initialized from the SHELL environment variable.
942 DEFVAR_LISP ("process-environment", &Vprocess_environment /*
943 List of environment variables for subprocesses to inherit.
944 Each element should be a string of the form ENVVARNAME=VALUE.
945 The environment which Emacs inherits is placed in this variable