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