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