* subr.el (with-current-buffer): don't use backquotes to avoid
[emacs.git] / src / callproc.c
blobde6856b5068f9c8a30acb167d7f32397794e74b7
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 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
43 #include <sys/file.h>
44 #ifdef USG5
45 #define INCLUDED_FCNTL
46 #include <fcntl.h>
47 #endif
49 #ifdef WINDOWSNT
50 #define NOMINMAX
51 #include <windows.h>
52 #include <stdlib.h> /* for proper declaration of environ */
53 #include <fcntl.h>
54 #include "w32.h"
55 #define _P_NOWAIT 1 /* from process.h */
56 #endif
58 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
59 #define INCLUDED_FCNTL
60 #include <fcntl.h>
61 #include <sys/stat.h>
62 #include <sys/param.h>
63 #include <errno.h>
64 #endif /* MSDOS */
66 #ifndef O_RDONLY
67 #define O_RDONLY 0
68 #endif
70 #ifndef O_WRONLY
71 #define O_WRONLY 1
72 #endif
74 #include "lisp.h"
75 #include "commands.h"
76 #include "buffer.h"
77 #include "charset.h"
78 #include "ccl.h"
79 #include "coding.h"
80 #include <epaths.h>
81 #include "process.h"
82 #include "syssignal.h"
83 #include "systty.h"
85 #ifdef MSDOS
86 #include "msdos.h"
87 #endif
89 #ifdef VMS
90 extern noshare char **environ;
91 #else
92 extern char **environ;
93 #endif
95 #define max(a, b) ((a) > (b) ? (a) : (b))
97 Lisp_Object Vexec_path, Vexec_directory, Vdata_directory, Vdoc_directory;
98 Lisp_Object Vconfigure_info_directory;
99 Lisp_Object Vtemp_file_name_pattern;
101 Lisp_Object Vshell_file_name;
103 Lisp_Object Vprocess_environment;
105 #ifdef DOS_NT
106 Lisp_Object Qbuffer_file_type;
107 #endif /* DOS_NT */
109 /* True iff we are about to fork off a synchronous process or if we
110 are waiting for it. */
111 int synch_process_alive;
113 /* Nonzero => this is a string explaining death of synchronous subprocess. */
114 char *synch_process_death;
116 /* If synch_process_death is zero,
117 this is exit code of synchronous subprocess. */
118 int synch_process_retcode;
120 extern Lisp_Object Vdoc_file_name;
122 extern Lisp_Object Vfile_name_coding_system, Vdefault_file_name_coding_system;
124 /* Clean up when exiting Fcall_process.
125 On MSDOS, delete the temporary file on any kind of termination.
126 On Unix, kill the process and any children on termination by signal. */
128 /* Nonzero if this is termination due to exit. */
129 static int call_process_exited;
131 #ifndef VMS /* VMS version is in vmsproc.c. */
133 static Lisp_Object
134 call_process_kill (fdpid)
135 Lisp_Object fdpid;
137 close (XFASTINT (Fcar (fdpid)));
138 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
139 synch_process_alive = 0;
140 return Qnil;
143 Lisp_Object
144 call_process_cleanup (fdpid)
145 Lisp_Object fdpid;
147 #if defined (MSDOS) || defined (macintosh)
148 /* for MSDOS fdpid is really (fd . tempfile) */
149 register Lisp_Object file;
150 file = Fcdr (fdpid);
151 close (XFASTINT (Fcar (fdpid)));
152 if (strcmp (XSTRING (file)-> data, NULL_DEVICE) != 0)
153 unlink (XSTRING (file)->data);
154 #else /* not MSDOS and not macintosh */
155 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 remaining arguments are optional.\n\
184 The program's input comes from file INFILE (nil means `/dev/null').\n\
185 Insert output in BUFFER before point; t means current buffer;\n\
186 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
187 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
188 REAL-BUFFER says what to do with standard output, as above,\n\
189 while STDERR-FILE says what to do with standard error in the child.\n\
190 STDERR-FILE may be nil (discard standard error output),\n\
191 t (mix it with ordinary output), or a file name string.\n\
193 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
194 Remaining arguments are strings passed as command arguments to PROGRAM.\n\
196 If BUFFER is 0, `call-process' returns immediately with value nil.\n\
197 Otherwise it waits for PROGRAM to terminate\n\
198 and returns a numeric exit status or a signal description string.\n\
199 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
200 (nargs, args)
201 int nargs;
202 register Lisp_Object *args;
204 Lisp_Object infile, buffer, current_dir, display, path;
205 int fd[2];
206 int filefd;
207 register int pid;
208 char buf[16384];
209 char *bufptr = buf;
210 int bufsize = 16384;
211 int count = specpdl_ptr - specpdl;
213 register unsigned char **new_argv
214 = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
215 struct buffer *old = current_buffer;
216 /* File to use for stderr in the child.
217 t means use same as standard output. */
218 Lisp_Object error_file;
219 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
220 char *outf, *tempfile;
221 int outfilefd;
222 #endif
223 #ifdef macintosh
224 char *tempfile;
225 int outfilefd;
226 #endif
227 #if 0
228 int mask;
229 #endif
230 struct coding_system process_coding; /* coding-system of process output */
231 struct coding_system argument_coding; /* coding-system of arguments */
232 /* Set to the return value of Ffind_operation_coding_system. */
233 Lisp_Object coding_systems;
235 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
236 coding_systems = Qt;
238 CHECK_STRING (args[0], 0);
240 error_file = Qt;
242 #ifndef subprocesses
243 /* Without asynchronous processes we cannot have BUFFER == 0. */
244 if (nargs >= 3
245 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
246 error ("Operating system cannot handle asynchronous subprocesses");
247 #endif /* subprocesses */
249 /* Decide the coding-system for giving arguments. */
251 Lisp_Object val, *args2;
252 int i;
254 /* If arguments are supplied, we may have to encode them. */
255 if (nargs >= 5)
257 int must_encode = 0;
259 for (i = 4; i < nargs; i++)
260 CHECK_STRING (args[i], i);
262 for (i = 4; i < nargs; i++)
263 if (STRING_MULTIBYTE (args[i]))
264 must_encode = 1;
266 if (!NILP (Vcoding_system_for_write))
267 val = Vcoding_system_for_write;
268 else if (! must_encode)
269 val = Qnil;
270 else
272 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
273 args2[0] = Qcall_process;
274 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
275 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
276 if (CONSP (coding_systems))
277 val = XCDR (coding_systems);
278 else if (CONSP (Vdefault_process_coding_system))
279 val = XCDR (Vdefault_process_coding_system);
280 else
281 val = Qnil;
283 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
287 if (nargs >= 2 && ! NILP (args[1]))
289 infile = Fexpand_file_name (args[1], current_buffer->directory);
290 CHECK_STRING (infile, 1);
292 else
293 infile = build_string (NULL_DEVICE);
295 if (nargs >= 3)
297 buffer = args[2];
299 /* If BUFFER is a list, its meaning is
300 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
301 if (CONSP (buffer))
303 if (CONSP (XCDR (buffer)))
305 Lisp_Object stderr_file;
306 stderr_file = XCAR (XCDR (buffer));
308 if (NILP (stderr_file) || EQ (Qt, stderr_file))
309 error_file = stderr_file;
310 else
311 error_file = Fexpand_file_name (stderr_file, Qnil);
314 buffer = XCAR (buffer);
317 if (!(EQ (buffer, Qnil)
318 || EQ (buffer, Qt)
319 || INTEGERP (buffer)))
321 Lisp_Object spec_buffer;
322 spec_buffer = buffer;
323 buffer = Fget_buffer_create (buffer);
324 /* Mention the buffer name for a better error message. */
325 if (NILP (buffer))
326 CHECK_BUFFER (spec_buffer, 2);
327 CHECK_BUFFER (buffer, 2);
330 else
331 buffer = Qnil;
333 /* Make sure that the child will be able to chdir to the current
334 buffer's current directory, or its unhandled equivalent. We
335 can't just have the child check for an error when it does the
336 chdir, since it's in a vfork.
338 We have to GCPRO around this because Fexpand_file_name,
339 Funhandled_file_name_directory, and Ffile_accessible_directory_p
340 might call a file name handling function. The argument list is
341 protected by the caller, so all we really have to worry about is
342 buffer. */
344 struct gcpro gcpro1, gcpro2, gcpro3;
346 current_dir = current_buffer->directory;
348 GCPRO3 (infile, buffer, current_dir);
350 current_dir
351 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
352 Qnil);
353 if (NILP (Ffile_accessible_directory_p (current_dir)))
354 report_file_error ("Setting current directory",
355 Fcons (current_buffer->directory, Qnil));
357 UNGCPRO;
360 display = nargs >= 4 ? args[3] : Qnil;
362 filefd = open (XSTRING (infile)->data, O_RDONLY, 0);
363 if (filefd < 0)
365 report_file_error ("Opening process input file", Fcons (infile, Qnil));
367 /* Search for program; barf if not found. */
369 struct gcpro gcpro1;
371 GCPRO1 (current_dir);
372 openp (Vexec_path, args[0], EXEC_SUFFIXES, &path, 1);
373 UNGCPRO;
375 if (NILP (path))
377 close (filefd);
378 report_file_error ("Searching for program", Fcons (args[0], Qnil));
380 new_argv[0] = XSTRING (path)->data;
381 if (nargs > 4)
383 register int i;
385 if (! CODING_REQUIRE_ENCODING (&argument_coding))
387 for (i = 4; i < nargs; i++)
388 new_argv[i - 3] = XSTRING (args[i])->data;
390 else
392 /* We must encode the arguments. */
393 struct gcpro gcpro1, gcpro2, gcpro3;
395 GCPRO3 (infile, buffer, current_dir);
396 for (i = 4; i < nargs; i++)
398 int size = encoding_buffer_size (&argument_coding,
399 STRING_BYTES (XSTRING (args[i])));
400 unsigned char *dummy1 = (unsigned char *) alloca (size);
402 /* The Irix 4.0 compiler barfs if we eliminate dummy. */
403 new_argv[i - 3] = dummy1;
404 argument_coding.mode |= CODING_MODE_LAST_BLOCK;
405 encode_coding (&argument_coding,
406 XSTRING (args[i])->data,
407 new_argv[i - 3],
408 STRING_BYTES (XSTRING (args[i])),
409 size);
410 new_argv[i - 3][argument_coding.produced] = 0;
411 /* We have to initialize CCL program status again. */
412 if (argument_coding.type == coding_type_ccl)
413 setup_ccl_program (&(argument_coding.spec.ccl.encoder), Qnil);
415 UNGCPRO;
417 new_argv[nargs - 3] = 0;
419 else
420 new_argv[1] = 0;
422 #ifdef MSDOS /* MW, July 1993 */
423 if ((outf = egetenv ("TMPDIR")))
424 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
425 else
427 tempfile = alloca (20);
428 *tempfile = '\0';
430 dostounix_filename (tempfile);
431 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
432 strcat (tempfile, "/");
433 strcat (tempfile, "detmp.XXX");
434 mktemp (tempfile);
436 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
437 if (outfilefd < 0)
439 close (filefd);
440 report_file_error ("Opening process output file",
441 Fcons (build_string (tempfile), Qnil));
443 fd[0] = filefd;
444 fd[1] = outfilefd;
445 #endif /* MSDOS */
447 #ifdef macintosh
448 /* Since we don't have pipes on the Mac, create a temporary file to
449 hold the output of the subprocess. */
450 tempfile = (char *) alloca (STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
451 bcopy (XSTRING (Vtemp_file_name_pattern)->data, tempfile,
452 STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
454 mktemp (tempfile);
456 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
457 if (outfilefd < 0)
459 close (filefd);
460 report_file_error ("Opening process output file",
461 Fcons (build_string (tempfile), Qnil));
463 fd[0] = filefd;
464 fd[1] = outfilefd;
465 #endif /* macintosh */
467 if (INTEGERP (buffer))
468 fd[1] = open (NULL_DEVICE, O_WRONLY), fd[0] = -1;
469 else
471 #ifndef MSDOS
472 #ifndef macintosh
473 pipe (fd);
474 #endif
475 #endif
476 #if 0
477 /* Replaced by close_process_descs */
478 set_exclusive_use (fd[0]);
479 #endif
483 /* child_setup must clobber environ in systems with true vfork.
484 Protect it from permanent change. */
485 register char **save_environ = environ;
486 register int fd1 = fd[1];
487 int fd_error = fd1;
489 #if 0 /* Some systems don't have sigblock. */
490 mask = sigblock (sigmask (SIGCHLD));
491 #endif
493 /* Record that we're about to create a synchronous process. */
494 synch_process_alive = 1;
496 /* These vars record information from process termination.
497 Clear them now before process can possibly terminate,
498 to avoid timing error if process terminates soon. */
499 synch_process_death = 0;
500 synch_process_retcode = 0;
502 if (NILP (error_file))
503 fd_error = open (NULL_DEVICE, O_WRONLY);
504 else if (STRINGP (error_file))
506 #ifdef DOS_NT
507 fd_error = open (XSTRING (error_file)->data,
508 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
509 S_IREAD | S_IWRITE);
510 #else /* not DOS_NT */
511 fd_error = creat (XSTRING (error_file)->data, 0666);
512 #endif /* not DOS_NT */
515 if (fd_error < 0)
517 close (filefd);
518 if (fd[0] != filefd)
519 close (fd[0]);
520 if (fd1 >= 0)
521 close (fd1);
522 #ifdef MSDOS
523 unlink (tempfile);
524 #endif
525 report_file_error ("Cannot redirect stderr",
526 Fcons ((NILP (error_file)
527 ? build_string (NULL_DEVICE) : error_file),
528 Qnil));
531 current_dir = ENCODE_FILE (current_dir);
533 #ifdef macintosh
535 /* Call run_mac_command in sysdep.c here directly instead of doing
536 a child_setup as for MSDOS and other platforms. Note that this
537 code does not handle passing the environment to the synchronous
538 Mac subprocess. */
539 char *infn, *outfn, *errfn, *currdn;
541 /* close these files so subprocess can write to them */
542 close (outfilefd);
543 if (fd_error != outfilefd)
544 close (fd_error);
545 fd1 = -1; /* No harm in closing that one! */
547 infn = XSTRING (infile)->data;
548 outfn = tempfile;
549 if (NILP (error_file))
550 errfn = NULL_DEVICE;
551 else if (EQ (Qt, error_file))
552 errfn = outfn;
553 else
554 errfn = XSTRING (error_file)->data;
555 currdn = XSTRING (current_dir)->data;
556 pid = run_mac_command (new_argv, currdn, infn, outfn, errfn);
558 /* Record that the synchronous process exited and note its
559 termination status. */
560 synch_process_alive = 0;
561 synch_process_retcode = pid;
562 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
563 synch_process_death = strerror (errno);
565 /* Since CRLF is converted to LF within `decode_coding', we can
566 always open a file with binary mode. */
567 fd[0] = open (tempfile, O_BINARY);
568 if (fd[0] < 0)
570 unlink (tempfile);
571 close (filefd);
572 report_file_error ("Cannot re-open temporary file", Qnil);
575 #else /* not macintosh */
576 #ifdef MSDOS /* MW, July 1993 */
577 /* Note that on MSDOS `child_setup' actually returns the child process
578 exit status, not its PID, so we assign it to `synch_process_retcode'
579 below. */
580 pid = child_setup (filefd, outfilefd, fd_error, (char **) new_argv,
581 0, current_dir);
583 /* Record that the synchronous process exited and note its
584 termination status. */
585 synch_process_alive = 0;
586 synch_process_retcode = pid;
587 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
588 synch_process_death = strerror (errno);
590 close (outfilefd);
591 if (fd_error != outfilefd)
592 close (fd_error);
593 fd1 = -1; /* No harm in closing that one! */
594 /* Since CRLF is converted to LF within `decode_coding', we can
595 always open a file with binary mode. */
596 fd[0] = open (tempfile, O_BINARY);
597 if (fd[0] < 0)
599 unlink (tempfile);
600 close (filefd);
601 report_file_error ("Cannot re-open temporary file", Qnil);
603 #else /* not MSDOS */
604 #ifdef WINDOWSNT
605 pid = child_setup (filefd, fd1, fd_error, (char **) new_argv,
606 0, current_dir);
607 #else /* not WINDOWSNT */
608 pid = vfork ();
610 if (pid == 0)
612 if (fd[0] >= 0)
613 close (fd[0]);
614 #ifdef HAVE_SETSID
615 setsid ();
616 #endif
617 #if defined (USG) && !defined (BSD_PGRPS)
618 setpgrp ();
619 #else
620 setpgrp (pid, pid);
621 #endif /* USG */
622 child_setup (filefd, fd1, fd_error, (char **) new_argv,
623 0, current_dir);
625 #endif /* not WINDOWSNT */
627 /* The MSDOS case did this already. */
628 if (fd_error >= 0)
629 close (fd_error);
630 #endif /* not MSDOS */
631 #endif /* not macintosh */
633 environ = save_environ;
635 /* Close most of our fd's, but not fd[0]
636 since we will use that to read input from. */
637 close (filefd);
638 if (fd1 >= 0 && fd1 != fd_error)
639 close (fd1);
642 if (pid < 0)
644 if (fd[0] >= 0)
645 close (fd[0]);
646 report_file_error ("Doing vfork", Qnil);
649 if (INTEGERP (buffer))
651 if (fd[0] >= 0)
652 close (fd[0]);
653 #ifndef subprocesses
654 /* If Emacs has been built with asynchronous subprocess support,
655 we don't need to do this, I think because it will then have
656 the facilities for handling SIGCHLD. */
657 wait_without_blocking ();
658 #endif /* subprocesses */
659 return Qnil;
662 /* Enable sending signal if user quits below. */
663 call_process_exited = 0;
665 #if defined(MSDOS) || defined(macintosh)
666 /* MSDOS needs different cleanup information. */
667 record_unwind_protect (call_process_cleanup,
668 Fcons (make_number (fd[0]), build_string (tempfile)));
669 #else
670 record_unwind_protect (call_process_cleanup,
671 Fcons (make_number (fd[0]), make_number (pid)));
672 #endif /* not MSDOS and not macintosh */
675 if (BUFFERP (buffer))
676 Fset_buffer (buffer);
678 if (NILP (buffer))
680 /* If BUFFER is nil, we must read process output once and then
681 discard it, so setup coding system but with nil. */
682 setup_coding_system (Qnil, &process_coding);
684 else
686 Lisp_Object val, *args2;
688 val = Qnil;
689 if (!NILP (Vcoding_system_for_read))
690 val = Vcoding_system_for_read;
691 else
693 if (EQ (coding_systems, Qt))
695 int i;
697 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
698 args2[0] = Qcall_process;
699 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
700 coding_systems
701 = Ffind_operation_coding_system (nargs + 1, args2);
703 if (CONSP (coding_systems))
704 val = XCAR (coding_systems);
705 else if (CONSP (Vdefault_process_coding_system))
706 val = XCAR (Vdefault_process_coding_system);
707 else
708 val = Qnil;
710 setup_coding_system (Fcheck_coding_system (val), &process_coding);
711 /* In unibyte mode, character code conversion should not take
712 place but EOL conversion should. So, setup raw-text or one
713 of the subsidiary according to the information just setup. */
714 if (NILP (current_buffer->enable_multibyte_characters)
715 && !NILP (val))
716 setup_raw_text_coding_system (&process_coding);
719 immediate_quit = 1;
720 QUIT;
723 register int nread;
724 int first = 1;
725 int total_read = 0;
726 int carryover = 0;
727 int display_on_the_fly = !NILP (display) && INTERACTIVE;
728 struct coding_system saved_coding;
730 saved_coding = process_coding;
732 while (1)
734 /* Repeatedly read until we've filled as much as possible
735 of the buffer size we have. But don't read
736 less than 1024--save that for the next bufferful. */
737 nread = carryover;
738 while (nread < bufsize - 1024)
740 int this_read = read (fd[0], bufptr + nread, bufsize - nread);
742 if (this_read < 0)
743 goto give_up;
745 if (this_read == 0)
747 process_coding.mode |= CODING_MODE_LAST_BLOCK;
748 break;
751 nread += this_read;
752 total_read += this_read;
754 if (display_on_the_fly)
755 break;
758 /* Now NREAD is the total amount of data in the buffer. */
759 immediate_quit = 0;
761 if (!NILP (buffer))
763 if (process_coding.type == coding_type_no_conversion)
764 insert (bufptr, nread);
765 else
766 { /* We have to decode the input. */
767 int size = decoding_buffer_size (&process_coding, nread);
768 char *decoding_buf = (char *) xmalloc (size);
770 decode_coding (&process_coding, bufptr, decoding_buf,
771 nread, size);
772 if (display_on_the_fly
773 && saved_coding.type == coding_type_undecided
774 && process_coding.type != coding_type_undecided)
776 /* We have detected some coding system. But,
777 there's a possibility that the detection was
778 done by insufficient data. So, we give up
779 displaying on the fly. */
780 xfree (decoding_buf);
781 display_on_the_fly = 0;
782 process_coding = saved_coding;
783 carryover = nread;
784 continue;
786 if (process_coding.produced > 0)
787 insert (decoding_buf, process_coding.produced);
788 xfree (decoding_buf);
789 carryover = nread - process_coding.consumed;
790 if (carryover > 0)
792 /* As CARRYOVER should not be that large, we had
793 better avoid overhead of bcopy. */
794 char *p = bufptr + process_coding.consumed;
795 char *pend = p + carryover;
796 char *dst = bufptr;
798 while (p < pend) *dst++ = *p++;
802 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
804 if (carryover > 0)
805 insert (bufptr, carryover);
806 break;
809 /* Make the buffer bigger as we continue to read more data,
810 but not past 64k. */
811 if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
813 bufsize *= 2;
814 bufptr = (char *) alloca (bufsize);
817 if (!NILP (display) && INTERACTIVE)
819 if (first)
820 prepare_menu_bars ();
821 first = 0;
822 redisplay_preserve_echo_area ();
824 immediate_quit = 1;
825 QUIT;
827 give_up: ;
829 Vlast_coding_system_used = process_coding.symbol;
831 /* If the caller required, let the buffer inherit the
832 coding-system used to decode the process output. */
833 if (inherit_process_coding_system)
834 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
835 make_number (total_read));
838 /* Wait for it to terminate, unless it already has. */
839 wait_for_termination (pid);
841 immediate_quit = 0;
843 set_buffer_internal (old);
845 /* Don't kill any children that the subprocess may have left behind
846 when exiting. */
847 call_process_exited = 1;
849 unbind_to (count, Qnil);
851 if (synch_process_death)
852 return build_string (synch_process_death);
853 return make_number (synch_process_retcode);
855 #endif
857 static Lisp_Object
858 delete_temp_file (name)
859 Lisp_Object name;
861 /* Use Fdelete_file (indirectly) because that runs a file name handler.
862 We did that when writing the file, so we should do so when deleting. */
863 internal_delete_file (name);
866 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
867 3, MANY, 0,
868 "Send text from START to END to a synchronous process running PROGRAM.\n\
869 The remaining arguments are optional.\n\
870 Delete the text if fourth arg DELETE is non-nil.\n\
872 Insert output in BUFFER before point; t means current buffer;\n\
873 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
874 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
875 REAL-BUFFER says what to do with standard output, as above,\n\
876 while STDERR-FILE says what to do with standard error in the child.\n\
877 STDERR-FILE may be nil (discard standard error output),\n\
878 t (mix it with ordinary output), or a file name string.\n\
880 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
881 Remaining args are passed to PROGRAM at startup as command args.\n\
883 If BUFFER is nil, `call-process-region' returns immediately with value nil.\n\
884 Otherwise it waits for PROGRAM to terminate\n\
885 and returns a numeric exit status or a signal description string.\n\
886 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
887 (nargs, args)
888 int nargs;
889 register Lisp_Object *args;
891 struct gcpro gcpro1;
892 Lisp_Object filename_string;
893 register Lisp_Object start, end;
894 int count = specpdl_ptr - specpdl;
895 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
896 Lisp_Object coding_systems;
897 Lisp_Object val, *args2;
898 int i;
899 #ifdef DOS_NT
900 char *tempfile;
901 char *outf = '\0';
903 if ((outf = egetenv ("TMPDIR"))
904 || (outf = egetenv ("TMP"))
905 || (outf = egetenv ("TEMP")))
906 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
907 else
909 tempfile = alloca (20);
910 *tempfile = '\0';
912 if (!IS_DIRECTORY_SEP (tempfile[strlen (tempfile) - 1]))
913 strcat (tempfile, "/");
914 if ('/' == DIRECTORY_SEP)
915 dostounix_filename (tempfile);
916 else
917 unixtodos_filename (tempfile);
918 #ifdef WINDOWSNT
919 strcat (tempfile, "emXXXXXX");
920 #else
921 strcat (tempfile, "detmp.XXX");
922 #endif
923 #else /* not DOS_NT */
924 char *tempfile = (char *) alloca (STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
925 bcopy (XSTRING (Vtemp_file_name_pattern)->data, tempfile,
926 STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
927 #endif /* not DOS_NT */
929 coding_systems = Qt;
931 mktemp (tempfile);
933 filename_string = build_string (tempfile);
934 GCPRO1 (filename_string);
935 start = args[0];
936 end = args[1];
937 /* Decide coding-system of the contents of the temporary file. */
938 if (!NILP (Vcoding_system_for_write))
939 val = Vcoding_system_for_write;
940 else if (NILP (current_buffer->enable_multibyte_characters))
941 val = Qnil;
942 else
944 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
945 args2[0] = Qcall_process_region;
946 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
947 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
948 if (CONSP (coding_systems))
949 val = XCDR (coding_systems);
950 else if (CONSP (Vdefault_process_coding_system))
951 val = XCDR (Vdefault_process_coding_system);
952 else
953 val = Qnil;
957 int count1 = specpdl_ptr - specpdl;
959 specbind (intern ("coding-system-for-write"), val);
960 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
962 unbind_to (count1, Qnil);
965 /* Note that Fcall_process takes care of binding
966 coding-system-for-read. */
968 record_unwind_protect (delete_temp_file, filename_string);
970 if (nargs > 3 && !NILP (args[3]))
971 Fdelete_region (start, end);
973 if (nargs > 3)
975 args += 2;
976 nargs -= 2;
978 else
980 args[0] = args[2];
981 nargs = 2;
983 args[1] = filename_string;
985 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs, args)));
988 #ifndef VMS /* VMS version is in vmsproc.c. */
990 static int relocate_fd ();
992 /* This is the last thing run in a newly forked inferior
993 either synchronous or asynchronous.
994 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
995 Initialize inferior's priority, pgrp, connected dir and environment.
996 then exec another program based on new_argv.
998 This function may change environ for the superior process.
999 Therefore, the superior process must save and restore the value
1000 of environ around the vfork and the call to this function.
1002 SET_PGRP is nonzero if we should put the subprocess into a separate
1003 process group.
1005 CURRENT_DIR is an elisp string giving the path of the current
1006 directory the subprocess should have. Since we can't really signal
1007 a decent error from within the child, this should be verified as an
1008 executable directory by the parent. */
1011 child_setup (in, out, err, new_argv, set_pgrp, current_dir)
1012 int in, out, err;
1013 register char **new_argv;
1014 int set_pgrp;
1015 Lisp_Object current_dir;
1017 char **env;
1018 char *pwd_var;
1019 #ifdef WINDOWSNT
1020 int cpid;
1021 HANDLE handles[3];
1022 #endif /* WINDOWSNT */
1024 int pid = getpid ();
1026 #ifdef SET_EMACS_PRIORITY
1028 extern int emacs_priority;
1030 if (emacs_priority < 0)
1031 nice (- emacs_priority);
1033 #endif
1035 #ifdef subprocesses
1036 /* Close Emacs's descriptors that this process should not have. */
1037 close_process_descs ();
1038 #endif
1039 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
1040 we will lose if we call close_load_descs here. */
1041 #ifndef DOS_NT
1042 close_load_descs ();
1043 #endif
1045 /* Note that use of alloca is always safe here. It's obvious for systems
1046 that do not have true vfork or that have true (stack) alloca.
1047 If using vfork and C_ALLOCA it is safe because that changes
1048 the superior's static variables as if the superior had done alloca
1049 and will be cleaned up in the usual way. */
1051 register char *temp;
1052 register int i;
1054 i = STRING_BYTES (XSTRING (current_dir));
1055 pwd_var = (char *) alloca (i + 6);
1056 temp = pwd_var + 4;
1057 bcopy ("PWD=", pwd_var, 4);
1058 bcopy (XSTRING (current_dir)->data, temp, i);
1059 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
1060 temp[i] = 0;
1062 #ifndef DOS_NT
1063 /* We can't signal an Elisp error here; we're in a vfork. Since
1064 the callers check the current directory before forking, this
1065 should only return an error if the directory's permissions
1066 are changed between the check and this chdir, but we should
1067 at least check. */
1068 if (chdir (temp) < 0)
1069 _exit (errno);
1070 #endif
1072 #ifdef DOS_NT
1073 /* Get past the drive letter, so that d:/ is left alone. */
1074 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1076 temp += 2;
1077 i -= 2;
1079 #endif
1081 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
1082 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
1083 temp[--i] = 0;
1086 /* Set `env' to a vector of the strings in Vprocess_environment. */
1088 register Lisp_Object tem;
1089 register char **new_env;
1090 register int new_length;
1092 new_length = 0;
1093 for (tem = Vprocess_environment;
1094 CONSP (tem) && STRINGP (XCAR (tem));
1095 tem = XCDR (tem))
1096 new_length++;
1098 /* new_length + 2 to include PWD and terminating 0. */
1099 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
1101 /* If we have a PWD envvar, pass one down,
1102 but with corrected value. */
1103 if (getenv ("PWD"))
1104 *new_env++ = pwd_var;
1106 /* Copy the Vprocess_environment strings into new_env. */
1107 for (tem = Vprocess_environment;
1108 CONSP (tem) && STRINGP (XCAR (tem));
1109 tem = XCDR (tem))
1111 char **ep = env;
1112 char *string = (char *) XSTRING (XCAR (tem))->data;
1113 /* See if this string duplicates any string already in the env.
1114 If so, don't put it in.
1115 When an env var has multiple definitions,
1116 we keep the definition that comes first in process-environment. */
1117 for (; ep != new_env; ep++)
1119 char *p = *ep, *q = string;
1120 while (1)
1122 if (*q == 0)
1123 /* The string is malformed; might as well drop it. */
1124 goto duplicate;
1125 if (*q != *p)
1126 break;
1127 if (*q == '=')
1128 goto duplicate;
1129 p++, q++;
1132 *new_env++ = string;
1133 duplicate: ;
1135 *new_env = 0;
1137 #ifdef WINDOWSNT
1138 prepare_standard_handles (in, out, err, handles);
1139 set_process_dir (XSTRING (current_dir)->data);
1140 #else /* not WINDOWSNT */
1141 /* Make sure that in, out, and err are not actually already in
1142 descriptors zero, one, or two; this could happen if Emacs is
1143 started with its standard in, out, or error closed, as might
1144 happen under X. */
1146 int oin = in, oout = out;
1148 /* We have to avoid relocating the same descriptor twice! */
1150 in = relocate_fd (in, 3);
1152 if (out == oin)
1153 out = in;
1154 else
1155 out = relocate_fd (out, 3);
1157 if (err == oin)
1158 err = in;
1159 else if (err == oout)
1160 err = out;
1161 else
1162 err = relocate_fd (err, 3);
1165 #ifndef MSDOS
1166 close (0);
1167 close (1);
1168 close (2);
1170 dup2 (in, 0);
1171 dup2 (out, 1);
1172 dup2 (err, 2);
1173 close (in);
1174 close (out);
1175 close (err);
1176 #endif /* not MSDOS */
1177 #endif /* not WINDOWSNT */
1179 #if defined(USG) && !defined(BSD_PGRPS)
1180 #ifndef SETPGRP_RELEASES_CTTY
1181 setpgrp (); /* No arguments but equivalent in this case */
1182 #endif
1183 #else
1184 setpgrp (pid, pid);
1185 #endif /* USG */
1186 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
1187 EMACS_SET_TTY_PGRP (0, &pid);
1189 #ifdef vipc
1190 something missing here;
1191 #endif /* vipc */
1193 #ifdef MSDOS
1194 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1195 if (pid == -1)
1196 /* An error occurred while trying to run the subprocess. */
1197 report_file_error ("Spawning child process", Qnil);
1198 return pid;
1199 #else /* not MSDOS */
1200 #ifdef WINDOWSNT
1201 /* Spawn the child. (See ntproc.c:Spawnve). */
1202 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1203 reset_standard_handles (in, out, err, handles);
1204 if (cpid == -1)
1205 /* An error occurred while trying to spawn the process. */
1206 report_file_error ("Spawning child process", Qnil);
1207 return cpid;
1208 #else /* not WINDOWSNT */
1209 /* execvp does not accept an environment arg so the only way
1210 to pass this environment is to set environ. Our caller
1211 is responsible for restoring the ambient value of environ. */
1212 environ = env;
1213 execvp (new_argv[0], new_argv);
1215 write (1, "Can't exec program: ", 20);
1216 write (1, new_argv[0], strlen (new_argv[0]));
1217 write (1, "\n", 1);
1218 _exit (1);
1219 #endif /* not WINDOWSNT */
1220 #endif /* not MSDOS */
1223 /* Move the file descriptor FD so that its number is not less than MINFD.
1224 If the file descriptor is moved at all, the original is freed. */
1225 static int
1226 relocate_fd (fd, minfd)
1227 int fd, minfd;
1229 if (fd >= minfd)
1230 return fd;
1231 else
1233 int new = dup (fd);
1234 if (new == -1)
1236 char *message1 = "Error while setting up child: ";
1237 char *errmessage = strerror (errno);
1238 char *message2 = "\n";
1239 write (2, message1, strlen (message1));
1240 write (2, errmessage, strlen (errmessage));
1241 write (2, message2, strlen (message2));
1242 _exit (1);
1244 /* Note that we hold the original FD open while we recurse,
1245 to guarantee we'll get a new FD if we need it. */
1246 new = relocate_fd (new, minfd);
1247 close (fd);
1248 return new;
1252 static int
1253 getenv_internal (var, varlen, value, valuelen)
1254 char *var;
1255 int varlen;
1256 char **value;
1257 int *valuelen;
1259 Lisp_Object scan;
1261 for (scan = Vprocess_environment; CONSP (scan); scan = XCDR (scan))
1263 Lisp_Object entry;
1265 entry = XCAR (scan);
1266 if (STRINGP (entry)
1267 && STRING_BYTES (XSTRING (entry)) > varlen
1268 && XSTRING (entry)->data[varlen] == '='
1269 #ifdef WINDOWSNT
1270 /* NT environment variables are case insensitive. */
1271 && ! strnicmp (XSTRING (entry)->data, var, varlen)
1272 #else /* not WINDOWSNT */
1273 && ! bcmp (XSTRING (entry)->data, var, varlen)
1274 #endif /* not WINDOWSNT */
1277 *value = (char *) XSTRING (entry)->data + (varlen + 1);
1278 *valuelen = STRING_BYTES (XSTRING (entry)) - (varlen + 1);
1279 return 1;
1283 return 0;
1286 DEFUN ("getenv", Fgetenv, Sgetenv, 1, 1, 0,
1287 "Return the value of environment variable VAR, as a string.\n\
1288 VAR should be a string. Value is nil if VAR is undefined in the environment.\n\
1289 This function consults the variable ``process-environment'' for its value.")
1290 (var)
1291 Lisp_Object var;
1293 char *value;
1294 int valuelen;
1296 CHECK_STRING (var, 0);
1297 if (getenv_internal (XSTRING (var)->data, STRING_BYTES (XSTRING (var)),
1298 &value, &valuelen))
1299 return make_string (value, valuelen);
1300 else
1301 return Qnil;
1304 /* A version of getenv that consults process_environment, easily
1305 callable from C. */
1306 char *
1307 egetenv (var)
1308 char *var;
1310 char *value;
1311 int valuelen;
1313 if (getenv_internal (var, strlen (var), &value, &valuelen))
1314 return value;
1315 else
1316 return 0;
1319 #endif /* not VMS */
1321 /* This is run before init_cmdargs. */
1323 void
1324 init_callproc_1 ()
1326 char *data_dir = egetenv ("EMACSDATA");
1327 char *doc_dir = egetenv ("EMACSDOC");
1329 Vdata_directory
1330 = Ffile_name_as_directory (build_string (data_dir ? data_dir
1331 : PATH_DATA));
1332 Vdoc_directory
1333 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
1334 : PATH_DOC));
1336 /* Check the EMACSPATH environment variable, defaulting to the
1337 PATH_EXEC path from epaths.h. */
1338 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1339 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1340 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1343 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1345 void
1346 init_callproc ()
1348 char *data_dir = egetenv ("EMACSDATA");
1350 register char * sh;
1351 Lisp_Object tempdir;
1353 if (!NILP (Vinstallation_directory))
1355 /* Add to the path the lib-src subdir of the installation dir. */
1356 Lisp_Object tem;
1357 tem = Fexpand_file_name (build_string ("lib-src"),
1358 Vinstallation_directory);
1359 #ifndef DOS_NT
1360 /* MSDOS uses wrapped binaries, so don't do this. */
1361 if (NILP (Fmember (tem, Vexec_path)))
1362 Vexec_path = nconc2 (Vexec_path, Fcons (tem, Qnil));
1364 Vexec_directory = Ffile_name_as_directory (tem);
1365 #endif /* not DOS_NT */
1367 /* Maybe use ../etc as well as ../lib-src. */
1368 if (data_dir == 0)
1370 tem = Fexpand_file_name (build_string ("etc"),
1371 Vinstallation_directory);
1372 Vdoc_directory = Ffile_name_as_directory (tem);
1376 /* Look for the files that should be in etc. We don't use
1377 Vinstallation_directory, because these files are never installed
1378 near the executable, and they are never in the build
1379 directory when that's different from the source directory.
1381 Instead, if these files are not in the nominal place, we try the
1382 source directory. */
1383 if (data_dir == 0)
1385 Lisp_Object tem, tem1, newdir;
1387 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1388 tem1 = Ffile_exists_p (tem);
1389 if (NILP (tem1))
1391 newdir = Fexpand_file_name (build_string ("../etc/"),
1392 build_string (PATH_DUMPLOADSEARCH));
1393 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1394 tem1 = Ffile_exists_p (tem);
1395 if (!NILP (tem1))
1396 Vdata_directory = newdir;
1400 #ifndef CANNOT_DUMP
1401 if (initialized)
1402 #endif
1404 tempdir = Fdirectory_file_name (Vexec_directory);
1405 if (access (XSTRING (tempdir)->data, 0) < 0)
1406 dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
1407 Vexec_directory);
1410 tempdir = Fdirectory_file_name (Vdata_directory);
1411 if (access (XSTRING (tempdir)->data, 0) < 0)
1412 dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
1413 Vdata_directory);
1415 #ifdef VMS
1416 Vshell_file_name = build_string ("*dcl*");
1417 #else
1418 sh = (char *) getenv ("SHELL");
1419 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1420 #endif
1422 #ifdef VMS
1423 Vtemp_file_name_pattern = build_string ("tmp:emacsXXXXXX.");
1424 #else
1425 if (getenv ("TMPDIR"))
1427 char *dir = getenv ("TMPDIR");
1428 Vtemp_file_name_pattern
1429 = Fexpand_file_name (build_string ("emacsXXXXXX"),
1430 build_string (dir));
1432 else
1433 Vtemp_file_name_pattern = build_string ("/tmp/emacsXXXXXX");
1434 #endif
1437 void
1438 set_process_environment ()
1440 register char **envp;
1442 Vprocess_environment = Qnil;
1443 #ifndef CANNOT_DUMP
1444 if (initialized)
1445 #endif
1446 for (envp = environ; *envp; envp++)
1447 Vprocess_environment = Fcons (build_string (*envp),
1448 Vprocess_environment);
1451 void
1452 syms_of_callproc ()
1454 #ifdef DOS_NT
1455 Qbuffer_file_type = intern ("buffer-file-type");
1456 staticpro (&Qbuffer_file_type);
1457 #endif /* DOS_NT */
1459 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
1460 "*File name to load inferior shells from.\n\
1461 Initialized from the SHELL environment variable.");
1463 DEFVAR_LISP ("exec-path", &Vexec_path,
1464 "*List of directories to search programs to run in subprocesses.\n\
1465 Each element is a string (directory name) or nil (try default directory).");
1467 DEFVAR_LISP ("exec-directory", &Vexec_directory,
1468 "Directory for executables for Emacs to invoke.\n\
1469 More generally, this includes any architecture-dependent files\n\
1470 that are built and installed from the Emacs distribution.");
1472 DEFVAR_LISP ("data-directory", &Vdata_directory,
1473 "Directory of machine-independent files that come with GNU Emacs.\n\
1474 These are files intended for Emacs to use while it runs.");
1476 DEFVAR_LISP ("doc-directory", &Vdoc_directory,
1477 "Directory containing the DOC file that comes with GNU Emacs.\n\
1478 This is usually the same as data-directory.");
1480 DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
1481 "For internal use by the build procedure only.\n\
1482 This is the name of the directory in which the build procedure installed\n\
1483 Emacs's info files; the default value for Info-default-directory-list\n\
1484 includes this.");
1485 Vconfigure_info_directory = build_string (PATH_INFO);
1487 DEFVAR_LISP ("temp-file-name-pattern", &Vtemp_file_name_pattern,
1488 "Pattern for making names for temporary files.\n\
1489 This is used by `call-process-region'.");
1490 /* This variable is initialized in init_callproc. */
1492 DEFVAR_LISP ("process-environment", &Vprocess_environment,
1493 "List of environment variables for subprocesses to inherit.\n\
1494 Each element should be a string of the form ENVVARNAME=VALUE.\n\
1495 The environment which Emacs inherits is placed in this variable\n\
1496 when Emacs starts.");
1498 #ifndef VMS
1499 defsubr (&Scall_process);
1500 defsubr (&Sgetenv);
1501 #endif
1502 defsubr (&Scall_process_region);