(MSVCNT11): Defined.
[bpt/emacs.git] / src / callproc.c
CommitLineData
80856e74 1/* Synchronous subprocess invocation for GNU Emacs.
f8c25f1b 2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95 Free Software Foundation, Inc.
80856e74
JB
3
4This file is part of GNU Emacs.
5
6GNU Emacs is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
826c56ac 8the Free Software Foundation; either version 2, or (at your option)
80856e74
JB
9any later version.
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Emacs; see the file COPYING. If not, write to
18the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
19
20
21#include <signal.h>
e576cab4 22#include <errno.h>
80856e74 23
18160b98 24#include <config.h>
565620a5 25#include <stdio.h>
80856e74 26
426b37ae 27extern int errno;
826c56ac 28extern char *strerror ();
426b37ae 29
80856e74
JB
30/* Define SIGCHLD as an alias for SIGCLD. */
31
32#if !defined (SIGCHLD) && defined (SIGCLD)
33#define SIGCHLD SIGCLD
34#endif /* SIGCLD */
35
36#include <sys/types.h>
88a64fef 37
80856e74
JB
38#include <sys/file.h>
39#ifdef USG5
472e83fe 40#define INCLUDED_FCNTL
80856e74
JB
41#include <fcntl.h>
42#endif
43
bad95d8f
RS
44#ifdef WINDOWSNT
45#define NOMINMAX
46#include <windows.h>
47#include <stdlib.h> /* for proper declaration of environ */
48#include <fcntl.h>
49#include "nt.h"
50#define _P_NOWAIT 1 /* from process.h */
51#endif
52
7e6c2178 53#ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
00353d4f 54#include "msdos.h"
472e83fe 55#define INCLUDED_FCNTL
7e6c2178
RS
56#include <fcntl.h>
57#include <sys/stat.h>
58#include <sys/param.h>
59#include <errno.h>
60#endif /* MSDOS */
61
80856e74
JB
62#ifndef O_RDONLY
63#define O_RDONLY 0
64#endif
65
66#ifndef O_WRONLY
67#define O_WRONLY 1
68#endif
69
70#include "lisp.h"
71#include "commands.h"
72#include "buffer.h"
2a6b3537 73#include <paths.h>
80856e74 74#include "process.h"
d177f194 75#include "syssignal.h"
a129418f 76#include "systty.h"
80856e74
JB
77
78#ifdef VMS
79extern noshare char **environ;
80#else
81extern char **environ;
82#endif
83
84#define max(a, b) ((a) > (b) ? (a) : (b))
85
bad95d8f 86#ifdef DOS_NT
093650fe
RS
87/* When we are starting external processes we need to know whether they
88 take binary input (no conversion) or text input (\n is converted to
89 \r\n). Similar for output: if newlines are written as \r\n then it's
90 text process output, otherwise it's binary. */
91Lisp_Object Vbinary_process_input;
92Lisp_Object Vbinary_process_output;
bad95d8f 93#endif /* DOS_NT */
7e6c2178 94
35a2f4b8 95Lisp_Object Vexec_path, Vexec_directory, Vdata_directory, Vdoc_directory;
ed61592a 96Lisp_Object Vconfigure_info_directory;
80856e74
JB
97
98Lisp_Object Vshell_file_name;
99
80856e74 100Lisp_Object Vprocess_environment;
80856e74 101
bad95d8f 102#ifdef DOS_NT
093650fe 103Lisp_Object Qbuffer_file_type;
bad95d8f 104#endif /* DOS_NT */
093650fe 105
80856e74
JB
106/* True iff we are about to fork off a synchronous process or if we
107 are waiting for it. */
108int synch_process_alive;
109
110/* Nonzero => this is a string explaining death of synchronous subprocess. */
111char *synch_process_death;
112
113/* If synch_process_death is zero,
114 this is exit code of synchronous subprocess. */
115int synch_process_retcode;
8de15d69
RS
116
117extern Lisp_Object Vdoc_file_name;
80856e74 118\f
37d54121
RS
119/* Clean up when exiting Fcall_process.
120 On MSDOS, delete the temporary file on any kind of termination.
121 On Unix, kill the process and any children on termination by signal. */
122
123/* Nonzero if this is termination due to exit. */
124static int call_process_exited;
125
80856e74
JB
126#ifndef VMS /* VMS version is in vmsproc.c. */
127
d177f194
JB
128static Lisp_Object
129call_process_kill (fdpid)
130 Lisp_Object fdpid;
131{
132 close (XFASTINT (Fcar (fdpid)));
133 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
134 synch_process_alive = 0;
135 return Qnil;
136}
137
80856e74
JB
138Lisp_Object
139call_process_cleanup (fdpid)
140 Lisp_Object fdpid;
141{
7e6c2178
RS
142#ifdef MSDOS
143 /* for MSDOS fdpid is really (fd . tempfile) */
c1350752
KH
144 register Lisp_Object file;
145 file = Fcdr (fdpid);
7e6c2178
RS
146 close (XFASTINT (Fcar (fdpid)));
147 if (strcmp (XSTRING (file)-> data, NULL_DEVICE) != 0)
148 unlink (XSTRING (file)->data);
149#else /* not MSDOS */
d177f194
JB
150 register int pid = XFASTINT (Fcdr (fdpid));
151
6b6e798b 152
37d54121 153 if (call_process_exited)
6b6e798b
RS
154 {
155 close (XFASTINT (Fcar (fdpid)));
156 return Qnil;
157 }
37d54121 158
d177f194
JB
159 if (EMACS_KILLPG (pid, SIGINT) == 0)
160 {
161 int count = specpdl_ptr - specpdl;
162 record_unwind_protect (call_process_kill, fdpid);
163 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
164 immediate_quit = 1;
165 QUIT;
166 wait_for_termination (pid);
167 immediate_quit = 0;
168 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
169 message1 ("Waiting for process to die...done");
170 }
80856e74 171 synch_process_alive = 0;
d177f194 172 close (XFASTINT (Fcar (fdpid)));
7e6c2178 173#endif /* not MSDOS */
80856e74
JB
174 return Qnil;
175}
176
177DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
178 "Call PROGRAM synchronously in separate process.\n\
179The program's input comes from file INFILE (nil means `/dev/null').\n\
180Insert output in BUFFER before point; t means current buffer;\n\
181 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
39eaa782
RS
182BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
183REAL-BUFFER says what to do with standard output, as above,\n\
184while STDERR-FILE says what to do with standard error in the child.\n\
185STDERR-FILE may be nil (discard standard error output),\n\
186t (mix it with ordinary output), or a file name string.\n\
187\n\
80856e74
JB
188Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
189Remaining arguments are strings passed as command arguments to PROGRAM.\n\
39eaa782
RS
190\n\
191If BUFFER is 0, `call-process' returns immediately with value nil.\n\
192Otherwise it waits for PROGRAM to terminate\n\
e576cab4 193and returns a numeric exit status or a signal description string.\n\
d177f194 194If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
80856e74
JB
195 (nargs, args)
196 int nargs;
197 register Lisp_Object *args;
198{
58616e67 199 Lisp_Object infile, buffer, current_dir, display, path;
80856e74
JB
200 int fd[2];
201 int filefd;
202 register int pid;
6e3bfbb2
RS
203 char buf[16384];
204 char *bufptr = buf;
205 int bufsize = 16384;
80856e74
JB
206 int count = specpdl_ptr - specpdl;
207 register unsigned char **new_argv
208 = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
209 struct buffer *old = current_buffer;
39eaa782
RS
210 /* File to use for stderr in the child.
211 t means use same as standard output. */
212 Lisp_Object error_file;
7e6c2178
RS
213#ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
214 char *outf, *tempfile;
215 int outfilefd;
216#endif
80856e74
JB
217#if 0
218 int mask;
219#endif
80856e74
JB
220 CHECK_STRING (args[0], 0);
221
39eaa782
RS
222 error_file = Qt;
223
7e6c2178
RS
224#ifndef subprocesses
225 /* Without asynchronous processes we cannot have BUFFER == 0. */
d50d3dc8 226 if (nargs >= 3 && INTEGERP (args[2]))
7e6c2178
RS
227 error ("Operating system cannot handle asynchronous subprocesses");
228#endif /* subprocesses */
229
e576cab4
JB
230 if (nargs >= 2 && ! NILP (args[1]))
231 {
232 infile = Fexpand_file_name (args[1], current_buffer->directory);
233 CHECK_STRING (infile, 1);
234 }
80856e74 235 else
5437e9f9 236 infile = build_string (NULL_DEVICE);
80856e74 237
e576cab4
JB
238 if (nargs >= 3)
239 {
39eaa782
RS
240 buffer = args[2];
241
242 /* If BUFFER is a list, its meaning is
243 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
244 if (CONSP (buffer))
245 {
246 if (CONSP (XCONS (buffer)->cdr))
d20b8af6
RS
247 error_file = Fexpand_file_name (XCONS (XCONS (buffer)->cdr)->car,
248 Qnil);
39eaa782
RS
249 buffer = XCONS (buffer)->car;
250 }
044512ed 251
39eaa782
RS
252 if (!(EQ (buffer, Qnil)
253 || EQ (buffer, Qt)
254 || XFASTINT (buffer) == 0))
e576cab4 255 {
39eaa782
RS
256 Lisp_Object spec_buffer;
257 spec_buffer = buffer;
258 buffer = Fget_buffer (buffer);
259 /* Mention the buffer name for a better error message. */
260 if (NILP (buffer))
261 CHECK_BUFFER (spec_buffer, 2);
e576cab4
JB
262 CHECK_BUFFER (buffer, 2);
263 }
264 }
265 else
266 buffer = Qnil;
80856e74 267
58616e67
JB
268 /* Make sure that the child will be able to chdir to the current
269 buffer's current directory, or its unhandled equivalent. We
270 can't just have the child check for an error when it does the
271 chdir, since it's in a vfork.
272
273 We have to GCPRO around this because Fexpand_file_name,
274 Funhandled_file_name_directory, and Ffile_accessible_directory_p
275 might call a file name handling function. The argument list is
276 protected by the caller, so all we really have to worry about is
277 buffer. */
278 {
279 struct gcpro gcpro1, gcpro2, gcpro3;
280
281 current_dir = current_buffer->directory;
282
283 GCPRO3 (infile, buffer, current_dir);
284
c52b0b34
KH
285 current_dir
286 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
287 Qnil);
58616e67
JB
288 if (NILP (Ffile_accessible_directory_p (current_dir)))
289 report_file_error ("Setting current directory",
290 Fcons (current_buffer->directory, Qnil));
291
292 UNGCPRO;
293 }
294
e576cab4 295 display = nargs >= 4 ? args[3] : Qnil;
80856e74 296
e576cab4 297 filefd = open (XSTRING (infile)->data, O_RDONLY, 0);
80856e74
JB
298 if (filefd < 0)
299 {
e576cab4 300 report_file_error ("Opening process input file", Fcons (infile, Qnil));
80856e74
JB
301 }
302 /* Search for program; barf if not found. */
c52b0b34
KH
303 {
304 struct gcpro gcpro1;
305
306 GCPRO1 (current_dir);
307 openp (Vexec_path, args[0], EXEC_SUFFIXES, &path, 1);
308 UNGCPRO;
309 }
012c6fcb 310 if (NILP (path))
80856e74
JB
311 {
312 close (filefd);
313 report_file_error ("Searching for program", Fcons (args[0], Qnil));
314 }
315 new_argv[0] = XSTRING (path)->data;
c52b0b34
KH
316 {
317 register int i;
318 for (i = 4; i < nargs; i++)
319 {
320 CHECK_STRING (args[i], i);
321 new_argv[i - 3] = XSTRING (args[i])->data;
322 }
323 new_argv[i - 3] = 0;
324 }
80856e74 325
7e6c2178
RS
326#ifdef MSDOS /* MW, July 1993 */
327 /* These vars record information from process termination.
328 Clear them now before process can possibly terminate,
329 to avoid timing error if process terminates soon. */
330 synch_process_death = 0;
331 synch_process_retcode = 0;
332
333 if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
334 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
335 else
336 {
337 tempfile = alloca (20);
338 *tempfile = '\0';
339 }
340 dostounix_filename (tempfile);
341 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
342 strcat (tempfile, "/");
343 strcat (tempfile, "detmp.XXX");
344 mktemp (tempfile);
345
346 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
347 if (outfilefd < 0)
348 {
349 close (filefd);
350 report_file_error ("Opening process output file", Fcons (tempfile, Qnil));
351 }
352#endif
353
d50d3dc8 354 if (INTEGERP (buffer))
5437e9f9 355 fd[1] = open (NULL_DEVICE, O_WRONLY), fd[0] = -1;
80856e74
JB
356 else
357 {
7e6c2178 358#ifndef MSDOS
bad95d8f
RS
359#ifdef WINDOWSNT
360 pipe_with_inherited_out (fd);
361#else /* not WINDOWSNT */
80856e74 362 pipe (fd);
bad95d8f 363#endif /* not WINDOWSNT */
7e6c2178 364#endif
80856e74
JB
365#if 0
366 /* Replaced by close_process_descs */
367 set_exclusive_use (fd[0]);
368#endif
369 }
370
371 {
372 /* child_setup must clobber environ in systems with true vfork.
373 Protect it from permanent change. */
374 register char **save_environ = environ;
375 register int fd1 = fd[1];
39eaa782 376 int fd_error = fd1;
80856e74
JB
377
378#if 0 /* Some systems don't have sigblock. */
e065a56e 379 mask = sigblock (sigmask (SIGCHLD));
80856e74
JB
380#endif
381
382 /* Record that we're about to create a synchronous process. */
383 synch_process_alive = 1;
384
5c03767e
RS
385 /* These vars record information from process termination.
386 Clear them now before process can possibly terminate,
387 to avoid timing error if process terminates soon. */
388 synch_process_death = 0;
389 synch_process_retcode = 0;
390
7e6c2178 391#ifdef MSDOS /* MW, July 1993 */
6b6e798b
RS
392 /* ??? Someone who knows MSDOG needs to check whether this properly
393 closes all descriptors that it opens. */
7e6c2178
RS
394 pid = run_msdos_command (new_argv, current_dir, filefd, outfilefd);
395 close (outfilefd);
396 fd1 = -1; /* No harm in closing that one! */
093650fe 397 fd[0] = open (tempfile, NILP (Vbinary_process_output) ? O_TEXT : O_BINARY);
7e6c2178
RS
398 if (fd[0] < 0)
399 {
400 unlink (tempfile);
6b6e798b 401 close (filefd);
7e6c2178
RS
402 report_file_error ("Cannot re-open temporary file", Qnil);
403 }
404#else /* not MSDOS */
39eaa782
RS
405
406 if (NILP (error_file))
407 fd_error = open (NULL_DEVICE, O_WRONLY);
408 else if (STRINGP (error_file))
409 {
410#ifdef DOS_NT
411 fd_error = open (XSTRING (error_file)->data,
412 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
413 S_IREAD | S_IWRITE);
414#else /* not DOS_NT */
415 fd_error = creat (XSTRING (error_file)->data, 0666);
416#endif /* not DOS_NT */
417 }
418
419 if (fd_error < 0)
420 {
421 close (filefd);
422 close (fd[0]);
423 if (fd1 >= 0)
424 close (fd1);
425 report_file_error ("Cannot open", error_file);
426 }
427
bad95d8f 428#ifdef WINDOWSNT
39eaa782 429 pid = child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
bad95d8f 430#else /* not WINDOWSNT */
80856e74
JB
431 pid = vfork ();
432
433 if (pid == 0)
434 {
435 if (fd[0] >= 0)
436 close (fd[0]);
5a570e37 437#ifdef USG
80856e74
JB
438 setpgrp ();
439#else
440 setpgrp (pid, pid);
441#endif /* USG */
39eaa782 442 child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
80856e74 443 }
7e6c2178 444#endif /* not MSDOS */
bad95d8f 445#endif /* not WINDOWSNT */
80856e74 446
80856e74
JB
447 environ = save_environ;
448
6b6e798b
RS
449 /* Close most of our fd's, but not fd[0]
450 since we will use that to read input from. */
80856e74 451 close (filefd);
7e6c2178
RS
452 if (fd1 >= 0)
453 close (fd1);
80856e74
JB
454 }
455
456 if (pid < 0)
457 {
6b6e798b
RS
458 if (fd[0] >= 0)
459 close (fd[0]);
80856e74
JB
460 report_file_error ("Doing vfork", Qnil);
461 }
462
d50d3dc8 463 if (INTEGERP (buffer))
80856e74 464 {
6b6e798b
RS
465 if (fd[0] >= 0)
466 close (fd[0]);
80856e74 467#ifndef subprocesses
e576cab4
JB
468 /* If Emacs has been built with asynchronous subprocess support,
469 we don't need to do this, I think because it will then have
470 the facilities for handling SIGCHLD. */
80856e74
JB
471 wait_without_blocking ();
472#endif /* subprocesses */
80856e74
JB
473 return Qnil;
474 }
475
6b6e798b 476 /* Enable sending signal if user quits below. */
37d54121
RS
477 call_process_exited = 0;
478
7e6c2178
RS
479#ifdef MSDOS
480 /* MSDOS needs different cleanup information. */
481 record_unwind_protect (call_process_cleanup,
482 Fcons (make_number (fd[0]), build_string (tempfile)));
483#else
80856e74
JB
484 record_unwind_protect (call_process_cleanup,
485 Fcons (make_number (fd[0]), make_number (pid)));
7e6c2178 486#endif /* not MSDOS */
80856e74
JB
487
488
d50d3dc8 489 if (BUFFERP (buffer))
80856e74
JB
490 Fset_buffer (buffer);
491
492 immediate_quit = 1;
493 QUIT;
494
495 {
496 register int nread;
0ad477db 497 int first = 1;
6e3bfbb2 498 int total_read = 0;
80856e74 499
60558b19 500 while (1)
80856e74 501 {
60558b19
RS
502 /* Repeatedly read until we've filled as much as possible
503 of the buffer size we have. But don't read
504 less than 1024--save that for the next bufferfull. */
505
506 nread = 0;
507 while (nread < bufsize - 1024)
00fb3e95 508 {
60558b19
RS
509 int this_read
510 = read (fd[0], bufptr + nread, bufsize - nread);
511
512 if (this_read < 0)
513 goto give_up;
514
515 if (this_read == 0)
516 goto give_up_1;
517
518 nread += this_read;
00fb3e95 519 }
60558b19
RS
520
521 give_up_1:
522
523 /* Now NREAD is the total amount of data in the buffer. */
524 if (nread == 0)
525 break;
526
80856e74 527 immediate_quit = 0;
6e3bfbb2
RS
528 total_read += nread;
529
012c6fcb 530 if (!NILP (buffer))
6e3bfbb2
RS
531 insert (bufptr, nread);
532
533 /* Make the buffer bigger as we continue to read more data,
534 but not past 64k. */
535 if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
536 {
537 bufsize *= 2;
538 bufptr = (char *) alloca (bufsize);
539 }
540
012c6fcb 541 if (!NILP (display) && INTERACTIVE)
0ad477db
RS
542 {
543 if (first)
544 prepare_menu_bars ();
545 first = 0;
546 redisplay_preserve_echo_area ();
547 }
80856e74
JB
548 immediate_quit = 1;
549 QUIT;
550 }
60558b19 551 give_up: ;
80856e74
JB
552 }
553
554 /* Wait for it to terminate, unless it already has. */
555 wait_for_termination (pid);
556
557 immediate_quit = 0;
558
559 set_buffer_internal (old);
560
37d54121
RS
561 /* Don't kill any children that the subprocess may have left behind
562 when exiting. */
563 call_process_exited = 1;
564
80856e74
JB
565 unbind_to (count, Qnil);
566
80856e74
JB
567 if (synch_process_death)
568 return build_string (synch_process_death);
569 return make_number (synch_process_retcode);
570}
571#endif
572\f
9fefd2ba 573static Lisp_Object
80856e74
JB
574delete_temp_file (name)
575 Lisp_Object name;
576{
2e3dc201 577 /* Use Fdelete_file (indirectly) because that runs a file name handler.
59750d69 578 We did that when writing the file, so we should do so when deleting. */
2e3dc201 579 internal_delete_file (name);
80856e74
JB
580}
581
582DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
583 3, MANY, 0,
584 "Send text from START to END to a synchronous process running PROGRAM.\n\
585Delete the text if fourth arg DELETE is non-nil.\n\
39eaa782 586\n\
80856e74
JB
587Insert output in BUFFER before point; t means current buffer;\n\
588 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
39eaa782
RS
589BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
590REAL-BUFFER says what to do with standard output, as above,\n\
591while STDERR-FILE says what to do with standard error in the child.\n\
592STDERR-FILE may be nil (discard standard error output),\n\
593t (mix it with ordinary output), or a file name string.\n\
594\n\
80856e74
JB
595Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
596Remaining args are passed to PROGRAM at startup as command args.\n\
39eaa782
RS
597\n\
598If BUFFER is nil, `call-process-region' returns immediately with value nil.\n\
599Otherwise it waits for PROGRAM to terminate\n\
e576cab4 600and returns a numeric exit status or a signal description string.\n\
d177f194 601If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
80856e74
JB
602 (nargs, args)
603 int nargs;
604 register Lisp_Object *args;
605{
39323a7e
KH
606 struct gcpro gcpro1;
607 Lisp_Object filename_string;
608 register Lisp_Object start, end;
bad95d8f 609#ifdef DOS_NT
7e6c2178
RS
610 char *tempfile;
611#else
80856e74 612 char tempfile[20];
7e6c2178 613#endif
80856e74 614 int count = specpdl_ptr - specpdl;
bad95d8f 615#ifdef DOS_NT
7e6c2178
RS
616 char *outf = '\0';
617
618 if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
619 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
620 else
621 {
622 tempfile = alloca (20);
623 *tempfile = '\0';
624 }
625 dostounix_filename (tempfile);
626 if (tempfile[strlen (tempfile) - 1] != '/')
627 strcat (tempfile, "/");
628 strcat (tempfile, "detmp.XXX");
bad95d8f 629#else /* not DOS_NT */
80856e74
JB
630
631#ifdef VMS
632 strcpy (tempfile, "tmp:emacsXXXXXX.");
633#else
634 strcpy (tempfile, "/tmp/emacsXXXXXX");
635#endif
bad95d8f 636#endif /* not DOS_NT */
7e6c2178 637
80856e74
JB
638 mktemp (tempfile);
639
640 filename_string = build_string (tempfile);
39323a7e 641 GCPRO1 (filename_string);
80856e74
JB
642 start = args[0];
643 end = args[1];
bad95d8f 644#ifdef DOS_NT
093650fe
RS
645 specbind (Qbuffer_file_type, Vbinary_process_input);
646 Fwrite_region (start, end, filename_string, Qnil, Qlambda);
647 unbind_to (count, Qnil);
bad95d8f 648#else /* not DOS_NT */
80856e74 649 Fwrite_region (start, end, filename_string, Qnil, Qlambda);
bad95d8f 650#endif /* not DOS_NT */
093650fe 651
80856e74
JB
652 record_unwind_protect (delete_temp_file, filename_string);
653
012c6fcb 654 if (!NILP (args[3]))
80856e74
JB
655 Fdelete_region (start, end);
656
657 args[3] = filename_string;
80856e74 658
39323a7e 659 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs - 2, args + 2)));
80856e74
JB
660}
661\f
662#ifndef VMS /* VMS version is in vmsproc.c. */
663
664/* This is the last thing run in a newly forked inferior
665 either synchronous or asynchronous.
666 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
667 Initialize inferior's priority, pgrp, connected dir and environment.
668 then exec another program based on new_argv.
669
670 This function may change environ for the superior process.
671 Therefore, the superior process must save and restore the value
672 of environ around the vfork and the call to this function.
673
674 ENV is the environment for the subprocess.
675
676 SET_PGRP is nonzero if we should put the subprocess into a separate
e576cab4
JB
677 process group.
678
679 CURRENT_DIR is an elisp string giving the path of the current
680 directory the subprocess should have. Since we can't really signal
681 a decent error from within the child, this should be verified as an
682 executable directory by the parent. */
80856e74 683
e576cab4 684child_setup (in, out, err, new_argv, set_pgrp, current_dir)
80856e74
JB
685 int in, out, err;
686 register char **new_argv;
80856e74 687 int set_pgrp;
e576cab4 688 Lisp_Object current_dir;
80856e74 689{
7e6c2178
RS
690#ifdef MSDOS
691 /* The MSDOS port of gcc cannot fork, vfork, ... so we must call system
692 instead. */
693#else /* not MSDOS */
e576cab4 694 char **env;
7fcf7f05 695 char *pwd_var;
bad95d8f
RS
696#ifdef WINDOWSNT
697 int cpid;
698 HANDLE handles[4];
699#endif /* WINDOWSNT */
e576cab4 700
33abe2d9 701 int pid = getpid ();
80856e74 702
68d10241 703#ifdef SET_EMACS_PRIORITY
4f0b9d49
JB
704 {
705 extern int emacs_priority;
706
68d10241
RS
707 if (emacs_priority < 0)
708 nice (- emacs_priority);
4f0b9d49 709 }
5b633aeb 710#endif
80856e74
JB
711
712#ifdef subprocesses
713 /* Close Emacs's descriptors that this process should not have. */
714 close_process_descs ();
715#endif
4458cebe 716 close_load_descs ();
80856e74
JB
717
718 /* Note that use of alloca is always safe here. It's obvious for systems
719 that do not have true vfork or that have true (stack) alloca.
720 If using vfork and C_ALLOCA it is safe because that changes
721 the superior's static variables as if the superior had done alloca
722 and will be cleaned up in the usual way. */
e576cab4 723 {
7fcf7f05 724 register char *temp;
e576cab4 725 register int i;
77d78be1 726
e576cab4 727 i = XSTRING (current_dir)->size;
7fcf7f05
RS
728 pwd_var = (char *) alloca (i + 6);
729 temp = pwd_var + 4;
730 bcopy ("PWD=", pwd_var, 4);
e576cab4 731 bcopy (XSTRING (current_dir)->data, temp, i);
bad95d8f 732 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
e576cab4
JB
733 temp[i] = 0;
734
735 /* We can't signal an Elisp error here; we're in a vfork. Since
736 the callers check the current directory before forking, this
737 should only return an error if the directory's permissions
738 are changed between the check and this chdir, but we should
739 at least check. */
740 if (chdir (temp) < 0)
20b25e46 741 _exit (errno);
7fcf7f05
RS
742
743 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
bad95d8f 744 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
7fcf7f05 745 temp[--i] = 0;
e576cab4 746 }
80856e74 747
80856e74
JB
748 /* Set `env' to a vector of the strings in Vprocess_environment. */
749 {
750 register Lisp_Object tem;
751 register char **new_env;
752 register int new_length;
753
754 new_length = 0;
755 for (tem = Vprocess_environment;
d50d3dc8 756 CONSP (tem) && STRINGP (XCONS (tem)->car);
80856e74
JB
757 tem = XCONS (tem)->cdr)
758 new_length++;
759
7fcf7f05
RS
760 /* new_length + 2 to include PWD and terminating 0. */
761 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
762
763 /* If we have a PWD envvar, pass one down,
764 but with corrected value. */
765 if (getenv ("PWD"))
766 *new_env++ = pwd_var;
80856e74 767
cd9565ba 768 /* Copy the Vprocess_environment strings into new_env. */
80856e74 769 for (tem = Vprocess_environment;
d50d3dc8 770 CONSP (tem) && STRINGP (XCONS (tem)->car);
80856e74 771 tem = XCONS (tem)->cdr)
cd9565ba
RS
772 {
773 char **ep = env;
774 char *string = (char *) XSTRING (XCONS (tem)->car)->data;
775 /* See if this string duplicates any string already in the env.
776 If so, don't put it in.
777 When an env var has multiple definitions,
778 we keep the definition that comes first in process-environment. */
779 for (; ep != new_env; ep++)
780 {
781 char *p = *ep, *q = string;
782 while (1)
783 {
784 if (*q == 0)
785 /* The string is malformed; might as well drop it. */
786 goto duplicate;
787 if (*q != *p)
788 break;
789 if (*q == '=')
790 goto duplicate;
791 p++, q++;
792 }
793 }
794 *new_env++ = string;
795 duplicate: ;
796 }
80856e74
JB
797 *new_env = 0;
798 }
bad95d8f
RS
799#ifdef WINDOWSNT
800 prepare_standard_handles (in, out, err, handles);
801#else /* not WINDOWSNT */
426b37ae
JB
802 /* Make sure that in, out, and err are not actually already in
803 descriptors zero, one, or two; this could happen if Emacs is
7e6c2178 804 started with its standard in, out, or error closed, as might
426b37ae
JB
805 happen under X. */
806 in = relocate_fd (in, 3);
3e9367e7
KH
807 if (out == err)
808 err = out = relocate_fd (out, 3);
809 else
810 {
811 out = relocate_fd (out, 3);
812 err = relocate_fd (err, 3);
813 }
426b37ae 814
80856e74
JB
815 close (0);
816 close (1);
817 close (2);
818
819 dup2 (in, 0);
820 dup2 (out, 1);
821 dup2 (err, 2);
822 close (in);
823 close (out);
824 close (err);
bad95d8f 825#endif /* not WINDOWSNT */
80856e74 826
fdba8590
RS
827#ifdef USG
828#ifndef SETPGRP_RELEASES_CTTY
e576cab4 829 setpgrp (); /* No arguments but equivalent in this case */
fdba8590 830#endif
e576cab4
JB
831#else
832 setpgrp (pid, pid);
833#endif /* USG */
a129418f
RS
834 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
835 EMACS_SET_TTY_PGRP (0, &pid);
80856e74
JB
836
837#ifdef vipc
838 something missing here;
839#endif /* vipc */
840
bad95d8f
RS
841#ifdef WINDOWSNT
842 /* Spawn the child. (See ntproc.c:Spawnve). */
843 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
ff27bfbe
KH
844 if (cpid == -1)
845 /* An error occurred while trying to spawn the process. */
846 report_file_error ("Spawning child process", Qnil);
bad95d8f
RS
847 reset_standard_handles (in, out, err, handles);
848 return cpid;
849#else /* not WINDOWSNT */
80856e74
JB
850 /* execvp does not accept an environment arg so the only way
851 to pass this environment is to set environ. Our caller
852 is responsible for restoring the ambient value of environ. */
853 environ = env;
854 execvp (new_argv[0], new_argv);
855
d20b8af6 856 write (1, "Can't exec program: ", 26);
80856e74 857 write (1, new_argv[0], strlen (new_argv[0]));
d20b8af6 858 write (1, "\n", 1);
80856e74 859 _exit (1);
bad95d8f 860#endif /* not WINDOWSNT */
7e6c2178 861#endif /* not MSDOS */
80856e74
JB
862}
863
426b37ae
JB
864/* Move the file descriptor FD so that its number is not less than MIN.
865 If the file descriptor is moved at all, the original is freed. */
866int
867relocate_fd (fd, min)
868 int fd, min;
869{
870 if (fd >= min)
871 return fd;
872 else
873 {
874 int new = dup (fd);
875 if (new == -1)
876 {
20c018a0 877 char *message1 = "Error while setting up child: ";
826c56ac 878 char *errmessage = strerror (errno);
20c018a0
JB
879 char *message2 = "\n";
880 write (2, message1, strlen (message1));
826c56ac 881 write (2, errmessage, strlen (errmessage));
20c018a0 882 write (2, message2, strlen (message2));
426b37ae
JB
883 _exit (1);
884 }
885 /* Note that we hold the original FD open while we recurse,
886 to guarantee we'll get a new FD if we need it. */
887 new = relocate_fd (new, min);
888 close (fd);
889 return new;
890 }
891}
892
012c6fcb
JA
893static int
894getenv_internal (var, varlen, value, valuelen)
895 char *var;
896 int varlen;
897 char **value;
898 int *valuelen;
899{
900 Lisp_Object scan;
901
902 for (scan = Vprocess_environment; CONSP (scan); scan = XCONS (scan)->cdr)
903 {
c1350752
KH
904 Lisp_Object entry;
905
906 entry = XCONS (scan)->car;
d50d3dc8 907 if (STRINGP (entry)
012c6fcb
JA
908 && XSTRING (entry)->size > varlen
909 && XSTRING (entry)->data[varlen] == '='
bad95d8f
RS
910#ifdef WINDOWSNT
911 /* NT environment variables are case insensitive. */
a9971c6d 912 && ! strnicmp (XSTRING (entry)->data, var, varlen)
bad95d8f 913#else /* not WINDOWSNT */
a9971c6d 914 && ! bcmp (XSTRING (entry)->data, var, varlen)
bad95d8f 915#endif /* not WINDOWSNT */
a9971c6d 916 )
012c6fcb
JA
917 {
918 *value = (char *) XSTRING (entry)->data + (varlen + 1);
919 *valuelen = XSTRING (entry)->size - (varlen + 1);
920 return 1;
921 }
922 }
923
924 return 0;
925}
926
0ad477db 927DEFUN ("getenv", Fgetenv, Sgetenv, 1, 1, 0,
012c6fcb
JA
928 "Return the value of environment variable VAR, as a string.\n\
929VAR should be a string. Value is nil if VAR is undefined in the environment.\n\
930This function consults the variable ``process-environment'' for its value.")
931 (var)
932 Lisp_Object var;
933{
934 char *value;
935 int valuelen;
936
937 CHECK_STRING (var, 0);
938 if (getenv_internal (XSTRING (var)->data, XSTRING (var)->size,
939 &value, &valuelen))
940 return make_string (value, valuelen);
941 else
942 return Qnil;
943}
944
945/* A version of getenv that consults process_environment, easily
e576cab4 946 callable from C. */
012c6fcb
JA
947char *
948egetenv (var)
e576cab4 949 char *var;
012c6fcb
JA
950{
951 char *value;
952 int valuelen;
953
954 if (getenv_internal (var, strlen (var), &value, &valuelen))
955 return value;
956 else
957 return 0;
958}
959
80856e74
JB
960#endif /* not VMS */
961\f
8de15d69 962/* This is run before init_cmdargs. */
7e6c2178 963
8de15d69
RS
964init_callproc_1 ()
965{
966 char *data_dir = egetenv ("EMACSDATA");
35a2f4b8
KH
967 char *doc_dir = egetenv ("EMACSDOC");
968
8de15d69 969 Vdata_directory
7e6c2178 970 = Ffile_name_as_directory (build_string (data_dir ? data_dir
8de15d69 971 : PATH_DATA));
35a2f4b8
KH
972 Vdoc_directory
973 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
974 : PATH_DOC));
9453ea7b 975
e576cab4
JB
976 /* Check the EMACSPATH environment variable, defaulting to the
977 PATH_EXEC path from paths.h. */
978 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
80856e74
JB
979 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
980 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
8de15d69
RS
981}
982
983/* This is run after init_cmdargs, so that Vinvocation_directory is valid. */
984
985init_callproc ()
986{
987 char *data_dir = egetenv ("EMACSDATA");
988
989 register char * sh;
990 Lisp_Object tempdir;
991
05630743 992 if (initialized && !NILP (Vinstallation_directory))
8de15d69 993 {
05630743
RS
994 /* Add to the path the lib-src subdir of the installation dir. */
995 Lisp_Object tem;
996 tem = Fexpand_file_name (build_string ("lib-src"),
997 Vinstallation_directory);
998 if (NILP (Fmember (tem, Vexec_path)))
8de15d69 999 {
bad95d8f 1000#ifndef DOS_NT
1a6640ec 1001 /* MSDOS uses wrapped binaries, so don't do this. */
8de15d69
RS
1002 Vexec_path = nconc2 (Vexec_path, Fcons (tem, Qnil));
1003 Vexec_directory = Ffile_name_as_directory (tem);
bad95d8f 1004#endif /* not DOS_NT */
8de15d69
RS
1005
1006 /* If we use ../lib-src, maybe use ../etc as well.
1007 Do so if ../etc exists and has our DOC-... file in it. */
1008 if (data_dir == 0)
1009 {
05630743
RS
1010 tem = Fexpand_file_name (build_string ("etc"),
1011 Vinstallation_directory);
7e933683 1012 Vdoc_directory = Ffile_name_as_directory (tem);
8de15d69
RS
1013 }
1014 }
1015 }
7e933683
RS
1016
1017 /* Look for the files that should be in etc. We don't use
1018 Vinstallation_directory, because these files are never installed
1019 in /bin near the executable, and they are never in the build
1020 directory when that's different from the source directory.
1021
1022 Instead, if these files are not in the nominal place, we try the
1023 source directory. */
1024 if (data_dir == 0)
1025 {
1026 Lisp_Object tem, tem1, newdir;
1027
1028 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1029 tem1 = Ffile_exists_p (tem);
1030 if (NILP (tem1))
1031 {
1032 newdir = Fexpand_file_name (build_string ("../etc/"),
1033 build_string (PATH_DUMPLOADSEARCH));
1034 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1035 tem1 = Ffile_exists_p (tem);
1036 if (!NILP (tem1))
1037 Vdata_directory = newdir;
1038 }
1039 }
80856e74 1040
e576cab4
JB
1041 tempdir = Fdirectory_file_name (Vexec_directory);
1042 if (access (XSTRING (tempdir)->data, 0) < 0)
80856e74 1043 {
0af6a831
RS
1044 fprintf (stderr,
1045 "Warning: arch-dependent data dir (%s) does not exist.\n",
1046 XSTRING (Vexec_directory)->data);
80856e74
JB
1047 sleep (2);
1048 }
1049
e576cab4
JB
1050 tempdir = Fdirectory_file_name (Vdata_directory);
1051 if (access (XSTRING (tempdir)->data, 0) < 0)
1052 {
0af6a831
RS
1053 fprintf (stderr,
1054 "Warning: arch-independent data dir (%s) does not exist.\n",
1055 XSTRING (Vdata_directory)->data);
e576cab4
JB
1056 sleep (2);
1057 }
1058
80856e74
JB
1059#ifdef VMS
1060 Vshell_file_name = build_string ("*dcl*");
1061#else
e576cab4 1062 sh = (char *) getenv ("SHELL");
80856e74
JB
1063 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1064#endif
9fefd2ba
JB
1065}
1066
1067set_process_environment ()
1068{
1069 register char **envp;
80856e74 1070
80856e74
JB
1071 Vprocess_environment = Qnil;
1072#ifndef CANNOT_DUMP
1073 if (initialized)
1074#endif
1075 for (envp = environ; *envp; envp++)
1076 Vprocess_environment = Fcons (build_string (*envp),
1077 Vprocess_environment);
80856e74
JB
1078}
1079
1080syms_of_callproc ()
1081{
bad95d8f 1082#ifdef DOS_NT
093650fe
RS
1083 Qbuffer_file_type = intern ("buffer-file-type");
1084 staticpro (&Qbuffer_file_type);
1085
1086 DEFVAR_LISP ("binary-process-input", &Vbinary_process_input,
1087 "*If non-nil then new subprocesses are assumed to take binary input.");
1088 Vbinary_process_input = Qnil;
1089
1090 DEFVAR_LISP ("binary-process-output", &Vbinary_process_output,
7e6c2178 1091 "*If non-nil then new subprocesses are assumed to produce binary output.");
093650fe 1092 Vbinary_process_output = Qnil;
bad95d8f 1093#endif /* DOS_NT */
7e6c2178 1094
80856e74
JB
1095 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
1096 "*File name to load inferior shells from.\n\
1097Initialized from the SHELL environment variable.");
1098
1099 DEFVAR_LISP ("exec-path", &Vexec_path,
1100 "*List of directories to search programs to run in subprocesses.\n\
1101Each element is a string (directory name) or nil (try default directory).");
1102
1103 DEFVAR_LISP ("exec-directory", &Vexec_directory,
e576cab4
JB
1104 "Directory of architecture-dependent files that come with GNU Emacs,\n\
1105especially executable programs intended for Emacs to invoke.");
1106
1107 DEFVAR_LISP ("data-directory", &Vdata_directory,
1108 "Directory of architecture-independent files that come with GNU Emacs,\n\
1109intended for Emacs to use.");
80856e74 1110
35a2f4b8
KH
1111 DEFVAR_LISP ("doc-directory", &Vdoc_directory,
1112 "Directory containing the DOC file that comes with GNU Emacs.\n\
1113This is usually the same as data-directory.");
1114
ed61592a
JB
1115 DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
1116 "For internal use by the build procedure only.\n\
1117This is the name of the directory in which the build procedure installed\n\
1118Emacs's info files; the default value for Info-default-directory-list\n\
1119includes this.");
1120 Vconfigure_info_directory = build_string (PATH_INFO);
1121
80856e74 1122 DEFVAR_LISP ("process-environment", &Vprocess_environment,
e576cab4
JB
1123 "List of environment variables for subprocesses to inherit.\n\
1124Each element should be a string of the form ENVVARNAME=VALUE.\n\
1125The environment which Emacs inherits is placed in this variable\n\
1126when Emacs starts.");
80856e74
JB
1127
1128#ifndef VMS
1129 defsubr (&Scall_process);
012c6fcb 1130 defsubr (&Sgetenv);
986ffb24 1131#endif
e576cab4 1132 defsubr (&Scall_process_region);
80856e74 1133}