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