various fixes and gratuitous movements.
[bpt/emacs.git] / src / callproc.c
CommitLineData
80856e74 1/* Synchronous subprocess invocation for GNU Emacs.
68c45bf0 2 Copyright (C) 1985, 86,87,88,93,94,95, 1999 Free Software Foundation, Inc.
80856e74
JB
3
4This file is part of GNU Emacs.
5
6GNU Emacs is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
826c56ac 8the Free Software Foundation; either version 2, or (at your option)
80856e74
JB
9any later version.
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Emacs; see the file COPYING. If not, write to
3b7ad313
EN
18the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19Boston, MA 02111-1307, USA. */
80856e74
JB
20
21
68c45bf0 22#include <config.h>
80856e74 23#include <signal.h>
e576cab4 24#include <errno.h>
565620a5 25#include <stdio.h>
80856e74 26
426b37ae 27extern int errno;
426b37ae 28
80856e74
JB
29/* Define SIGCHLD as an alias for SIGCLD. */
30
31#if !defined (SIGCHLD) && defined (SIGCLD)
32#define SIGCHLD SIGCLD
33#endif /* SIGCLD */
34
35#include <sys/types.h>
88a64fef 36
3cbd6585
GM
37#ifdef HAVE_UNISTD_H
38#include <unistd.h>
39#endif
40
80856e74
JB
41#include <sys/file.h>
42#ifdef USG5
472e83fe 43#define INCLUDED_FCNTL
80856e74
JB
44#include <fcntl.h>
45#endif
46
bad95d8f
RS
47#ifdef WINDOWSNT
48#define NOMINMAX
49#include <windows.h>
50#include <stdlib.h> /* for proper declaration of environ */
51#include <fcntl.h>
489f9371 52#include "w32.h"
bad95d8f
RS
53#define _P_NOWAIT 1 /* from process.h */
54#endif
55
7e6c2178 56#ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
472e83fe 57#define INCLUDED_FCNTL
7e6c2178
RS
58#include <fcntl.h>
59#include <sys/stat.h>
60#include <sys/param.h>
61#include <errno.h>
62#endif /* MSDOS */
63
80856e74
JB
64#ifndef O_RDONLY
65#define O_RDONLY 0
66#endif
67
68#ifndef O_WRONLY
69#define O_WRONLY 1
70#endif
71
72#include "lisp.h"
73#include "commands.h"
74#include "buffer.h"
32d08644 75#include "charset.h"
edf496dd 76#include "ccl.h"
32d08644 77#include "coding.h"
57bda87a 78#include <epaths.h>
80856e74 79#include "process.h"
d177f194 80#include "syssignal.h"
a129418f 81#include "systty.h"
80856e74 82
5f027cea
EZ
83#ifdef MSDOS
84#include "msdos.h"
85#endif
86
80856e74
JB
87#ifdef VMS
88extern noshare char **environ;
89#else
90extern char **environ;
91#endif
92
93#define max(a, b) ((a) > (b) ? (a) : (b))
94
35a2f4b8 95Lisp_Object Vexec_path, Vexec_directory, Vdata_directory, Vdoc_directory;
ed61592a 96Lisp_Object Vconfigure_info_directory;
8abd035b 97Lisp_Object Vtemp_file_name_pattern;
80856e74
JB
98
99Lisp_Object Vshell_file_name;
100
80856e74 101Lisp_Object Vprocess_environment;
80856e74 102
bad95d8f 103#ifdef DOS_NT
093650fe 104Lisp_Object Qbuffer_file_type;
bad95d8f 105#endif /* DOS_NT */
093650fe 106
80856e74
JB
107/* True iff we are about to fork off a synchronous process or if we
108 are waiting for it. */
109int synch_process_alive;
110
111/* Nonzero => this is a string explaining death of synchronous subprocess. */
112char *synch_process_death;
113
114/* If synch_process_death is zero,
115 this is exit code of synchronous subprocess. */
116int synch_process_retcode;
8de15d69
RS
117
118extern Lisp_Object Vdoc_file_name;
89e1ec1d 119
8d024345 120extern Lisp_Object Vfile_name_coding_system, Vdefault_file_name_coding_system;
80856e74 121\f
37d54121
RS
122/* Clean up when exiting Fcall_process.
123 On MSDOS, delete the temporary file on any kind of termination.
124 On Unix, kill the process and any children on termination by signal. */
125
126/* Nonzero if this is termination due to exit. */
127static int call_process_exited;
128
80856e74
JB
129#ifndef VMS /* VMS version is in vmsproc.c. */
130
d177f194
JB
131static Lisp_Object
132call_process_kill (fdpid)
133 Lisp_Object fdpid;
134{
68c45bf0 135 emacs_close (XFASTINT (Fcar (fdpid)));
d177f194
JB
136 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
137 synch_process_alive = 0;
138 return Qnil;
139}
140
80856e74
JB
141Lisp_Object
142call_process_cleanup (fdpid)
143 Lisp_Object fdpid;
144{
052062e0 145#if defined (MSDOS) || defined (macintosh)
7e6c2178 146 /* for MSDOS fdpid is really (fd . tempfile) */
c1350752
KH
147 register Lisp_Object file;
148 file = Fcdr (fdpid);
68c45bf0 149 emacs_close (XFASTINT (Fcar (fdpid)));
7e6c2178
RS
150 if (strcmp (XSTRING (file)-> data, NULL_DEVICE) != 0)
151 unlink (XSTRING (file)->data);
052062e0 152#else /* not MSDOS and not macintosh */
d177f194
JB
153 register int pid = XFASTINT (Fcdr (fdpid));
154
37d54121 155 if (call_process_exited)
6b6e798b 156 {
68c45bf0 157 emacs_close (XFASTINT (Fcar (fdpid)));
6b6e798b
RS
158 return Qnil;
159 }
37d54121 160
d177f194
JB
161 if (EMACS_KILLPG (pid, SIGINT) == 0)
162 {
163 int count = specpdl_ptr - specpdl;
164 record_unwind_protect (call_process_kill, fdpid);
165 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
166 immediate_quit = 1;
167 QUIT;
168 wait_for_termination (pid);
169 immediate_quit = 0;
170 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
171 message1 ("Waiting for process to die...done");
172 }
80856e74 173 synch_process_alive = 0;
68c45bf0 174 emacs_close (XFASTINT (Fcar (fdpid)));
7e6c2178 175#endif /* not MSDOS */
80856e74
JB
176 return Qnil;
177}
178
179DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
180 "Call PROGRAM synchronously in separate process.\n\
edf496dd 181The remaining arguments are optional.\n\
80856e74
JB
182The program's input comes from file INFILE (nil means `/dev/null').\n\
183Insert output in BUFFER before point; t means current buffer;\n\
184 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
39eaa782
RS
185BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
186REAL-BUFFER says what to do with standard output, as above,\n\
187while STDERR-FILE says what to do with standard error in the child.\n\
188STDERR-FILE may be nil (discard standard error output),\n\
189t (mix it with ordinary output), or a file name string.\n\
190\n\
80856e74
JB
191Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
192Remaining arguments are strings passed as command arguments to PROGRAM.\n\
39eaa782
RS
193\n\
194If BUFFER is 0, `call-process' returns immediately with value nil.\n\
195Otherwise it waits for PROGRAM to terminate\n\
e576cab4 196and returns a numeric exit status or a signal description string.\n\
d177f194 197If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
80856e74
JB
198 (nargs, args)
199 int nargs;
200 register Lisp_Object *args;
201{
58616e67 202 Lisp_Object infile, buffer, current_dir, display, path;
80856e74
JB
203 int fd[2];
204 int filefd;
205 register int pid;
6e3bfbb2
RS
206 char buf[16384];
207 char *bufptr = buf;
208 int bufsize = 16384;
80856e74 209 int count = specpdl_ptr - specpdl;
2d607244 210
80856e74
JB
211 register unsigned char **new_argv
212 = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
213 struct buffer *old = current_buffer;
39eaa782
RS
214 /* File to use for stderr in the child.
215 t means use same as standard output. */
216 Lisp_Object error_file;
7e6c2178
RS
217#ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
218 char *outf, *tempfile;
219 int outfilefd;
220#endif
052062e0
RS
221#ifdef macintosh
222 char *tempfile;
223 int outfilefd;
224#endif
80856e74
JB
225#if 0
226 int mask;
227#endif
32d08644
KH
228 struct coding_system process_coding; /* coding-system of process output */
229 struct coding_system argument_coding; /* coding-system of arguments */
09494912
RS
230 /* Set to the return value of Ffind_operation_coding_system. */
231 Lisp_Object coding_systems;
232
233 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
234 coding_systems = Qt;
32d08644 235
80856e74
JB
236 CHECK_STRING (args[0], 0);
237
39eaa782
RS
238 error_file = Qt;
239
7e6c2178
RS
240#ifndef subprocesses
241 /* Without asynchronous processes we cannot have BUFFER == 0. */
3ffde7d6 242 if (nargs >= 3
09ffb8b5 243 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
7e6c2178
RS
244 error ("Operating system cannot handle asynchronous subprocesses");
245#endif /* subprocesses */
246
09494912 247 /* Decide the coding-system for giving arguments. */
32d08644
KH
248 {
249 Lisp_Object val, *args2;
32d08644
KH
250 int i;
251
252 /* If arguments are supplied, we may have to encode them. */
253 if (nargs >= 5)
254 {
30d57b8e
RS
255 int must_encode = 0;
256
e7c1c20e
RS
257 for (i = 4; i < nargs; i++)
258 CHECK_STRING (args[i], i);
259
a2286b5c 260 for (i = 4; i < nargs; i++)
30d57b8e
RS
261 if (STRING_MULTIBYTE (args[i]))
262 must_encode = 1;
263
beacaab3
KH
264 if (!NILP (Vcoding_system_for_write))
265 val = Vcoding_system_for_write;
30d57b8e 266 else if (! must_encode)
beacaab3
KH
267 val = Qnil;
268 else
32d08644
KH
269 {
270 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
271 args2[0] = Qcall_process;
272 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
08ee4e87 273 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
776b95cb 274 if (CONSP (coding_systems))
70949dac 275 val = XCDR (coding_systems);
776b95cb 276 else if (CONSP (Vdefault_process_coding_system))
70949dac 277 val = XCDR (Vdefault_process_coding_system);
beacaab3
KH
278 else
279 val = Qnil;
32d08644
KH
280 }
281 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
282 }
32d08644
KH
283 }
284
e576cab4
JB
285 if (nargs >= 2 && ! NILP (args[1]))
286 {
287 infile = Fexpand_file_name (args[1], current_buffer->directory);
288 CHECK_STRING (infile, 1);
289 }
80856e74 290 else
5437e9f9 291 infile = build_string (NULL_DEVICE);
80856e74 292
e576cab4
JB
293 if (nargs >= 3)
294 {
39eaa782
RS
295 buffer = args[2];
296
297 /* If BUFFER is a list, its meaning is
298 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
299 if (CONSP (buffer))
300 {
70949dac 301 if (CONSP (XCDR (buffer)))
45be8a1e 302 {
a9d4f28a 303 Lisp_Object stderr_file;
70949dac 304 stderr_file = XCAR (XCDR (buffer));
45be8a1e
RS
305
306 if (NILP (stderr_file) || EQ (Qt, stderr_file))
307 error_file = stderr_file;
308 else
309 error_file = Fexpand_file_name (stderr_file, Qnil);
310 }
311
70949dac 312 buffer = XCAR (buffer);
39eaa782 313 }
044512ed 314
39eaa782
RS
315 if (!(EQ (buffer, Qnil)
316 || EQ (buffer, Qt)
3ffde7d6 317 || INTEGERP (buffer)))
e576cab4 318 {
39eaa782
RS
319 Lisp_Object spec_buffer;
320 spec_buffer = buffer;
50fe359b 321 buffer = Fget_buffer_create (buffer);
39eaa782
RS
322 /* Mention the buffer name for a better error message. */
323 if (NILP (buffer))
324 CHECK_BUFFER (spec_buffer, 2);
e576cab4
JB
325 CHECK_BUFFER (buffer, 2);
326 }
327 }
328 else
329 buffer = Qnil;
80856e74 330
58616e67
JB
331 /* Make sure that the child will be able to chdir to the current
332 buffer's current directory, or its unhandled equivalent. We
333 can't just have the child check for an error when it does the
334 chdir, since it's in a vfork.
335
336 We have to GCPRO around this because Fexpand_file_name,
337 Funhandled_file_name_directory, and Ffile_accessible_directory_p
338 might call a file name handling function. The argument list is
339 protected by the caller, so all we really have to worry about is
340 buffer. */
341 {
342 struct gcpro gcpro1, gcpro2, gcpro3;
343
344 current_dir = current_buffer->directory;
345
346 GCPRO3 (infile, buffer, current_dir);
347
c52b0b34
KH
348 current_dir
349 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
350 Qnil);
58616e67
JB
351 if (NILP (Ffile_accessible_directory_p (current_dir)))
352 report_file_error ("Setting current directory",
353 Fcons (current_buffer->directory, Qnil));
354
355 UNGCPRO;
356 }
357
e576cab4 358 display = nargs >= 4 ? args[3] : Qnil;
80856e74 359
68c45bf0 360 filefd = emacs_open (XSTRING (infile)->data, O_RDONLY, 0);
80856e74
JB
361 if (filefd < 0)
362 {
e576cab4 363 report_file_error ("Opening process input file", Fcons (infile, Qnil));
80856e74
JB
364 }
365 /* Search for program; barf if not found. */
c52b0b34
KH
366 {
367 struct gcpro gcpro1;
368
369 GCPRO1 (current_dir);
370 openp (Vexec_path, args[0], EXEC_SUFFIXES, &path, 1);
371 UNGCPRO;
372 }
012c6fcb 373 if (NILP (path))
80856e74 374 {
68c45bf0 375 emacs_close (filefd);
80856e74
JB
376 report_file_error ("Searching for program", Fcons (args[0], Qnil));
377 }
378 new_argv[0] = XSTRING (path)->data;
c364e618
KH
379 if (nargs > 4)
380 {
381 register int i;
382
c364e618
KH
383 if (! CODING_REQUIRE_ENCODING (&argument_coding))
384 {
385 for (i = 4; i < nargs; i++)
386 new_argv[i - 3] = XSTRING (args[i])->data;
387 }
388 else
389 {
390 /* We must encode the arguments. */
391 struct gcpro gcpro1, gcpro2, gcpro3;
392
393 GCPRO3 (infile, buffer, current_dir);
394 for (i = 4; i < nargs; i++)
395 {
396 int size = encoding_buffer_size (&argument_coding,
fc932ac6 397 STRING_BYTES (XSTRING (args[i])));
c364e618 398 unsigned char *dummy1 = (unsigned char *) alloca (size);
c364e618
KH
399
400 /* The Irix 4.0 compiler barfs if we eliminate dummy. */
401 new_argv[i - 3] = dummy1;
edf496dd 402 argument_coding.mode |= CODING_MODE_LAST_BLOCK;
321fecde
KH
403 encode_coding (&argument_coding,
404 XSTRING (args[i])->data,
405 new_argv[i - 3],
fc932ac6 406 STRING_BYTES (XSTRING (args[i])),
321fecde
KH
407 size);
408 new_argv[i - 3][argument_coding.produced] = 0;
edf496dd
KH
409 /* We have to initialize CCL program status again. */
410 if (argument_coding.type == coding_type_ccl)
411 setup_ccl_program (&(argument_coding.spec.ccl.encoder), Qnil);
c364e618
KH
412 }
413 UNGCPRO;
414 }
db54baaa 415 new_argv[nargs - 3] = 0;
c364e618 416 }
db54baaa
KH
417 else
418 new_argv[1] = 0;
80856e74 419
7e6c2178 420#ifdef MSDOS /* MW, July 1993 */
8a52365c 421 if ((outf = egetenv ("TMPDIR")))
7e6c2178
RS
422 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
423 else
424 {
425 tempfile = alloca (20);
426 *tempfile = '\0';
427 }
428 dostounix_filename (tempfile);
429 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
430 strcat (tempfile, "/");
431 strcat (tempfile, "detmp.XXX");
432 mktemp (tempfile);
433
434 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
435 if (outfilefd < 0)
436 {
68c45bf0 437 emacs_close (filefd);
6f89d28a
MB
438 report_file_error ("Opening process output file",
439 Fcons (build_string (tempfile), Qnil));
7e6c2178 440 }
6f89d28a 441 fd[0] = filefd;
2610078a 442 fd[1] = outfilefd;
6f89d28a 443#endif /* MSDOS */
7e6c2178 444
052062e0
RS
445#ifdef macintosh
446 /* Since we don't have pipes on the Mac, create a temporary file to
447 hold the output of the subprocess. */
448 tempfile = (char *) alloca (STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
449 bcopy (XSTRING (Vtemp_file_name_pattern)->data, tempfile,
450 STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
451
452 mktemp (tempfile);
453
454 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
455 if (outfilefd < 0)
456 {
457 close (filefd);
458 report_file_error ("Opening process output file",
459 Fcons (build_string (tempfile), Qnil));
460 }
461 fd[0] = filefd;
462 fd[1] = outfilefd;
463#endif /* macintosh */
464
d50d3dc8 465 if (INTEGERP (buffer))
68c45bf0 466 fd[1] = emacs_open (NULL_DEVICE, O_WRONLY, 0), fd[0] = -1;
80856e74
JB
467 else
468 {
7e6c2178 469#ifndef MSDOS
052062e0 470#ifndef macintosh
80856e74 471 pipe (fd);
7e6c2178 472#endif
052062e0 473#endif
80856e74
JB
474#if 0
475 /* Replaced by close_process_descs */
476 set_exclusive_use (fd[0]);
477#endif
478 }
479
480 {
481 /* child_setup must clobber environ in systems with true vfork.
482 Protect it from permanent change. */
483 register char **save_environ = environ;
484 register int fd1 = fd[1];
39eaa782 485 int fd_error = fd1;
80856e74
JB
486
487#if 0 /* Some systems don't have sigblock. */
e065a56e 488 mask = sigblock (sigmask (SIGCHLD));
80856e74
JB
489#endif
490
491 /* Record that we're about to create a synchronous process. */
492 synch_process_alive = 1;
493
5c03767e
RS
494 /* These vars record information from process termination.
495 Clear them now before process can possibly terminate,
496 to avoid timing error if process terminates soon. */
497 synch_process_death = 0;
498 synch_process_retcode = 0;
499
39eaa782 500 if (NILP (error_file))
68c45bf0 501 fd_error = emacs_open (NULL_DEVICE, O_WRONLY, 0);
39eaa782
RS
502 else if (STRINGP (error_file))
503 {
504#ifdef DOS_NT
68c45bf0
PE
505 fd_error = emacs_open (XSTRING (error_file)->data,
506 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
507 S_IREAD | S_IWRITE);
39eaa782
RS
508#else /* not DOS_NT */
509 fd_error = creat (XSTRING (error_file)->data, 0666);
510#endif /* not DOS_NT */
511 }
512
513 if (fd_error < 0)
514 {
68c45bf0 515 emacs_close (filefd);
6f89d28a 516 if (fd[0] != filefd)
68c45bf0 517 emacs_close (fd[0]);
39eaa782 518 if (fd1 >= 0)
68c45bf0 519 emacs_close (fd1);
6f89d28a
MB
520#ifdef MSDOS
521 unlink (tempfile);
522#endif
523 report_file_error ("Cannot redirect stderr",
524 Fcons ((NILP (error_file)
525 ? build_string (NULL_DEVICE) : error_file),
526 Qnil));
39eaa782 527 }
89e1ec1d 528
8d024345 529 current_dir = ENCODE_FILE (current_dir);
89e1ec1d 530
052062e0
RS
531#ifdef macintosh
532 {
533 /* Call run_mac_command in sysdep.c here directly instead of doing
534 a child_setup as for MSDOS and other platforms. Note that this
535 code does not handle passing the environment to the synchronous
536 Mac subprocess. */
537 char *infn, *outfn, *errfn, *currdn;
538
539 /* close these files so subprocess can write to them */
540 close (outfilefd);
541 if (fd_error != outfilefd)
542 close (fd_error);
543 fd1 = -1; /* No harm in closing that one! */
544
545 infn = XSTRING (infile)->data;
546 outfn = tempfile;
547 if (NILP (error_file))
548 errfn = NULL_DEVICE;
549 else if (EQ (Qt, error_file))
550 errfn = outfn;
551 else
552 errfn = XSTRING (error_file)->data;
553 currdn = XSTRING (current_dir)->data;
554 pid = run_mac_command (new_argv, currdn, infn, outfn, errfn);
555
556 /* Record that the synchronous process exited and note its
557 termination status. */
558 synch_process_alive = 0;
559 synch_process_retcode = pid;
560 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
68c45bf0 561 {
ca9c0567 562 synchronize_system_messages_locale ();
68c45bf0
PE
563 synch_process_death = strerror (errno);
564 }
052062e0
RS
565
566 /* Since CRLF is converted to LF within `decode_coding', we can
567 always open a file with binary mode. */
568 fd[0] = open (tempfile, O_BINARY);
569 if (fd[0] < 0)
570 {
571 unlink (tempfile);
572 close (filefd);
573 report_file_error ("Cannot re-open temporary file", Qnil);
574 }
575 }
576#else /* not macintosh */
2610078a 577#ifdef MSDOS /* MW, July 1993 */
c17c4250 578 /* Note that on MSDOS `child_setup' actually returns the child process
2610078a
KH
579 exit status, not its PID, so we assign it to `synch_process_retcode'
580 below. */
c17c4250
EZ
581 pid = child_setup (filefd, outfilefd, fd_error, (char **) new_argv,
582 0, current_dir);
39eaa782 583
2610078a
KH
584 /* Record that the synchronous process exited and note its
585 termination status. */
586 synch_process_alive = 0;
587 synch_process_retcode = pid;
588 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
68c45bf0 589 {
ca9c0567 590 synchronize_system_messages_locale ();
68c45bf0
PE
591 synch_process_death = strerror (errno);
592 }
2610078a 593
68c45bf0 594 emacs_close (outfilefd);
2610078a 595 if (fd_error != outfilefd)
68c45bf0 596 emacs_close (fd_error);
2610078a 597 fd1 = -1; /* No harm in closing that one! */
32d08644
KH
598 /* Since CRLF is converted to LF within `decode_coding', we can
599 always open a file with binary mode. */
68c45bf0 600 fd[0] = emacs_open (tempfile, O_RDONLY | O_BINARY, 0);
2610078a
KH
601 if (fd[0] < 0)
602 {
603 unlink (tempfile);
68c45bf0 604 emacs_close (filefd);
2610078a
KH
605 report_file_error ("Cannot re-open temporary file", Qnil);
606 }
607#else /* not MSDOS */
bad95d8f 608#ifdef WINDOWSNT
2d607244
RS
609 pid = child_setup (filefd, fd1, fd_error, (char **) new_argv,
610 0, current_dir);
bad95d8f 611#else /* not WINDOWSNT */
80856e74
JB
612 pid = vfork ();
613
614 if (pid == 0)
615 {
616 if (fd[0] >= 0)
68c45bf0 617 emacs_close (fd[0]);
1e7963c7
RS
618#ifdef HAVE_SETSID
619 setsid ();
620#endif
621#if defined (USG) && !defined (BSD_PGRPS)
80856e74
JB
622 setpgrp ();
623#else
624 setpgrp (pid, pid);
625#endif /* USG */
2d607244
RS
626 child_setup (filefd, fd1, fd_error, (char **) new_argv,
627 0, current_dir);
80856e74 628 }
bad95d8f 629#endif /* not WINDOWSNT */
cd5f8f60
RS
630
631 /* The MSDOS case did this already. */
632 if (fd_error >= 0)
68c45bf0 633 emacs_close (fd_error);
2610078a 634#endif /* not MSDOS */
052062e0 635#endif /* not macintosh */
80856e74 636
80856e74
JB
637 environ = save_environ;
638
6b6e798b
RS
639 /* Close most of our fd's, but not fd[0]
640 since we will use that to read input from. */
68c45bf0 641 emacs_close (filefd);
799abb26 642 if (fd1 >= 0 && fd1 != fd_error)
68c45bf0 643 emacs_close (fd1);
80856e74
JB
644 }
645
646 if (pid < 0)
647 {
6b6e798b 648 if (fd[0] >= 0)
68c45bf0 649 emacs_close (fd[0]);
80856e74
JB
650 report_file_error ("Doing vfork", Qnil);
651 }
652
d50d3dc8 653 if (INTEGERP (buffer))
80856e74 654 {
6b6e798b 655 if (fd[0] >= 0)
68c45bf0 656 emacs_close (fd[0]);
80856e74 657#ifndef subprocesses
e576cab4
JB
658 /* If Emacs has been built with asynchronous subprocess support,
659 we don't need to do this, I think because it will then have
660 the facilities for handling SIGCHLD. */
80856e74
JB
661 wait_without_blocking ();
662#endif /* subprocesses */
80856e74
JB
663 return Qnil;
664 }
665
6b6e798b 666 /* Enable sending signal if user quits below. */
37d54121
RS
667 call_process_exited = 0;
668
052062e0 669#if defined(MSDOS) || defined(macintosh)
7e6c2178
RS
670 /* MSDOS needs different cleanup information. */
671 record_unwind_protect (call_process_cleanup,
672 Fcons (make_number (fd[0]), build_string (tempfile)));
673#else
80856e74
JB
674 record_unwind_protect (call_process_cleanup,
675 Fcons (make_number (fd[0]), make_number (pid)));
052062e0 676#endif /* not MSDOS and not macintosh */
80856e74
JB
677
678
d50d3dc8 679 if (BUFFERP (buffer))
80856e74
JB
680 Fset_buffer (buffer);
681
09494912
RS
682 if (NILP (buffer))
683 {
684 /* If BUFFER is nil, we must read process output once and then
685 discard it, so setup coding system but with nil. */
686 setup_coding_system (Qnil, &process_coding);
687 }
688 else
689 {
690 Lisp_Object val, *args2;
691
692 val = Qnil;
693 if (!NILP (Vcoding_system_for_read))
694 val = Vcoding_system_for_read;
695 else
696 {
697 if (EQ (coding_systems, Qt))
698 {
699 int i;
700
701 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
702 args2[0] = Qcall_process;
703 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
704 coding_systems
705 = Ffind_operation_coding_system (nargs + 1, args2);
706 }
707 if (CONSP (coding_systems))
70949dac 708 val = XCAR (coding_systems);
09494912 709 else if (CONSP (Vdefault_process_coding_system))
70949dac 710 val = XCAR (Vdefault_process_coding_system);
09494912
RS
711 else
712 val = Qnil;
713 }
714 setup_coding_system (Fcheck_coding_system (val), &process_coding);
715 /* In unibyte mode, character code conversion should not take
716 place but EOL conversion should. So, setup raw-text or one
717 of the subsidiary according to the information just setup. */
718 if (NILP (current_buffer->enable_multibyte_characters)
719 && !NILP (val))
720 setup_raw_text_coding_system (&process_coding);
721 }
722
80856e74
JB
723 immediate_quit = 1;
724 QUIT;
725
726 {
727 register int nread;
0ad477db 728 int first = 1;
6e3bfbb2 729 int total_read = 0;
321fecde 730 int carryover = 0;
7a7ab107 731 int display_on_the_fly = !NILP (display) && INTERACTIVE;
05b44e90
KH
732 struct coding_system saved_coding;
733
734 saved_coding = process_coding;
80856e74 735
60558b19 736 while (1)
80856e74 737 {
60558b19
RS
738 /* Repeatedly read until we've filled as much as possible
739 of the buffer size we have. But don't read
8e6208c5 740 less than 1024--save that for the next bufferful. */
321fecde 741 nread = carryover;
60558b19 742 while (nread < bufsize - 1024)
00fb3e95 743 {
68c45bf0
PE
744 int this_read = emacs_read (fd[0], bufptr + nread,
745 bufsize - nread);
60558b19
RS
746
747 if (this_read < 0)
748 goto give_up;
749
750 if (this_read == 0)
7a7ab107
KH
751 {
752 process_coding.mode |= CODING_MODE_LAST_BLOCK;
753 break;
754 }
60558b19
RS
755
756 nread += this_read;
7a7ab107 757 total_read += this_read;
60558b19 758
7a7ab107
KH
759 if (display_on_the_fly)
760 break;
761 }
60558b19
RS
762
763 /* Now NREAD is the total amount of data in the buffer. */
80856e74 764 immediate_quit = 0;
6e3bfbb2 765
012c6fcb 766 if (!NILP (buffer))
32d08644
KH
767 {
768 if (process_coding.type == coding_type_no_conversion)
769 insert (bufptr, nread);
770 else
771 { /* We have to decode the input. */
321fecde 772 int size = decoding_buffer_size (&process_coding, nread);
a871dd58 773 char *decoding_buf = (char *) xmalloc (size);
32d08644 774
321fecde
KH
775 decode_coding (&process_coding, bufptr, decoding_buf,
776 nread, size);
7a7ab107
KH
777 if (display_on_the_fly
778 && saved_coding.type == coding_type_undecided
779 && process_coding.type != coding_type_undecided)
780 {
781 /* We have detected some coding system. But,
782 there's a possibility that the detection was
783 done by insufficient data. So, we give up
784 displaying on the fly. */
a871dd58 785 xfree (decoding_buf);
7a7ab107
KH
786 display_on_the_fly = 0;
787 process_coding = saved_coding;
788 carryover = nread;
789 continue;
790 }
321fecde
KH
791 if (process_coding.produced > 0)
792 insert (decoding_buf, process_coding.produced);
a871dd58 793 xfree (decoding_buf);
11218c68 794 carryover = nread - process_coding.consumed;
321fecde
KH
795 if (carryover > 0)
796 {
797 /* As CARRYOVER should not be that large, we had
798 better avoid overhead of bcopy. */
799 char *p = bufptr + process_coding.consumed;
800 char *pend = p + carryover;
801 char *dst = bufptr;
802
803 while (p < pend) *dst++ = *p++;
804 }
32d08644
KH
805 }
806 }
321fecde
KH
807 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
808 {
809 if (carryover > 0)
810 insert (bufptr, carryover);
811 break;
812 }
6e3bfbb2
RS
813
814 /* Make the buffer bigger as we continue to read more data,
815 but not past 64k. */
816 if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
817 {
818 bufsize *= 2;
819 bufptr = (char *) alloca (bufsize);
820 }
821
012c6fcb 822 if (!NILP (display) && INTERACTIVE)
0ad477db
RS
823 {
824 if (first)
825 prepare_menu_bars ();
826 first = 0;
827 redisplay_preserve_echo_area ();
828 }
80856e74
JB
829 immediate_quit = 1;
830 QUIT;
831 }
60558b19 832 give_up: ;
80856e74 833
bbd29cfe
KH
834 Vlast_coding_system_used = process_coding.symbol;
835
3b440bb5
EZ
836 /* If the caller required, let the buffer inherit the
837 coding-system used to decode the process output. */
838 if (inherit_process_coding_system)
839 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
840 make_number (total_read));
841 }
842
80856e74
JB
843 /* Wait for it to terminate, unless it already has. */
844 wait_for_termination (pid);
845
846 immediate_quit = 0;
847
848 set_buffer_internal (old);
849
37d54121
RS
850 /* Don't kill any children that the subprocess may have left behind
851 when exiting. */
852 call_process_exited = 1;
853
80856e74
JB
854 unbind_to (count, Qnil);
855
80856e74 856 if (synch_process_death)
68c45bf0
PE
857 return code_convert_string_norecord (build_string (synch_process_death),
858 Vlocale_coding_system, 0);
80856e74
JB
859 return make_number (synch_process_retcode);
860}
861#endif
862\f
9fefd2ba 863static Lisp_Object
80856e74
JB
864delete_temp_file (name)
865 Lisp_Object name;
866{
2e3dc201 867 /* Use Fdelete_file (indirectly) because that runs a file name handler.
59750d69 868 We did that when writing the file, so we should do so when deleting. */
2e3dc201 869 internal_delete_file (name);
80856e74
JB
870}
871
872DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
873 3, MANY, 0,
874 "Send text from START to END to a synchronous process running PROGRAM.\n\
edf496dd 875The remaining arguments are optional.\n\
80856e74 876Delete the text if fourth arg DELETE is non-nil.\n\
39eaa782 877\n\
80856e74
JB
878Insert output in BUFFER before point; t means current buffer;\n\
879 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
39eaa782
RS
880BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
881REAL-BUFFER says what to do with standard output, as above,\n\
882while STDERR-FILE says what to do with standard error in the child.\n\
883STDERR-FILE may be nil (discard standard error output),\n\
884t (mix it with ordinary output), or a file name string.\n\
885\n\
80856e74
JB
886Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
887Remaining args are passed to PROGRAM at startup as command args.\n\
39eaa782
RS
888\n\
889If BUFFER is nil, `call-process-region' returns immediately with value nil.\n\
890Otherwise it waits for PROGRAM to terminate\n\
e576cab4 891and returns a numeric exit status or a signal description string.\n\
d177f194 892If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
80856e74
JB
893 (nargs, args)
894 int nargs;
895 register Lisp_Object *args;
896{
39323a7e
KH
897 struct gcpro gcpro1;
898 Lisp_Object filename_string;
899 register Lisp_Object start, end;
d3e81d0a 900 int count = specpdl_ptr - specpdl;
08ee4e87 901 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
09494912 902 Lisp_Object coding_systems;
32d08644
KH
903 Lisp_Object val, *args2;
904 int i;
bad95d8f 905#ifdef DOS_NT
7e6c2178 906 char *tempfile;
7e6c2178
RS
907 char *outf = '\0';
908
8a52365c
EZ
909 if ((outf = egetenv ("TMPDIR"))
910 || (outf = egetenv ("TMP"))
911 || (outf = egetenv ("TEMP")))
7e6c2178
RS
912 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
913 else
914 {
915 tempfile = alloca (20);
916 *tempfile = '\0';
917 }
0774fcf8 918 if (!IS_DIRECTORY_SEP (tempfile[strlen (tempfile) - 1]))
7e6c2178 919 strcat (tempfile, "/");
5711b547
RS
920 if ('/' == DIRECTORY_SEP)
921 dostounix_filename (tempfile);
922 else
923 unixtodos_filename (tempfile);
0774fcf8
RS
924#ifdef WINDOWSNT
925 strcat (tempfile, "emXXXXXX");
926#else
7e6c2178 927 strcat (tempfile, "detmp.XXX");
0774fcf8 928#endif
bad95d8f 929#else /* not DOS_NT */
fc932ac6 930 char *tempfile = (char *) alloca (STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
8abd035b 931 bcopy (XSTRING (Vtemp_file_name_pattern)->data, tempfile,
fc932ac6 932 STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
bad95d8f 933#endif /* not DOS_NT */
7e6c2178 934
09494912
RS
935 coding_systems = Qt;
936
80856e74
JB
937 mktemp (tempfile);
938
939 filename_string = build_string (tempfile);
39323a7e 940 GCPRO1 (filename_string);
80856e74
JB
941 start = args[0];
942 end = args[1];
32d08644 943 /* Decide coding-system of the contents of the temporary file. */
91489411
RS
944 if (!NILP (Vcoding_system_for_write))
945 val = Vcoding_system_for_write;
946 else if (NILP (current_buffer->enable_multibyte_characters))
32d08644
KH
947 val = Qnil;
948 else
beacaab3 949 {
91489411
RS
950 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
951 args2[0] = Qcall_process_region;
952 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
953 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
954 if (CONSP (coding_systems))
70949dac 955 val = XCDR (coding_systems);
91489411 956 else if (CONSP (Vdefault_process_coding_system))
70949dac 957 val = XCDR (Vdefault_process_coding_system);
beacaab3 958 else
91489411 959 val = Qnil;
beacaab3 960 }
32d08644 961
168afdaa
RS
962 {
963 int count1 = specpdl_ptr - specpdl;
964
965 specbind (intern ("coding-system-for-write"), val);
966 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
967
968 unbind_to (count1, Qnil);
969 }
91489411
RS
970
971 /* Note that Fcall_process takes care of binding
972 coding-system-for-read. */
093650fe 973
80856e74
JB
974 record_unwind_protect (delete_temp_file, filename_string);
975
edf496dd 976 if (nargs > 3 && !NILP (args[3]))
80856e74
JB
977 Fdelete_region (start, end);
978
edf496dd
KH
979 if (nargs > 3)
980 {
981 args += 2;
982 nargs -= 2;
983 }
984 else
985 {
986 args[0] = args[2];
987 nargs = 2;
988 }
989 args[1] = filename_string;
80856e74 990
edf496dd 991 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs, args)));
80856e74
JB
992}
993\f
994#ifndef VMS /* VMS version is in vmsproc.c. */
995
dfcf069d
AS
996static int relocate_fd ();
997
80856e74
JB
998/* This is the last thing run in a newly forked inferior
999 either synchronous or asynchronous.
1000 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
1001 Initialize inferior's priority, pgrp, connected dir and environment.
1002 then exec another program based on new_argv.
1003
1004 This function may change environ for the superior process.
1005 Therefore, the superior process must save and restore the value
1006 of environ around the vfork and the call to this function.
1007
80856e74 1008 SET_PGRP is nonzero if we should put the subprocess into a separate
e576cab4
JB
1009 process group.
1010
1011 CURRENT_DIR is an elisp string giving the path of the current
1012 directory the subprocess should have. Since we can't really signal
1013 a decent error from within the child, this should be verified as an
1014 executable directory by the parent. */
80856e74 1015
dfcf069d 1016int
e576cab4 1017child_setup (in, out, err, new_argv, set_pgrp, current_dir)
80856e74
JB
1018 int in, out, err;
1019 register char **new_argv;
80856e74 1020 int set_pgrp;
e576cab4 1021 Lisp_Object current_dir;
80856e74 1022{
e576cab4 1023 char **env;
7fcf7f05 1024 char *pwd_var;
bad95d8f
RS
1025#ifdef WINDOWSNT
1026 int cpid;
4252a4bd 1027 HANDLE handles[3];
bad95d8f 1028#endif /* WINDOWSNT */
e576cab4 1029
33abe2d9 1030 int pid = getpid ();
80856e74 1031
68d10241 1032#ifdef SET_EMACS_PRIORITY
4f0b9d49
JB
1033 {
1034 extern int emacs_priority;
1035
68d10241
RS
1036 if (emacs_priority < 0)
1037 nice (- emacs_priority);
4f0b9d49 1038 }
5b633aeb 1039#endif
80856e74
JB
1040
1041#ifdef subprocesses
1042 /* Close Emacs's descriptors that this process should not have. */
1043 close_process_descs ();
1044#endif
c17c4250
EZ
1045 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
1046 we will lose if we call close_load_descs here. */
1047#ifndef DOS_NT
4458cebe 1048 close_load_descs ();
c17c4250 1049#endif
80856e74
JB
1050
1051 /* Note that use of alloca is always safe here. It's obvious for systems
1052 that do not have true vfork or that have true (stack) alloca.
1053 If using vfork and C_ALLOCA it is safe because that changes
1054 the superior's static variables as if the superior had done alloca
1055 and will be cleaned up in the usual way. */
e576cab4 1056 {
7fcf7f05 1057 register char *temp;
e576cab4 1058 register int i;
77d78be1 1059
fc932ac6 1060 i = STRING_BYTES (XSTRING (current_dir));
7fcf7f05
RS
1061 pwd_var = (char *) alloca (i + 6);
1062 temp = pwd_var + 4;
1063 bcopy ("PWD=", pwd_var, 4);
e576cab4 1064 bcopy (XSTRING (current_dir)->data, temp, i);
bad95d8f 1065 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
e576cab4
JB
1066 temp[i] = 0;
1067
c17c4250 1068#ifndef DOS_NT
e576cab4
JB
1069 /* We can't signal an Elisp error here; we're in a vfork. Since
1070 the callers check the current directory before forking, this
1071 should only return an error if the directory's permissions
1072 are changed between the check and this chdir, but we should
1073 at least check. */
1074 if (chdir (temp) < 0)
20b25e46 1075 _exit (errno);
b4c7684c 1076#endif
7fcf7f05 1077
c17c4250
EZ
1078#ifdef DOS_NT
1079 /* Get past the drive letter, so that d:/ is left alone. */
1080 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1081 {
1082 temp += 2;
1083 i -= 2;
1084 }
1085#endif
1086
7fcf7f05 1087 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
bad95d8f 1088 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
7fcf7f05 1089 temp[--i] = 0;
e576cab4 1090 }
80856e74 1091
80856e74
JB
1092 /* Set `env' to a vector of the strings in Vprocess_environment. */
1093 {
1094 register Lisp_Object tem;
1095 register char **new_env;
1096 register int new_length;
1097
1098 new_length = 0;
1099 for (tem = Vprocess_environment;
70949dac
KR
1100 CONSP (tem) && STRINGP (XCAR (tem));
1101 tem = XCDR (tem))
80856e74
JB
1102 new_length++;
1103
7fcf7f05
RS
1104 /* new_length + 2 to include PWD and terminating 0. */
1105 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
1106
1107 /* If we have a PWD envvar, pass one down,
1108 but with corrected value. */
1109 if (getenv ("PWD"))
1110 *new_env++ = pwd_var;
80856e74 1111
cd9565ba 1112 /* Copy the Vprocess_environment strings into new_env. */
80856e74 1113 for (tem = Vprocess_environment;
70949dac
KR
1114 CONSP (tem) && STRINGP (XCAR (tem));
1115 tem = XCDR (tem))
cd9565ba
RS
1116 {
1117 char **ep = env;
70949dac 1118 char *string = (char *) XSTRING (XCAR (tem))->data;
cd9565ba
RS
1119 /* See if this string duplicates any string already in the env.
1120 If so, don't put it in.
1121 When an env var has multiple definitions,
1122 we keep the definition that comes first in process-environment. */
1123 for (; ep != new_env; ep++)
1124 {
1125 char *p = *ep, *q = string;
1126 while (1)
1127 {
1128 if (*q == 0)
1129 /* The string is malformed; might as well drop it. */
1130 goto duplicate;
1131 if (*q != *p)
1132 break;
1133 if (*q == '=')
1134 goto duplicate;
1135 p++, q++;
1136 }
1137 }
1138 *new_env++ = string;
1139 duplicate: ;
1140 }
80856e74
JB
1141 *new_env = 0;
1142 }
bad95d8f
RS
1143#ifdef WINDOWSNT
1144 prepare_standard_handles (in, out, err, handles);
b4c7684c 1145 set_process_dir (XSTRING (current_dir)->data);
bad95d8f 1146#else /* not WINDOWSNT */
426b37ae
JB
1147 /* Make sure that in, out, and err are not actually already in
1148 descriptors zero, one, or two; this could happen if Emacs is
7e6c2178 1149 started with its standard in, out, or error closed, as might
426b37ae 1150 happen under X. */
f29f9e4a
RS
1151 {
1152 int oin = in, oout = out;
1153
1154 /* We have to avoid relocating the same descriptor twice! */
1155
1156 in = relocate_fd (in, 3);
1157
1158 if (out == oin)
1159 out = in;
1160 else
3e9367e7 1161 out = relocate_fd (out, 3);
f29f9e4a
RS
1162
1163 if (err == oin)
1164 err = in;
1165 else if (err == oout)
1166 err = out;
1167 else
3e9367e7 1168 err = relocate_fd (err, 3);
f29f9e4a 1169 }
426b37ae 1170
c17c4250 1171#ifndef MSDOS
68c45bf0
PE
1172 emacs_close (0);
1173 emacs_close (1);
1174 emacs_close (2);
80856e74
JB
1175
1176 dup2 (in, 0);
1177 dup2 (out, 1);
1178 dup2 (err, 2);
68c45bf0
PE
1179 emacs_close (in);
1180 emacs_close (out);
1181 emacs_close (err);
c17c4250 1182#endif /* not MSDOS */
bad95d8f 1183#endif /* not WINDOWSNT */
80856e74 1184
6b2cd868 1185#if defined(USG) && !defined(BSD_PGRPS)
fdba8590 1186#ifndef SETPGRP_RELEASES_CTTY
e576cab4 1187 setpgrp (); /* No arguments but equivalent in this case */
fdba8590 1188#endif
e576cab4
JB
1189#else
1190 setpgrp (pid, pid);
1191#endif /* USG */
a129418f
RS
1192 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
1193 EMACS_SET_TTY_PGRP (0, &pid);
80856e74
JB
1194
1195#ifdef vipc
1196 something missing here;
1197#endif /* vipc */
1198
c17c4250
EZ
1199#ifdef MSDOS
1200 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1201 if (pid == -1)
1202 /* An error occurred while trying to run the subprocess. */
1203 report_file_error ("Spawning child process", Qnil);
1204 return pid;
1205#else /* not MSDOS */
bad95d8f
RS
1206#ifdef WINDOWSNT
1207 /* Spawn the child. (See ntproc.c:Spawnve). */
1208 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
db77d785 1209 reset_standard_handles (in, out, err, handles);
ff27bfbe
KH
1210 if (cpid == -1)
1211 /* An error occurred while trying to spawn the process. */
1212 report_file_error ("Spawning child process", Qnil);
bad95d8f
RS
1213 return cpid;
1214#else /* not WINDOWSNT */
80856e74
JB
1215 /* execvp does not accept an environment arg so the only way
1216 to pass this environment is to set environ. Our caller
1217 is responsible for restoring the ambient value of environ. */
1218 environ = env;
1219 execvp (new_argv[0], new_argv);
1220
68c45bf0
PE
1221 emacs_write (1, "Can't exec program: ", 20);
1222 emacs_write (1, new_argv[0], strlen (new_argv[0]));
1223 emacs_write (1, "\n", 1);
80856e74 1224 _exit (1);
bad95d8f 1225#endif /* not WINDOWSNT */
7e6c2178 1226#endif /* not MSDOS */
80856e74
JB
1227}
1228
a3833dfe 1229/* Move the file descriptor FD so that its number is not less than MINFD.
426b37ae 1230 If the file descriptor is moved at all, the original is freed. */
dfcf069d 1231static int
a3833dfe
KH
1232relocate_fd (fd, minfd)
1233 int fd, minfd;
426b37ae 1234{
a3833dfe 1235 if (fd >= minfd)
426b37ae
JB
1236 return fd;
1237 else
1238 {
1239 int new = dup (fd);
1240 if (new == -1)
1241 {
20c018a0 1242 char *message1 = "Error while setting up child: ";
826c56ac 1243 char *errmessage = strerror (errno);
20c018a0 1244 char *message2 = "\n";
68c45bf0
PE
1245 emacs_write (2, message1, strlen (message1));
1246 emacs_write (2, errmessage, strlen (errmessage));
1247 emacs_write (2, message2, strlen (message2));
426b37ae
JB
1248 _exit (1);
1249 }
1250 /* Note that we hold the original FD open while we recurse,
1251 to guarantee we'll get a new FD if we need it. */
a3833dfe 1252 new = relocate_fd (new, minfd);
68c45bf0 1253 emacs_close (fd);
426b37ae
JB
1254 return new;
1255 }
1256}
1257
012c6fcb
JA
1258static int
1259getenv_internal (var, varlen, value, valuelen)
1260 char *var;
1261 int varlen;
1262 char **value;
1263 int *valuelen;
1264{
1265 Lisp_Object scan;
1266
70949dac 1267 for (scan = Vprocess_environment; CONSP (scan); scan = XCDR (scan))
012c6fcb 1268 {
c1350752
KH
1269 Lisp_Object entry;
1270
70949dac 1271 entry = XCAR (scan);
d50d3dc8 1272 if (STRINGP (entry)
fc932ac6 1273 && STRING_BYTES (XSTRING (entry)) > varlen
012c6fcb 1274 && XSTRING (entry)->data[varlen] == '='
bad95d8f
RS
1275#ifdef WINDOWSNT
1276 /* NT environment variables are case insensitive. */
a9971c6d 1277 && ! strnicmp (XSTRING (entry)->data, var, varlen)
bad95d8f 1278#else /* not WINDOWSNT */
a9971c6d 1279 && ! bcmp (XSTRING (entry)->data, var, varlen)
bad95d8f 1280#endif /* not WINDOWSNT */
a9971c6d 1281 )
012c6fcb
JA
1282 {
1283 *value = (char *) XSTRING (entry)->data + (varlen + 1);
fc932ac6 1284 *valuelen = STRING_BYTES (XSTRING (entry)) - (varlen + 1);
012c6fcb
JA
1285 return 1;
1286 }
1287 }
1288
1289 return 0;
1290}
1291
0ad477db 1292DEFUN ("getenv", Fgetenv, Sgetenv, 1, 1, 0,
012c6fcb
JA
1293 "Return the value of environment variable VAR, as a string.\n\
1294VAR should be a string. Value is nil if VAR is undefined in the environment.\n\
1295This function consults the variable ``process-environment'' for its value.")
1296 (var)
1297 Lisp_Object var;
1298{
1299 char *value;
1300 int valuelen;
1301
1302 CHECK_STRING (var, 0);
fc932ac6 1303 if (getenv_internal (XSTRING (var)->data, STRING_BYTES (XSTRING (var)),
012c6fcb
JA
1304 &value, &valuelen))
1305 return make_string (value, valuelen);
1306 else
1307 return Qnil;
1308}
1309
1310/* A version of getenv that consults process_environment, easily
e576cab4 1311 callable from C. */
012c6fcb
JA
1312char *
1313egetenv (var)
e576cab4 1314 char *var;
012c6fcb
JA
1315{
1316 char *value;
1317 int valuelen;
1318
1319 if (getenv_internal (var, strlen (var), &value, &valuelen))
1320 return value;
1321 else
1322 return 0;
1323}
1324
80856e74
JB
1325#endif /* not VMS */
1326\f
8de15d69 1327/* This is run before init_cmdargs. */
7e6c2178 1328
dfcf069d 1329void
8de15d69
RS
1330init_callproc_1 ()
1331{
1332 char *data_dir = egetenv ("EMACSDATA");
35a2f4b8
KH
1333 char *doc_dir = egetenv ("EMACSDOC");
1334
8de15d69 1335 Vdata_directory
7e6c2178 1336 = Ffile_name_as_directory (build_string (data_dir ? data_dir
8de15d69 1337 : PATH_DATA));
35a2f4b8
KH
1338 Vdoc_directory
1339 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
1340 : PATH_DOC));
9453ea7b 1341
e576cab4 1342 /* Check the EMACSPATH environment variable, defaulting to the
57bda87a 1343 PATH_EXEC path from epaths.h. */
e576cab4 1344 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
80856e74
JB
1345 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1346 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
8de15d69
RS
1347}
1348
e17f7533 1349/* This is run after init_cmdargs, when Vinstallation_directory is valid. */
8de15d69 1350
dfcf069d 1351void
8de15d69
RS
1352init_callproc ()
1353{
1354 char *data_dir = egetenv ("EMACSDATA");
1355
1356 register char * sh;
1357 Lisp_Object tempdir;
1358
9cc4fad5 1359 if (!NILP (Vinstallation_directory))
8de15d69 1360 {
05630743
RS
1361 /* Add to the path the lib-src subdir of the installation dir. */
1362 Lisp_Object tem;
1363 tem = Fexpand_file_name (build_string ("lib-src"),
1364 Vinstallation_directory);
bad95d8f 1365#ifndef DOS_NT
1a6640ec 1366 /* MSDOS uses wrapped binaries, so don't do this. */
0fa248bc
RS
1367 if (NILP (Fmember (tem, Vexec_path)))
1368 Vexec_path = nconc2 (Vexec_path, Fcons (tem, Qnil));
1369
1370 Vexec_directory = Ffile_name_as_directory (tem);
bad95d8f 1371#endif /* not DOS_NT */
8de15d69 1372
e17f7533
RS
1373 /* Maybe use ../etc as well as ../lib-src. */
1374 if (data_dir == 0)
1375 {
1376 tem = Fexpand_file_name (build_string ("etc"),
1377 Vinstallation_directory);
1378 Vdoc_directory = Ffile_name_as_directory (tem);
8de15d69
RS
1379 }
1380 }
7e933683
RS
1381
1382 /* Look for the files that should be in etc. We don't use
1383 Vinstallation_directory, because these files are never installed
e17f7533 1384 near the executable, and they are never in the build
7e933683
RS
1385 directory when that's different from the source directory.
1386
1387 Instead, if these files are not in the nominal place, we try the
1388 source directory. */
1389 if (data_dir == 0)
1390 {
1391 Lisp_Object tem, tem1, newdir;
1392
1393 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1394 tem1 = Ffile_exists_p (tem);
1395 if (NILP (tem1))
1396 {
1397 newdir = Fexpand_file_name (build_string ("../etc/"),
1398 build_string (PATH_DUMPLOADSEARCH));
1399 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1400 tem1 = Ffile_exists_p (tem);
1401 if (!NILP (tem1))
1402 Vdata_directory = newdir;
1403 }
1404 }
80856e74 1405
d883eb62
RS
1406#ifndef CANNOT_DUMP
1407 if (initialized)
1408#endif
1409 {
1410 tempdir = Fdirectory_file_name (Vexec_directory);
1411 if (access (XSTRING (tempdir)->data, 0) < 0)
1412 dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
1413 Vexec_directory);
1414 }
80856e74 1415
e576cab4
JB
1416 tempdir = Fdirectory_file_name (Vdata_directory);
1417 if (access (XSTRING (tempdir)->data, 0) < 0)
76d5c6cf
RS
1418 dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
1419 Vdata_directory);
e576cab4 1420
80856e74
JB
1421#ifdef VMS
1422 Vshell_file_name = build_string ("*dcl*");
1423#else
e576cab4 1424 sh = (char *) getenv ("SHELL");
80856e74
JB
1425 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1426#endif
8abd035b
RS
1427
1428#ifdef VMS
1429 Vtemp_file_name_pattern = build_string ("tmp:emacsXXXXXX.");
1430#else
1431 if (getenv ("TMPDIR"))
1432 {
1433 char *dir = getenv ("TMPDIR");
1434 Vtemp_file_name_pattern
1435 = Fexpand_file_name (build_string ("emacsXXXXXX"),
1436 build_string (dir));
1437 }
1438 else
1439 Vtemp_file_name_pattern = build_string ("/tmp/emacsXXXXXX");
1440#endif
9fefd2ba
JB
1441}
1442
dfcf069d 1443void
9fefd2ba
JB
1444set_process_environment ()
1445{
1446 register char **envp;
80856e74 1447
80856e74
JB
1448 Vprocess_environment = Qnil;
1449#ifndef CANNOT_DUMP
1450 if (initialized)
1451#endif
1452 for (envp = environ; *envp; envp++)
1453 Vprocess_environment = Fcons (build_string (*envp),
1454 Vprocess_environment);
80856e74
JB
1455}
1456
dfcf069d 1457void
80856e74
JB
1458syms_of_callproc ()
1459{
bad95d8f 1460#ifdef DOS_NT
093650fe
RS
1461 Qbuffer_file_type = intern ("buffer-file-type");
1462 staticpro (&Qbuffer_file_type);
bad95d8f 1463#endif /* DOS_NT */
7e6c2178 1464
80856e74
JB
1465 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
1466 "*File name to load inferior shells from.\n\
1467Initialized from the SHELL environment variable.");
1468
1469 DEFVAR_LISP ("exec-path", &Vexec_path,
1470 "*List of directories to search programs to run in subprocesses.\n\
1471Each element is a string (directory name) or nil (try default directory).");
1472
1473 DEFVAR_LISP ("exec-directory", &Vexec_directory,
57ca9855
RS
1474 "Directory for executables for Emacs to invoke.\n\
1475More generally, this includes any architecture-dependent files\n\
1476that are built and installed from the Emacs distribution.");
e576cab4
JB
1477
1478 DEFVAR_LISP ("data-directory", &Vdata_directory,
57ca9855
RS
1479 "Directory of machine-independent files that come with GNU Emacs.\n\
1480These are files intended for Emacs to use while it runs.");
80856e74 1481
35a2f4b8
KH
1482 DEFVAR_LISP ("doc-directory", &Vdoc_directory,
1483 "Directory containing the DOC file that comes with GNU Emacs.\n\
1484This is usually the same as data-directory.");
1485
ed61592a
JB
1486 DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
1487 "For internal use by the build procedure only.\n\
1488This is the name of the directory in which the build procedure installed\n\
1489Emacs's info files; the default value for Info-default-directory-list\n\
1490includes this.");
1491 Vconfigure_info_directory = build_string (PATH_INFO);
1492
8abd035b
RS
1493 DEFVAR_LISP ("temp-file-name-pattern", &Vtemp_file_name_pattern,
1494 "Pattern for making names for temporary files.\n\
1495This is used by `call-process-region'.");
0537ec48 1496 /* This variable is initialized in init_callproc. */
8abd035b 1497
80856e74 1498 DEFVAR_LISP ("process-environment", &Vprocess_environment,
e576cab4
JB
1499 "List of environment variables for subprocesses to inherit.\n\
1500Each element should be a string of the form ENVVARNAME=VALUE.\n\
1501The environment which Emacs inherits is placed in this variable\n\
1502when Emacs starts.");
80856e74
JB
1503
1504#ifndef VMS
1505 defsubr (&Scall_process);
012c6fcb 1506 defsubr (&Sgetenv);
986ffb24 1507#endif
e576cab4 1508 defsubr (&Scall_process_region);
80856e74 1509}