entered into RCS
[bpt/emacs.git] / src / callproc.c
CommitLineData
80856e74 1/* Synchronous subprocess invocation for GNU Emacs.
91bac16a 2 Copyright (C) 1985, 1986, 1987, 1988, 1992 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
8the Free Software Foundation; either version 1, or (at your option)
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>
77d78be1 22#include <errno.h>
80856e74
JB
23
24#include "config.h"
25
26/* Define SIGCHLD as an alias for SIGCLD. */
27
28#if !defined (SIGCHLD) && defined (SIGCLD)
29#define SIGCHLD SIGCLD
30#endif /* SIGCLD */
31
32#include <sys/types.h>
33#define PRIO_PROCESS 0
34#include <sys/file.h>
35#ifdef USG5
36#include <fcntl.h>
37#endif
38
39#ifndef O_RDONLY
40#define O_RDONLY 0
41#endif
42
43#ifndef O_WRONLY
44#define O_WRONLY 1
45#endif
46
47#include "lisp.h"
48#include "commands.h"
49#include "buffer.h"
50#include "paths.h"
51#include "process.h"
52
53#ifdef VMS
54extern noshare char **environ;
55#else
56extern char **environ;
57#endif
58
59#define max(a, b) ((a) > (b) ? (a) : (b))
60
9453ea7b 61Lisp_Object Vexec_path, Vexec_directory, Vdata_directory;
80856e74
JB
62
63Lisp_Object Vshell_file_name;
64
80856e74 65Lisp_Object Vprocess_environment;
80856e74
JB
66
67/* True iff we are about to fork off a synchronous process or if we
68 are waiting for it. */
69int synch_process_alive;
70
71/* Nonzero => this is a string explaining death of synchronous subprocess. */
72char *synch_process_death;
73
74/* If synch_process_death is zero,
75 this is exit code of synchronous subprocess. */
76int synch_process_retcode;
77\f
78#ifndef VMS /* VMS version is in vmsproc.c. */
79
80Lisp_Object
81call_process_cleanup (fdpid)
82 Lisp_Object fdpid;
83{
84 register Lisp_Object fd, pid;
85 fd = Fcar (fdpid);
86 pid = Fcdr (fdpid);
87 close (XFASTINT (fd));
88 kill (XFASTINT (pid), SIGKILL);
89 synch_process_alive = 0;
90 return Qnil;
91}
92
93DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
94 "Call PROGRAM synchronously in separate process.\n\
95The program's input comes from file INFILE (nil means `/dev/null').\n\
96Insert output in BUFFER before point; t means current buffer;\n\
97 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
98Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
99Remaining arguments are strings passed as command arguments to PROGRAM.\n\
100If BUFFER is nil or 0, returns immediately with value nil.\n\
101Otherwise waits for PROGRAM to terminate\n\
102and returns a numeric exit status or a signal name as a string.\n\
103If you quit, the process is killed with SIGKILL.")
104 (nargs, args)
105 int nargs;
106 register Lisp_Object *args;
107{
77d78be1 108 Lisp_Object display, infile, buffer, path, current_dir;
80856e74
JB
109 int fd[2];
110 int filefd;
111 register int pid;
112 char buf[1024];
113 int count = specpdl_ptr - specpdl;
114 register unsigned char **new_argv
115 = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
116 struct buffer *old = current_buffer;
117#if 0
118 int mask;
119#endif
80856e74
JB
120 CHECK_STRING (args[0], 0);
121
77d78be1
JB
122 if (nargs >= 2 && ! NILP (args[1]))
123 {
124 infile = Fexpand_file_name (args[1], current_buffer->directory);
125 CHECK_STRING (infile, 1);
126 }
80856e74 127 else
77d78be1 128 infile = build_string ("/dev/null");
80856e74
JB
129
130 {
131 register Lisp_Object tem;
77d78be1 132 if (nargs < 3)
80856e74 133 buffer = Qnil;
77d78be1 134 else
80856e74 135 {
77d78be1
JB
136 buffer = tem = args[2];
137 if (!(EQ (tem, Qnil) || EQ (tem, Qt)
138 || XFASTINT (tem) == 0))
139 {
140 buffer = Fget_buffer (tem);
141 CHECK_BUFFER (buffer, 2);
142 }
80856e74
JB
143 }
144 }
145
146 display = nargs >= 3 ? args[3] : Qnil;
147
148 {
149 register int i;
150 for (i = 4; i < nargs; i++)
151 {
152 CHECK_STRING (args[i], i);
153 new_argv[i - 3] = XSTRING (args[i])->data;
154 }
155 /* Program name is first command arg */
156 new_argv[0] = XSTRING (args[0])->data;
157 new_argv[i - 3] = 0;
158 }
159
77d78be1 160 filefd = open (XSTRING (infile)->data, O_RDONLY, 0);
80856e74
JB
161 if (filefd < 0)
162 {
77d78be1 163 report_file_error ("Opening process input file", Fcons (infile, Qnil));
80856e74
JB
164 }
165 /* Search for program; barf if not found. */
166 openp (Vexec_path, args[0], "", &path, 1);
efb859b4 167 if (NILP (path))
80856e74
JB
168 {
169 close (filefd);
170 report_file_error ("Searching for program", Fcons (args[0], Qnil));
171 }
172 new_argv[0] = XSTRING (path)->data;
173
174 if (XTYPE (buffer) == Lisp_Int)
175 fd[1] = open ("/dev/null", O_WRONLY), fd[0] = -1;
176 else
177 {
178 pipe (fd);
179#if 0
180 /* Replaced by close_process_descs */
181 set_exclusive_use (fd[0]);
182#endif
183 }
184
77d78be1
JB
185 /* Make sure that the child will be able to chdir to the current
186 buffer's current directory. We can't just have the child check
187 for an error when it does the chdir, since it's in a vfork. */
188 current_dir = expand_and_dir_to_file (current_buffer->directory, Qnil);
189 if (NILP (Ffile_accessible_directory_p (current_dir)))
190 report_file_error ("Setting current directory",
191 Fcons (current_buffer->directory, Qnil));
192
80856e74
JB
193 {
194 /* child_setup must clobber environ in systems with true vfork.
195 Protect it from permanent change. */
196 register char **save_environ = environ;
197 register int fd1 = fd[1];
198 char **env;
199
80856e74 200 env = environ;
80856e74
JB
201
202#if 0 /* Some systems don't have sigblock. */
4746118a 203 EMACS_SIGBLOCK (sigmask (SIGCHLD), mask);
80856e74
JB
204#endif
205
206 /* Record that we're about to create a synchronous process. */
207 synch_process_alive = 1;
208
209 pid = vfork ();
210
211 if (pid == 0)
212 {
213 if (fd[0] >= 0)
214 close (fd[0]);
215#ifdef USG
216 setpgrp ();
217#else
218 setpgrp (pid, pid);
219#endif /* USG */
77d78be1 220 child_setup (filefd, fd1, fd1, new_argv, env, 0, current_dir);
80856e74
JB
221 }
222
223#if 0
224 /* Tell SIGCHLD handler to look for this pid. */
225 synch_process_pid = pid;
226 /* Now let SIGCHLD come through. */
32676c08
JB
227 {
228 int dummy;
229
230 EMACS_SIGSETMASK (mask, dummy);
231 }
80856e74
JB
232#endif
233
234 environ = save_environ;
235
236 close (filefd);
237 close (fd1);
238 }
239
240 if (pid < 0)
241 {
242 close (fd[0]);
243 report_file_error ("Doing vfork", Qnil);
244 }
245
246 if (XTYPE (buffer) == Lisp_Int)
247 {
248#ifndef subprocesses
8cf9a8c6
JB
249 /* If Emacs has been built with asynchronous subprocess support,
250 we don't need to do this, I think because it will then have
251 the facilities for handling SIGCHLD. */
80856e74
JB
252 wait_without_blocking ();
253#endif /* subprocesses */
80856e74
JB
254 return Qnil;
255 }
256
b5752bd1
JB
257 synch_process_death = 0;
258 synch_process_retcode = 0;
259
80856e74
JB
260 record_unwind_protect (call_process_cleanup,
261 Fcons (make_number (fd[0]), make_number (pid)));
262
263
264 if (XTYPE (buffer) == Lisp_Buffer)
265 Fset_buffer (buffer);
266
267 immediate_quit = 1;
268 QUIT;
269
270 {
271 register int nread;
272
273 while ((nread = read (fd[0], buf, sizeof buf)) > 0)
274 {
275 immediate_quit = 0;
efb859b4 276 if (!NILP (buffer))
80856e74 277 insert (buf, nread);
efb859b4 278 if (!NILP (display) && INTERACTIVE)
80856e74
JB
279 redisplay_preserve_echo_area ();
280 immediate_quit = 1;
281 QUIT;
282 }
283 }
284
285 /* Wait for it to terminate, unless it already has. */
286 wait_for_termination (pid);
287
288 immediate_quit = 0;
289
290 set_buffer_internal (old);
291
292 unbind_to (count, Qnil);
293
80856e74
JB
294 if (synch_process_death)
295 return build_string (synch_process_death);
296 return make_number (synch_process_retcode);
297}
298#endif
299\f
300static void
301delete_temp_file (name)
302 Lisp_Object name;
303{
304 unlink (XSTRING (name)->data);
305}
306
307DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
308 3, MANY, 0,
309 "Send text from START to END to a synchronous process running PROGRAM.\n\
310Delete the text if fourth arg DELETE is non-nil.\n\
311Insert output in BUFFER before point; t means current buffer;\n\
312 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
313Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
314Remaining args are passed to PROGRAM at startup as command args.\n\
315If BUFFER is nil, returns immediately with value nil.\n\
316Otherwise waits for PROGRAM to terminate\n\
317and returns a numeric exit status or a signal name as a string.\n\
318If you quit, the process is killed with SIGKILL.")
319 (nargs, args)
320 int nargs;
321 register Lisp_Object *args;
322{
323 register Lisp_Object filename_string, start, end;
324 char tempfile[20];
325 int count = specpdl_ptr - specpdl;
80856e74
JB
326
327#ifdef VMS
328 strcpy (tempfile, "tmp:emacsXXXXXX.");
329#else
330 strcpy (tempfile, "/tmp/emacsXXXXXX");
331#endif
332 mktemp (tempfile);
333
334 filename_string = build_string (tempfile);
335 start = args[0];
336 end = args[1];
337 Fwrite_region (start, end, filename_string, Qnil, Qlambda);
338 record_unwind_protect (delete_temp_file, filename_string);
339
efb859b4 340 if (!NILP (args[3]))
80856e74
JB
341 Fdelete_region (start, end);
342
343 args[3] = filename_string;
344 Fcall_process (nargs - 2, args + 2);
345
80856e74
JB
346 return unbind_to (count, Qnil);
347}
348\f
349#ifndef VMS /* VMS version is in vmsproc.c. */
350
351/* This is the last thing run in a newly forked inferior
352 either synchronous or asynchronous.
353 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
354 Initialize inferior's priority, pgrp, connected dir and environment.
355 then exec another program based on new_argv.
356
357 This function may change environ for the superior process.
358 Therefore, the superior process must save and restore the value
359 of environ around the vfork and the call to this function.
360
361 ENV is the environment for the subprocess.
362
363 SET_PGRP is nonzero if we should put the subprocess into a separate
77d78be1
JB
364 process group.
365
366 CURRENT_DIR is an elisp string giving the path of the current
367 directory the subprocess should have. Since we can't really signal
368 a decent error from within the child, this should be verified as an
369 executable directory by the parent. */
80856e74 370
77d78be1 371child_setup (in, out, err, new_argv, env, set_pgrp, current_dir)
80856e74
JB
372 int in, out, err;
373 register char **new_argv;
374 char **env;
375 int set_pgrp;
77d78be1 376 Lisp_Object current_dir;
80856e74
JB
377{
378 register int pid = getpid();
379
380 setpriority (PRIO_PROCESS, pid, 0);
381
382#ifdef subprocesses
383 /* Close Emacs's descriptors that this process should not have. */
384 close_process_descs ();
385#endif
386
387 /* Note that use of alloca is always safe here. It's obvious for systems
388 that do not have true vfork or that have true (stack) alloca.
389 If using vfork and C_ALLOCA it is safe because that changes
390 the superior's static variables as if the superior had done alloca
391 and will be cleaned up in the usual way. */
77d78be1
JB
392 {
393 register unsigned char *temp;
394 register int i;
395
396 i = XSTRING (current_dir)->size;
397 temp = (unsigned char *) alloca (i + 2);
398 bcopy (XSTRING (current_dir)->data, temp, i);
399 if (temp[i - 1] != '/') temp[i++] = '/';
400 temp[i] = 0;
401
402 /* We can't signal an Elisp error here; we're in a vfork. Since
403 the callers check the current directory before forking, this
404 should only return an error if the directory's permissions
405 are changed between the check and this chdir, but we should
406 at least check. */
407 if (chdir (temp) < 0)
408 exit (errno);
409 }
80856e74 410
80856e74
JB
411 /* Set `env' to a vector of the strings in Vprocess_environment. */
412 {
413 register Lisp_Object tem;
414 register char **new_env;
415 register int new_length;
416
417 new_length = 0;
418 for (tem = Vprocess_environment;
419 (XTYPE (tem) == Lisp_Cons
420 && XTYPE (XCONS (tem)->car) == Lisp_String);
421 tem = XCONS (tem)->cdr)
422 new_length++;
423
424 /* new_length + 1 to include terminating 0 */
425 env = new_env = (char **) alloca ((new_length + 1) * sizeof (char *));
426
427 /* Copy the env strings into new_env. */
428 for (tem = Vprocess_environment;
429 (XTYPE (tem) == Lisp_Cons
430 && XTYPE (XCONS (tem)->car) == Lisp_String);
431 tem = XCONS (tem)->cdr)
432 *new_env++ = (char *) XSTRING (XCONS (tem)->car)->data;
433 *new_env = 0;
434 }
80856e74
JB
435
436 close (0);
437 close (1);
438 close (2);
439
440 dup2 (in, 0);
441 dup2 (out, 1);
442 dup2 (err, 2);
443 close (in);
444 close (out);
445 close (err);
446
91bac16a
JB
447#ifdef USG
448 setpgrp (); /* No arguments but equivalent in this case */
449#else
450 setpgrp (pid, pid);
451#endif /* USG */
80856e74
JB
452 setpgrp_of_tty (pid);
453
454#ifdef vipc
455 something missing here;
456#endif /* vipc */
457
458 /* execvp does not accept an environment arg so the only way
459 to pass this environment is to set environ. Our caller
460 is responsible for restoring the ambient value of environ. */
461 environ = env;
462 execvp (new_argv[0], new_argv);
463
464 write (1, "Couldn't exec the program ", 26);
465 write (1, new_argv[0], strlen (new_argv[0]));
466 _exit (1);
467}
468
efb859b4
JB
469static int
470getenv_internal (var, varlen, value, valuelen)
471 char *var;
472 int varlen;
473 char **value;
77d78be1 474 int *valuelen;
efb859b4
JB
475{
476 Lisp_Object scan;
477
478 for (scan = Vprocess_environment; CONSP (scan); scan = XCONS (scan)->cdr)
479 {
480 Lisp_Object entry = XCONS (scan)->car;
481
482 if (XTYPE (entry) == Lisp_String
483 && XSTRING (entry)->size > varlen
484 && XSTRING (entry)->data[varlen] == '='
485 && ! bcmp (XSTRING (entry)->data, var, varlen))
486 {
77d78be1 487 *value = (char *) XSTRING (entry)->data + (varlen + 1);
efb859b4
JB
488 *valuelen = XSTRING (entry)->size - (varlen + 1);
489 return 1;
490 }
491 }
492
493 return 0;
494}
495
496DEFUN ("getenv", Fgetenv, Sgetenv, 1, 2, 0,
497 "Return the value of environment variable VAR, as a string.\n\
498VAR should be a string. Value is nil if VAR is undefined in the environment.\n\
499This function consults the variable ``process-environment'' for its value.")
500 (var)
501 Lisp_Object var;
502{
503 char *value;
504 int valuelen;
505
506 CHECK_STRING (var, 0);
507 if (getenv_internal (XSTRING (var)->data, XSTRING (var)->size,
508 &value, &valuelen))
509 return make_string (value, valuelen);
510 else
511 return Qnil;
512}
513
514/* A version of getenv that consults process_environment, easily
515 callable from C. */
516char *
517egetenv (var)
4746118a 518 char *var;
efb859b4
JB
519{
520 char *value;
521 int valuelen;
522
523 if (getenv_internal (var, strlen (var), &value, &valuelen))
524 return value;
525 else
526 return 0;
527}
528
80856e74
JB
529#endif /* not VMS */
530\f
531init_callproc ()
532{
533 register char * sh;
534 register char **envp;
9453ea7b
JB
535 Lisp_Object tempdir;
536
32676c08
JB
537 {
538 char *data_dir = egetenv ("EMACSDATA");
539
540 Vdata_directory =
541 Ffile_name_as_directory
542 (build_string (data_dir ? data_dir : PATH_DATA));
543 }
80856e74 544
32676c08
JB
545 /* Check the EMACSPATH environment variable, defaulting to the
546 PATH_EXEC path from paths.h. */
547 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
80856e74
JB
548 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
549 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
550
9453ea7b
JB
551 tempdir = Fdirectory_file_name (Vexec_directory);
552 if (access (XSTRING (tempdir)->data, 0) < 0)
80856e74 553 {
9453ea7b 554 printf ("Warning: arch-dependent data dir (%s) does not exist.\n",
80856e74
JB
555 XSTRING (Vexec_directory)->data);
556 sleep (2);
557 }
558
9453ea7b
JB
559 tempdir = Fdirectory_file_name (Vdata_directory);
560 if (access (XSTRING (tempdir)->data, 0) < 0)
561 {
562 printf ("Warning: arch-independent data dir (%s) does not exist.\n",
563 XSTRING (Vdata_directory)->data);
564 sleep (2);
565 }
566
80856e74
JB
567#ifdef VMS
568 Vshell_file_name = build_string ("*dcl*");
569#else
efb859b4 570 sh = (char *) getenv ("SHELL");
80856e74
JB
571 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
572#endif
573
80856e74
JB
574 Vprocess_environment = Qnil;
575#ifndef CANNOT_DUMP
576 if (initialized)
577#endif
578 for (envp = environ; *envp; envp++)
579 Vprocess_environment = Fcons (build_string (*envp),
580 Vprocess_environment);
80856e74
JB
581}
582
583syms_of_callproc ()
584{
585 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
586 "*File name to load inferior shells from.\n\
587Initialized from the SHELL environment variable.");
588
589 DEFVAR_LISP ("exec-path", &Vexec_path,
590 "*List of directories to search programs to run in subprocesses.\n\
591Each element is a string (directory name) or nil (try default directory).");
592
593 DEFVAR_LISP ("exec-directory", &Vexec_directory,
9453ea7b
JB
594 "Directory of architecture-dependent files that come with GNU Emacs,\n\
595especially executable programs intended for Emacs to invoke.");
596
597 DEFVAR_LISP ("data-directory", &Vdata_directory,
598 "Directory of architecture-independent files that come with GNU Emacs,\n\
599intended for Emacs to use.");
80856e74 600
80856e74 601 DEFVAR_LISP ("process-environment", &Vprocess_environment,
efb859b4
JB
602 "List of environment variables for subprocesses to inherit.\n\
603Each element should be a string of the form ENVVARNAME=VALUE.\n\
604The environment which Emacs inherits is placed in this variable\n\
605when Emacs starts.");
80856e74
JB
606
607#ifndef VMS
608 defsubr (&Scall_process);
609#endif
efb859b4 610 defsubr (&Sgetenv);
80856e74
JB
611 defsubr (&Scall_process_region);
612}