(xcar, xcdr): Print with /x.
[emacs.git] / src / callproc.c
blob5812821ee1150b1e8b46a3b54d19ba4c65cdfec1
1 /* Synchronous subprocess invocation for GNU Emacs.
2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; 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. */
22 #include <signal.h>
23 #include <errno.h>
25 #include <config.h>
26 #include <stdio.h>
28 extern int errno;
29 extern char *strerror ();
31 /* Define SIGCHLD as an alias for SIGCLD. */
33 #if !defined (SIGCHLD) && defined (SIGCLD)
34 #define SIGCHLD SIGCLD
35 #endif /* SIGCLD */
37 #include <sys/types.h>
39 #include <sys/file.h>
40 #ifdef USG5
41 #define INCLUDED_FCNTL
42 #include <fcntl.h>
43 #endif
45 #ifdef WINDOWSNT
46 #define NOMINMAX
47 #include <windows.h>
48 #include <stdlib.h> /* for proper declaration of environ */
49 #include <fcntl.h>
50 #include "w32.h"
51 #define _P_NOWAIT 1 /* from process.h */
52 #endif
54 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
55 #include "msdos.h"
56 #define INCLUDED_FCNTL
57 #include <fcntl.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <errno.h>
61 #endif /* MSDOS */
63 #ifndef O_RDONLY
64 #define O_RDONLY 0
65 #endif
67 #ifndef O_WRONLY
68 #define O_WRONLY 1
69 #endif
71 #include "lisp.h"
72 #include "commands.h"
73 #include "buffer.h"
74 #include "charset.h"
75 #include "coding.h"
76 #include <paths.h>
77 #include "process.h"
78 #include "syssignal.h"
79 #include "systty.h"
81 #ifdef VMS
82 extern noshare char **environ;
83 #else
84 extern char **environ;
85 #endif
87 #define max(a, b) ((a) > (b) ? (a) : (b))
89 #ifdef DOS_NT
90 /* When we are starting external processes we need to know whether they
91 take binary input (no conversion) or text input (\n is converted to
92 \r\n). Similar for output: if newlines are written as \r\n then it's
93 text process output, otherwise it's binary. */
94 Lisp_Object Vbinary_process_input;
95 Lisp_Object Vbinary_process_output;
96 #endif /* DOS_NT */
98 Lisp_Object Vexec_path, Vexec_directory, Vdata_directory, Vdoc_directory;
99 Lisp_Object Vconfigure_info_directory;
100 Lisp_Object Vtemp_file_name_pattern;
102 Lisp_Object Vshell_file_name;
104 Lisp_Object Vprocess_environment;
106 #ifdef DOS_NT
107 Lisp_Object Qbuffer_file_type;
108 #endif /* DOS_NT */
110 /* True iff we are about to fork off a synchronous process or if we
111 are waiting for it. */
112 int synch_process_alive;
114 /* Nonzero => this is a string explaining death of synchronous subprocess. */
115 char *synch_process_death;
117 /* If synch_process_death is zero,
118 this is exit code of synchronous subprocess. */
119 int synch_process_retcode;
121 extern Lisp_Object Vdoc_file_name;
123 /* Clean up when exiting Fcall_process.
124 On MSDOS, delete the temporary file on any kind of termination.
125 On Unix, kill the process and any children on termination by signal. */
127 /* Nonzero if this is termination due to exit. */
128 static int call_process_exited;
130 #ifndef VMS /* VMS version is in vmsproc.c. */
132 static Lisp_Object
133 call_process_kill (fdpid)
134 Lisp_Object fdpid;
136 close (XFASTINT (Fcar (fdpid)));
137 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
138 synch_process_alive = 0;
139 return Qnil;
142 Lisp_Object
143 call_process_cleanup (fdpid)
144 Lisp_Object fdpid;
146 #ifdef MSDOS
147 /* for MSDOS fdpid is really (fd . tempfile) */
148 register Lisp_Object file;
149 file = Fcdr (fdpid);
150 close (XFASTINT (Fcar (fdpid)));
151 if (strcmp (XSTRING (file)-> data, NULL_DEVICE) != 0)
152 unlink (XSTRING (file)->data);
153 #else /* not MSDOS */
154 register int pid = XFASTINT (Fcdr (fdpid));
157 if (call_process_exited)
159 close (XFASTINT (Fcar (fdpid)));
160 return Qnil;
163 if (EMACS_KILLPG (pid, SIGINT) == 0)
165 int count = specpdl_ptr - specpdl;
166 record_unwind_protect (call_process_kill, fdpid);
167 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
168 immediate_quit = 1;
169 QUIT;
170 wait_for_termination (pid);
171 immediate_quit = 0;
172 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
173 message1 ("Waiting for process to die...done");
175 synch_process_alive = 0;
176 close (XFASTINT (Fcar (fdpid)));
177 #endif /* not MSDOS */
178 return Qnil;
181 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
182 "Call PROGRAM synchronously in separate process.\n\
183 The program's input comes from file INFILE (nil means `/dev/null').\n\
184 Insert output in BUFFER before point; t means current buffer;\n\
185 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
186 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
187 REAL-BUFFER says what to do with standard output, as above,\n\
188 while STDERR-FILE says what to do with standard error in the child.\n\
189 STDERR-FILE may be nil (discard standard error output),\n\
190 t (mix it with ordinary output), or a file name string.\n\
192 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
193 Remaining arguments are strings passed as command arguments to PROGRAM.\n\
195 If BUFFER is 0, `call-process' returns immediately with value nil.\n\
196 Otherwise it waits for PROGRAM to terminate\n\
197 and returns a numeric exit status or a signal description string.\n\
198 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
199 (nargs, args)
200 int nargs;
201 register Lisp_Object *args;
203 Lisp_Object infile, buffer, current_dir, display, path;
204 int fd[2];
205 int filefd;
206 register int pid;
207 char buf[16384];
208 char *bufptr = buf;
209 int bufsize = 16384;
210 int count = specpdl_ptr - specpdl;
211 register unsigned char **new_argv
212 = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
213 struct buffer *old = current_buffer;
214 /* File to use for stderr in the child.
215 t means use same as standard output. */
216 Lisp_Object error_file;
217 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
218 char *outf, *tempfile;
219 int outfilefd;
220 #endif
221 #if 0
222 int mask;
223 #endif
224 struct coding_system process_coding; /* coding-system of process output */
225 struct coding_system argument_coding; /* coding-system of arguments */
227 CHECK_STRING (args[0], 0);
229 error_file = Qt;
231 #ifndef subprocesses
232 /* Without asynchronous processes we cannot have BUFFER == 0. */
233 if (nargs >= 3 && INTEGERP (args[2]))
234 error ("Operating system cannot handle asynchronous subprocesses");
235 #endif /* subprocesses */
237 /* Decide the coding-system for giving arguments and reading process
238 output. */
240 Lisp_Object val, *args2;
241 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
242 Lisp_Object coding_systems = Qt;
243 int i;
245 /* If arguments are supplied, we may have to encode them. */
246 if (nargs >= 5)
248 if (!NILP (Vcoding_system_for_write))
249 val = Vcoding_system_for_write;
250 else if (NILP (current_buffer->enable_multibyte_characters))
251 val = Qnil;
252 else
254 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
255 args2[0] = Qcall_process;
256 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
257 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
258 if (CONSP (coding_systems))
259 val = XCONS (coding_systems)->cdr;
260 else if (CONSP (Vdefault_process_coding_system))
261 val = XCONS (Vdefault_process_coding_system)->cdr;
262 else
263 val = Qnil;
265 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
268 /* If BUFFER is nil, we must read process output once and then
269 discard it, so setup coding system but with nil. If BUFFER is
270 an integer, we can discard it without reading. */
271 if (nargs < 3 || NILP (args[2]))
272 setup_coding_system (Qnil, &process_coding);
273 else if (!INTEGERP (args[2]))
275 val = Qnil;
276 if (!NILP (Vcoding_system_for_read))
277 val = Vcoding_system_for_read;
278 else if (NILP (current_buffer->enable_multibyte_characters))
279 val = Qemacs_mule;
280 else
282 if (!EQ (coding_systems, Qt))
284 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
285 args2[0] = Qcall_process;
286 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
287 coding_systems
288 = Ffind_operation_coding_system (nargs + 1, args2);
290 if (CONSP (coding_systems))
291 val = XCONS (coding_systems)->car;
292 else if (CONSP (Vdefault_process_coding_system))
293 val = XCONS (Vdefault_process_coding_system)->car;
294 else
295 val = Qnil;
297 setup_coding_system (Fcheck_coding_system (val), &process_coding);
298 #ifdef MSDOS
299 /* On MSDOS, if the user did not ask for binary,
300 treat it as "text" which means doing CRLF conversion. */
301 /* FIXME: this probably should be moved into the guts of
302 `Ffind_operation_coding_system' for the case of `call-process'. */
303 if (NILP (Vbinary_process_output))
305 process_coding.eol_type = CODING_EOL_CRLF;
306 if (process_coding.type == coding_type_no_conversion)
307 /* FIXME: should we set type to undecided? */
308 process_coding.type = coding_type_emacs_mule;
310 #endif
314 if (nargs >= 2 && ! NILP (args[1]))
316 infile = Fexpand_file_name (args[1], current_buffer->directory);
317 CHECK_STRING (infile, 1);
319 else
320 infile = build_string (NULL_DEVICE);
322 if (nargs >= 3)
324 buffer = args[2];
326 /* If BUFFER is a list, its meaning is
327 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
328 if (CONSP (buffer))
330 if (CONSP (XCONS (buffer)->cdr))
332 Lisp_Object stderr_file;
333 stderr_file = XCONS (XCONS (buffer)->cdr)->car;
335 if (NILP (stderr_file) || EQ (Qt, stderr_file))
336 error_file = stderr_file;
337 else
338 error_file = Fexpand_file_name (stderr_file, Qnil);
341 buffer = XCONS (buffer)->car;
344 if (!(EQ (buffer, Qnil)
345 || EQ (buffer, Qt)
346 || XFASTINT (buffer) == 0))
348 Lisp_Object spec_buffer;
349 spec_buffer = buffer;
350 buffer = Fget_buffer (buffer);
351 /* Mention the buffer name for a better error message. */
352 if (NILP (buffer))
353 CHECK_BUFFER (spec_buffer, 2);
354 CHECK_BUFFER (buffer, 2);
357 else
358 buffer = Qnil;
360 /* Make sure that the child will be able to chdir to the current
361 buffer's current directory, or its unhandled equivalent. We
362 can't just have the child check for an error when it does the
363 chdir, since it's in a vfork.
365 We have to GCPRO around this because Fexpand_file_name,
366 Funhandled_file_name_directory, and Ffile_accessible_directory_p
367 might call a file name handling function. The argument list is
368 protected by the caller, so all we really have to worry about is
369 buffer. */
371 struct gcpro gcpro1, gcpro2, gcpro3;
373 current_dir = current_buffer->directory;
375 GCPRO3 (infile, buffer, current_dir);
377 current_dir
378 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
379 Qnil);
380 if (NILP (Ffile_accessible_directory_p (current_dir)))
381 report_file_error ("Setting current directory",
382 Fcons (current_buffer->directory, Qnil));
384 UNGCPRO;
387 display = nargs >= 4 ? args[3] : Qnil;
389 filefd = open (XSTRING (infile)->data, O_RDONLY, 0);
390 if (filefd < 0)
392 report_file_error ("Opening process input file", Fcons (infile, Qnil));
394 /* Search for program; barf if not found. */
396 struct gcpro gcpro1;
398 GCPRO1 (current_dir);
399 openp (Vexec_path, args[0], EXEC_SUFFIXES, &path, 1);
400 UNGCPRO;
402 if (NILP (path))
404 close (filefd);
405 report_file_error ("Searching for program", Fcons (args[0], Qnil));
407 new_argv[0] = XSTRING (path)->data;
409 register int i;
410 for (i = 4; i < nargs; i++)
412 CHECK_STRING (args[i], i);
413 if (argument_coding.type == coding_type_no_conversion)
414 new_argv[i - 3] = XSTRING (args[i])->data;
415 else
417 /* We must encode the arguments. */
418 int size = encoding_buffer_size (&argument_coding,
419 XSTRING (args[i])->size);
420 int produced, dummy;
421 unsigned char *dummy1 = (unsigned char *) alloca (size);
423 /* The Irix 4.0 compiler barfs if we eliminate dummy. */
424 new_argv[i - 3] = dummy1;
425 produced = encode_coding (&argument_coding,
426 XSTRING (args[i])->data, new_argv[i - 3],
427 XSTRING (args[i])->size, size, &dummy);
428 new_argv[i - 3][produced] = 0;
431 new_argv[i - 3] = 0;
434 #ifdef MSDOS /* MW, July 1993 */
435 if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
436 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
437 else
439 tempfile = alloca (20);
440 *tempfile = '\0';
442 dostounix_filename (tempfile);
443 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
444 strcat (tempfile, "/");
445 strcat (tempfile, "detmp.XXX");
446 mktemp (tempfile);
448 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
449 if (outfilefd < 0)
451 close (filefd);
452 report_file_error ("Opening process output file",
453 Fcons (build_string (tempfile), Qnil));
455 fd[0] = filefd;
456 fd[1] = outfilefd;
457 #endif /* MSDOS */
459 if (INTEGERP (buffer))
460 fd[1] = open (NULL_DEVICE, O_WRONLY), fd[0] = -1;
461 else
463 #ifndef MSDOS
464 pipe (fd);
465 #endif
466 #if 0
467 /* Replaced by close_process_descs */
468 set_exclusive_use (fd[0]);
469 #endif
473 /* child_setup must clobber environ in systems with true vfork.
474 Protect it from permanent change. */
475 register char **save_environ = environ;
476 register int fd1 = fd[1];
477 int fd_error = fd1;
479 #if 0 /* Some systems don't have sigblock. */
480 mask = sigblock (sigmask (SIGCHLD));
481 #endif
483 /* Record that we're about to create a synchronous process. */
484 synch_process_alive = 1;
486 /* These vars record information from process termination.
487 Clear them now before process can possibly terminate,
488 to avoid timing error if process terminates soon. */
489 synch_process_death = 0;
490 synch_process_retcode = 0;
492 if (NILP (error_file))
493 fd_error = open (NULL_DEVICE, O_WRONLY);
494 else if (STRINGP (error_file))
496 #ifdef DOS_NT
497 fd_error = open (XSTRING (error_file)->data,
498 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
499 S_IREAD | S_IWRITE);
500 #else /* not DOS_NT */
501 fd_error = creat (XSTRING (error_file)->data, 0666);
502 #endif /* not DOS_NT */
505 if (fd_error < 0)
507 close (filefd);
508 if (fd[0] != filefd)
509 close (fd[0]);
510 if (fd1 >= 0)
511 close (fd1);
512 #ifdef MSDOS
513 unlink (tempfile);
514 #endif
515 report_file_error ("Cannot redirect stderr",
516 Fcons ((NILP (error_file)
517 ? build_string (NULL_DEVICE) : error_file),
518 Qnil));
520 #ifdef MSDOS /* MW, July 1993 */
521 /* ??? Someone who knows MSDOG needs to check whether this properly
522 closes all descriptors that it opens.
524 Note that run_msdos_command() actually returns the child process
525 exit status, not its PID, so we assign it to `synch_process_retcode'
526 below. */
527 pid = run_msdos_command (new_argv, current_dir,
528 filefd, outfilefd, fd_error);
530 /* Record that the synchronous process exited and note its
531 termination status. */
532 synch_process_alive = 0;
533 synch_process_retcode = pid;
534 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
535 synch_process_death = strerror(errno);
537 close (outfilefd);
538 if (fd_error != outfilefd)
539 close (fd_error);
540 fd1 = -1; /* No harm in closing that one! */
541 /* Since CRLF is converted to LF within `decode_coding', we can
542 always open a file with binary mode. */
543 fd[0] = open (tempfile, O_BINARY);
544 if (fd[0] < 0)
546 unlink (tempfile);
547 close (filefd);
548 report_file_error ("Cannot re-open temporary file", Qnil);
550 #else /* not MSDOS */
551 #ifdef WINDOWSNT
552 pid = child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
553 #else /* not WINDOWSNT */
554 pid = vfork ();
556 if (pid == 0)
558 if (fd[0] >= 0)
559 close (fd[0]);
560 #ifdef HAVE_SETSID
561 setsid ();
562 #endif
563 #if defined (USG) && !defined (BSD_PGRPS)
564 setpgrp ();
565 #else
566 setpgrp (pid, pid);
567 #endif /* USG */
568 child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
570 #endif /* not WINDOWSNT */
572 /* The MSDOS case did this already. */
573 if (fd_error >= 0)
574 close (fd_error);
575 #endif /* not MSDOS */
577 environ = save_environ;
579 /* Close most of our fd's, but not fd[0]
580 since we will use that to read input from. */
581 close (filefd);
582 if (fd1 >= 0 && fd1 != fd_error)
583 close (fd1);
586 if (pid < 0)
588 if (fd[0] >= 0)
589 close (fd[0]);
590 report_file_error ("Doing vfork", Qnil);
593 if (INTEGERP (buffer))
595 if (fd[0] >= 0)
596 close (fd[0]);
597 #ifndef subprocesses
598 /* If Emacs has been built with asynchronous subprocess support,
599 we don't need to do this, I think because it will then have
600 the facilities for handling SIGCHLD. */
601 wait_without_blocking ();
602 #endif /* subprocesses */
603 return Qnil;
606 /* Enable sending signal if user quits below. */
607 call_process_exited = 0;
609 #ifdef MSDOS
610 /* MSDOS needs different cleanup information. */
611 record_unwind_protect (call_process_cleanup,
612 Fcons (make_number (fd[0]), build_string (tempfile)));
613 #else
614 record_unwind_protect (call_process_cleanup,
615 Fcons (make_number (fd[0]), make_number (pid)));
616 #endif /* not MSDOS */
619 if (BUFFERP (buffer))
620 Fset_buffer (buffer);
622 immediate_quit = 1;
623 QUIT;
626 register int nread;
627 int first = 1;
628 int total_read = 0;
630 while (1)
632 /* Repeatedly read until we've filled as much as possible
633 of the buffer size we have. But don't read
634 less than 1024--save that for the next bufferful. */
636 nread = process_coding.carryover_size; /* This value is initially 0. */
637 while (nread < bufsize - 1024)
639 int this_read
640 = read (fd[0], bufptr + nread, bufsize - nread);
642 if (this_read < 0)
643 goto give_up;
645 if (this_read == 0)
646 goto give_up_1;
648 nread += this_read;
651 give_up_1:
653 /* Now NREAD is the total amount of data in the buffer. */
654 if (nread == 0)
655 /* Here, just tell decode_coding that we are processing the
656 last block. We break the loop after decoding. */
657 process_coding.last_block = 1;
659 immediate_quit = 0;
660 total_read += nread;
662 if (!NILP (buffer))
664 if (process_coding.type == coding_type_no_conversion)
665 insert (bufptr, nread);
666 else
667 { /* We have to decode the input. */
668 int size = decoding_buffer_size (&process_coding, bufsize);
669 char *decoding_buf = get_conversion_buffer (size);
670 int dummy;
672 nread = decode_coding (&process_coding, bufptr, decoding_buf,
673 nread, size, &dummy);
674 if (nread > 0)
675 insert (decoding_buf, nread);
679 if (process_coding.last_block)
680 break;
682 /* Make the buffer bigger as we continue to read more data,
683 but not past 64k. */
684 if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
686 bufsize *= 2;
687 bufptr = (char *) alloca (bufsize);
690 if (!NILP (buffer) && process_coding.carryover_size > 0)
691 /* We have carryover in the last decoding. It should be
692 processed again after reading more data. */
693 bcopy (process_coding.carryover, bufptr,
694 process_coding.carryover_size);
696 if (!NILP (display) && INTERACTIVE)
698 if (first)
699 prepare_menu_bars ();
700 first = 0;
701 redisplay_preserve_echo_area ();
703 immediate_quit = 1;
704 QUIT;
706 give_up: ;
709 /* Wait for it to terminate, unless it already has. */
710 wait_for_termination (pid);
712 immediate_quit = 0;
714 set_buffer_internal (old);
716 /* Don't kill any children that the subprocess may have left behind
717 when exiting. */
718 call_process_exited = 1;
720 unbind_to (count, Qnil);
722 if (synch_process_death)
723 return build_string (synch_process_death);
724 return make_number (synch_process_retcode);
726 #endif
728 static Lisp_Object
729 delete_temp_file (name)
730 Lisp_Object name;
732 /* Use Fdelete_file (indirectly) because that runs a file name handler.
733 We did that when writing the file, so we should do so when deleting. */
734 internal_delete_file (name);
737 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
738 3, MANY, 0,
739 "Send text from START to END to a synchronous process running PROGRAM.\n\
740 Delete the text if fourth arg DELETE is non-nil.\n\
742 Insert output in BUFFER before point; t means current buffer;\n\
743 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
744 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
745 REAL-BUFFER says what to do with standard output, as above,\n\
746 while STDERR-FILE says what to do with standard error in the child.\n\
747 STDERR-FILE may be nil (discard standard error output),\n\
748 t (mix it with ordinary output), or a file name string.\n\
750 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
751 Remaining args are passed to PROGRAM at startup as command args.\n\
753 If BUFFER is nil, `call-process-region' returns immediately with value nil.\n\
754 Otherwise it waits for PROGRAM to terminate\n\
755 and returns a numeric exit status or a signal description string.\n\
756 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
757 (nargs, args)
758 int nargs;
759 register Lisp_Object *args;
761 struct gcpro gcpro1;
762 Lisp_Object filename_string;
763 register Lisp_Object start, end;
764 int count = specpdl_ptr - specpdl;
765 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
766 Lisp_Object coding_systems = Qt;
767 Lisp_Object val, *args2;
768 int i;
769 #ifdef DOS_NT
770 char *tempfile;
771 char *outf = '\0';
773 if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
774 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
775 else
777 tempfile = alloca (20);
778 *tempfile = '\0';
780 if (!IS_DIRECTORY_SEP (tempfile[strlen (tempfile) - 1]))
781 strcat (tempfile, "/");
782 if ('/' == DIRECTORY_SEP)
783 dostounix_filename (tempfile);
784 else
785 unixtodos_filename (tempfile);
786 #ifdef WINDOWSNT
787 strcat (tempfile, "emXXXXXX");
788 #else
789 strcat (tempfile, "detmp.XXX");
790 #endif
791 #else /* not DOS_NT */
792 char *tempfile = (char *) alloca (XSTRING (Vtemp_file_name_pattern)->size + 1);
793 bcopy (XSTRING (Vtemp_file_name_pattern)->data, tempfile,
794 XSTRING (Vtemp_file_name_pattern)->size + 1);
795 #endif /* not DOS_NT */
797 mktemp (tempfile);
799 filename_string = build_string (tempfile);
800 GCPRO1 (filename_string);
801 start = args[0];
802 end = args[1];
803 /* Decide coding-system of the contents of the temporary file. */
804 #ifdef DOS_NT
805 specbind (Qbuffer_file_type, Vbinary_process_input);
806 if (NILP (Vbinary_process_input))
807 val = Qnil;
808 else
809 #endif
811 if (!NILP (Vcoding_system_for_write))
812 val = Vcoding_system_for_write;
813 else if (NILP (current_buffer->enable_multibyte_characters))
814 val = Qnil;
815 else
817 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
818 args2[0] = Qcall_process_region;
819 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
820 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
821 if (CONSP (coding_systems))
822 val = XCONS (coding_systems)->cdr;
823 else if (CONSP (Vdefault_process_coding_system))
824 val = XCONS (Vdefault_process_coding_system)->car;
825 else
826 val = Qnil;
829 specbind (intern ("coding-system-for-write"), val);
830 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil);
832 #ifdef DOS_NT
833 if (NILP (Vbinary_process_input))
834 val = Qnil;
835 else
836 #endif
838 if (!NILP (Vcoding_system_for_read))
839 val = Vcoding_system_for_read;
840 else if (NILP (current_buffer->enable_multibyte_characters))
841 val = Qemacs_mule;
842 else
844 if (EQ (coding_systems, Qt))
846 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
847 args2[0] = Qcall_process_region;
848 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
849 coding_systems = Ffind_operation_coding_system (nargs + 1,
850 args2);
852 val = CONSP (coding_systems) ? XCONS (coding_systems)->car : Qnil;
855 specbind (intern ("coding-system-for-read"), val);
857 record_unwind_protect (delete_temp_file, filename_string);
859 if (!NILP (args[3]))
860 Fdelete_region (start, end);
862 args[3] = filename_string;
864 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs - 2, args + 2)));
867 #ifndef VMS /* VMS version is in vmsproc.c. */
869 /* This is the last thing run in a newly forked inferior
870 either synchronous or asynchronous.
871 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
872 Initialize inferior's priority, pgrp, connected dir and environment.
873 then exec another program based on new_argv.
875 This function may change environ for the superior process.
876 Therefore, the superior process must save and restore the value
877 of environ around the vfork and the call to this function.
879 ENV is the environment for the subprocess.
881 SET_PGRP is nonzero if we should put the subprocess into a separate
882 process group.
884 CURRENT_DIR is an elisp string giving the path of the current
885 directory the subprocess should have. Since we can't really signal
886 a decent error from within the child, this should be verified as an
887 executable directory by the parent. */
889 child_setup (in, out, err, new_argv, set_pgrp, current_dir)
890 int in, out, err;
891 register char **new_argv;
892 int set_pgrp;
893 Lisp_Object current_dir;
895 #ifdef MSDOS
896 /* The MSDOS port of gcc cannot fork, vfork, ... so we must call system
897 instead. */
898 #else /* not MSDOS */
899 char **env;
900 char *pwd_var;
901 #ifdef WINDOWSNT
902 int cpid;
903 HANDLE handles[3];
904 #endif /* WINDOWSNT */
906 int pid = getpid ();
908 #ifdef SET_EMACS_PRIORITY
910 extern int emacs_priority;
912 if (emacs_priority < 0)
913 nice (- emacs_priority);
915 #endif
917 #ifdef subprocesses
918 /* Close Emacs's descriptors that this process should not have. */
919 close_process_descs ();
920 #endif
921 close_load_descs ();
923 /* Note that use of alloca is always safe here. It's obvious for systems
924 that do not have true vfork or that have true (stack) alloca.
925 If using vfork and C_ALLOCA it is safe because that changes
926 the superior's static variables as if the superior had done alloca
927 and will be cleaned up in the usual way. */
929 register char *temp;
930 register int i;
932 i = XSTRING (current_dir)->size;
933 pwd_var = (char *) alloca (i + 6);
934 temp = pwd_var + 4;
935 bcopy ("PWD=", pwd_var, 4);
936 bcopy (XSTRING (current_dir)->data, temp, i);
937 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
938 temp[i] = 0;
940 /* We can't signal an Elisp error here; we're in a vfork. Since
941 the callers check the current directory before forking, this
942 should only return an error if the directory's permissions
943 are changed between the check and this chdir, but we should
944 at least check. */
945 if (chdir (temp) < 0)
946 _exit (errno);
948 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
949 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
950 temp[--i] = 0;
953 /* Set `env' to a vector of the strings in Vprocess_environment. */
955 register Lisp_Object tem;
956 register char **new_env;
957 register int new_length;
959 new_length = 0;
960 for (tem = Vprocess_environment;
961 CONSP (tem) && STRINGP (XCONS (tem)->car);
962 tem = XCONS (tem)->cdr)
963 new_length++;
965 /* new_length + 2 to include PWD and terminating 0. */
966 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
968 /* If we have a PWD envvar, pass one down,
969 but with corrected value. */
970 if (getenv ("PWD"))
971 *new_env++ = pwd_var;
973 /* Copy the Vprocess_environment strings into new_env. */
974 for (tem = Vprocess_environment;
975 CONSP (tem) && STRINGP (XCONS (tem)->car);
976 tem = XCONS (tem)->cdr)
978 char **ep = env;
979 char *string = (char *) XSTRING (XCONS (tem)->car)->data;
980 /* See if this string duplicates any string already in the env.
981 If so, don't put it in.
982 When an env var has multiple definitions,
983 we keep the definition that comes first in process-environment. */
984 for (; ep != new_env; ep++)
986 char *p = *ep, *q = string;
987 while (1)
989 if (*q == 0)
990 /* The string is malformed; might as well drop it. */
991 goto duplicate;
992 if (*q != *p)
993 break;
994 if (*q == '=')
995 goto duplicate;
996 p++, q++;
999 *new_env++ = string;
1000 duplicate: ;
1002 *new_env = 0;
1004 #ifdef WINDOWSNT
1005 prepare_standard_handles (in, out, err, handles);
1006 #else /* not WINDOWSNT */
1007 /* Make sure that in, out, and err are not actually already in
1008 descriptors zero, one, or two; this could happen if Emacs is
1009 started with its standard in, out, or error closed, as might
1010 happen under X. */
1012 int oin = in, oout = out;
1014 /* We have to avoid relocating the same descriptor twice! */
1016 in = relocate_fd (in, 3);
1018 if (out == oin)
1019 out = in;
1020 else
1021 out = relocate_fd (out, 3);
1023 if (err == oin)
1024 err = in;
1025 else if (err == oout)
1026 err = out;
1027 else
1028 err = relocate_fd (err, 3);
1031 close (0);
1032 close (1);
1033 close (2);
1035 dup2 (in, 0);
1036 dup2 (out, 1);
1037 dup2 (err, 2);
1038 close (in);
1039 close (out);
1040 close (err);
1041 #endif /* not WINDOWSNT */
1043 #if defined(USG) && !defined(BSD_PGRPS)
1044 #ifndef SETPGRP_RELEASES_CTTY
1045 setpgrp (); /* No arguments but equivalent in this case */
1046 #endif
1047 #else
1048 setpgrp (pid, pid);
1049 #endif /* USG */
1050 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
1051 EMACS_SET_TTY_PGRP (0, &pid);
1053 #ifdef vipc
1054 something missing here;
1055 #endif /* vipc */
1057 #ifdef WINDOWSNT
1058 /* Spawn the child. (See ntproc.c:Spawnve). */
1059 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1060 if (cpid == -1)
1061 /* An error occurred while trying to spawn the process. */
1062 report_file_error ("Spawning child process", Qnil);
1063 reset_standard_handles (in, out, err, handles);
1064 return cpid;
1065 #else /* not WINDOWSNT */
1066 /* execvp does not accept an environment arg so the only way
1067 to pass this environment is to set environ. Our caller
1068 is responsible for restoring the ambient value of environ. */
1069 environ = env;
1070 execvp (new_argv[0], new_argv);
1072 write (1, "Can't exec program: ", 20);
1073 write (1, new_argv[0], strlen (new_argv[0]));
1074 write (1, "\n", 1);
1075 _exit (1);
1076 #endif /* not WINDOWSNT */
1077 #endif /* not MSDOS */
1080 /* Move the file descriptor FD so that its number is not less than MIN.
1081 If the file descriptor is moved at all, the original is freed. */
1083 relocate_fd (fd, min)
1084 int fd, min;
1086 if (fd >= min)
1087 return fd;
1088 else
1090 int new = dup (fd);
1091 if (new == -1)
1093 char *message1 = "Error while setting up child: ";
1094 char *errmessage = strerror (errno);
1095 char *message2 = "\n";
1096 write (2, message1, strlen (message1));
1097 write (2, errmessage, strlen (errmessage));
1098 write (2, message2, strlen (message2));
1099 _exit (1);
1101 /* Note that we hold the original FD open while we recurse,
1102 to guarantee we'll get a new FD if we need it. */
1103 new = relocate_fd (new, min);
1104 close (fd);
1105 return new;
1109 static int
1110 getenv_internal (var, varlen, value, valuelen)
1111 char *var;
1112 int varlen;
1113 char **value;
1114 int *valuelen;
1116 Lisp_Object scan;
1118 for (scan = Vprocess_environment; CONSP (scan); scan = XCONS (scan)->cdr)
1120 Lisp_Object entry;
1122 entry = XCONS (scan)->car;
1123 if (STRINGP (entry)
1124 && XSTRING (entry)->size > varlen
1125 && XSTRING (entry)->data[varlen] == '='
1126 #ifdef WINDOWSNT
1127 /* NT environment variables are case insensitive. */
1128 && ! strnicmp (XSTRING (entry)->data, var, varlen)
1129 #else /* not WINDOWSNT */
1130 && ! bcmp (XSTRING (entry)->data, var, varlen)
1131 #endif /* not WINDOWSNT */
1134 *value = (char *) XSTRING (entry)->data + (varlen + 1);
1135 *valuelen = XSTRING (entry)->size - (varlen + 1);
1136 return 1;
1140 return 0;
1143 DEFUN ("getenv", Fgetenv, Sgetenv, 1, 1, 0,
1144 "Return the value of environment variable VAR, as a string.\n\
1145 VAR should be a string. Value is nil if VAR is undefined in the environment.\n\
1146 This function consults the variable ``process-environment'' for its value.")
1147 (var)
1148 Lisp_Object var;
1150 char *value;
1151 int valuelen;
1153 CHECK_STRING (var, 0);
1154 if (getenv_internal (XSTRING (var)->data, XSTRING (var)->size,
1155 &value, &valuelen))
1156 return make_string (value, valuelen);
1157 else
1158 return Qnil;
1161 /* A version of getenv that consults process_environment, easily
1162 callable from C. */
1163 char *
1164 egetenv (var)
1165 char *var;
1167 char *value;
1168 int valuelen;
1170 if (getenv_internal (var, strlen (var), &value, &valuelen))
1171 return value;
1172 else
1173 return 0;
1176 #endif /* not VMS */
1178 /* This is run before init_cmdargs. */
1180 init_callproc_1 ()
1182 char *data_dir = egetenv ("EMACSDATA");
1183 char *doc_dir = egetenv ("EMACSDOC");
1185 Vdata_directory
1186 = Ffile_name_as_directory (build_string (data_dir ? data_dir
1187 : PATH_DATA));
1188 Vdoc_directory
1189 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
1190 : PATH_DOC));
1192 /* Check the EMACSPATH environment variable, defaulting to the
1193 PATH_EXEC path from paths.h. */
1194 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1195 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1196 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1199 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1201 init_callproc ()
1203 char *data_dir = egetenv ("EMACSDATA");
1205 register char * sh;
1206 Lisp_Object tempdir;
1208 if (initialized && !NILP (Vinstallation_directory))
1210 /* Add to the path the lib-src subdir of the installation dir. */
1211 Lisp_Object tem;
1212 tem = Fexpand_file_name (build_string ("lib-src"),
1213 Vinstallation_directory);
1214 if (NILP (Fmember (tem, Vexec_path)))
1216 #ifndef DOS_NT
1217 /* MSDOS uses wrapped binaries, so don't do this. */
1218 Vexec_path = nconc2 (Vexec_path, Fcons (tem, Qnil));
1219 Vexec_directory = Ffile_name_as_directory (tem);
1220 #endif /* not DOS_NT */
1223 /* Maybe use ../etc as well as ../lib-src. */
1224 if (data_dir == 0)
1226 tem = Fexpand_file_name (build_string ("etc"),
1227 Vinstallation_directory);
1228 Vdoc_directory = Ffile_name_as_directory (tem);
1232 /* Look for the files that should be in etc. We don't use
1233 Vinstallation_directory, because these files are never installed
1234 near the executable, and they are never in the build
1235 directory when that's different from the source directory.
1237 Instead, if these files are not in the nominal place, we try the
1238 source directory. */
1239 if (data_dir == 0)
1241 Lisp_Object tem, tem1, newdir;
1243 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1244 tem1 = Ffile_exists_p (tem);
1245 if (NILP (tem1))
1247 newdir = Fexpand_file_name (build_string ("../etc/"),
1248 build_string (PATH_DUMPLOADSEARCH));
1249 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1250 tem1 = Ffile_exists_p (tem);
1251 if (!NILP (tem1))
1252 Vdata_directory = newdir;
1256 tempdir = Fdirectory_file_name (Vexec_directory);
1257 if (access (XSTRING (tempdir)->data, 0) < 0)
1258 dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
1259 Vexec_directory);
1261 tempdir = Fdirectory_file_name (Vdata_directory);
1262 if (access (XSTRING (tempdir)->data, 0) < 0)
1263 dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
1264 Vdata_directory);
1266 #ifdef VMS
1267 Vshell_file_name = build_string ("*dcl*");
1268 #else
1269 sh = (char *) getenv ("SHELL");
1270 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1271 #endif
1273 #ifdef VMS
1274 Vtemp_file_name_pattern = build_string ("tmp:emacsXXXXXX.");
1275 #else
1276 if (getenv ("TMPDIR"))
1278 char *dir = getenv ("TMPDIR");
1279 Vtemp_file_name_pattern
1280 = Fexpand_file_name (build_string ("emacsXXXXXX"),
1281 build_string (dir));
1283 else
1284 Vtemp_file_name_pattern = build_string ("/tmp/emacsXXXXXX");
1285 #endif
1288 set_process_environment ()
1290 register char **envp;
1292 Vprocess_environment = Qnil;
1293 #ifndef CANNOT_DUMP
1294 if (initialized)
1295 #endif
1296 for (envp = environ; *envp; envp++)
1297 Vprocess_environment = Fcons (build_string (*envp),
1298 Vprocess_environment);
1301 syms_of_callproc ()
1303 #ifdef DOS_NT
1304 Qbuffer_file_type = intern ("buffer-file-type");
1305 staticpro (&Qbuffer_file_type);
1307 DEFVAR_LISP ("binary-process-input", &Vbinary_process_input,
1308 "*If non-nil then new subprocesses are assumed to take binary input.");
1309 Vbinary_process_input = Qnil;
1311 DEFVAR_LISP ("binary-process-output", &Vbinary_process_output,
1312 "*If non-nil then new subprocesses are assumed to produce binary output.");
1313 Vbinary_process_output = Qnil;
1314 #endif /* DOS_NT */
1316 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
1317 "*File name to load inferior shells from.\n\
1318 Initialized from the SHELL environment variable.");
1320 DEFVAR_LISP ("exec-path", &Vexec_path,
1321 "*List of directories to search programs to run in subprocesses.\n\
1322 Each element is a string (directory name) or nil (try default directory).");
1324 DEFVAR_LISP ("exec-directory", &Vexec_directory,
1325 "Directory of architecture-dependent files that come with GNU Emacs,\n\
1326 especially executable programs intended for Emacs to invoke.");
1328 DEFVAR_LISP ("data-directory", &Vdata_directory,
1329 "Directory of architecture-independent files that come with GNU Emacs,\n\
1330 intended for Emacs to use.");
1332 DEFVAR_LISP ("doc-directory", &Vdoc_directory,
1333 "Directory containing the DOC file that comes with GNU Emacs.\n\
1334 This is usually the same as data-directory.");
1336 DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
1337 "For internal use by the build procedure only.\n\
1338 This is the name of the directory in which the build procedure installed\n\
1339 Emacs's info files; the default value for Info-default-directory-list\n\
1340 includes this.");
1341 Vconfigure_info_directory = build_string (PATH_INFO);
1343 DEFVAR_LISP ("temp-file-name-pattern", &Vtemp_file_name_pattern,
1344 "Pattern for making names for temporary files.\n\
1345 This is used by `call-process-region'.");
1346 /* The real initialization is when we start again. */
1347 Vtemp_file_name_pattern = Qnil;
1349 DEFVAR_LISP ("process-environment", &Vprocess_environment,
1350 "List of environment variables for subprocesses to inherit.\n\
1351 Each element should be a string of the form ENVVARNAME=VALUE.\n\
1352 The environment which Emacs inherits is placed in this variable\n\
1353 when Emacs starts.");
1355 #ifndef VMS
1356 defsubr (&Scall_process);
1357 defsubr (&Sgetenv);
1358 #endif
1359 defsubr (&Scall_process_region);