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