Partially sync files.el from XEmacs 21.5 for wildcard support.
[sxemacs] / src / callproc.c
1 /* Old synchronous subprocess invocation for SXEmacs.
2    Copyright (C) 1985, 86, 87, 88, 93, 94, 95 Free Software Foundation, Inc.
3
4 This file is part of SXEmacs
5
6 SXEmacs 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 3 of the License, or
9 (at your option) any later version.
10
11 SXEmacs 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 this program.  If not, see <http://www.gnu.org/licenses/>. */
18
19
20 /* Synched up with: Mule 2.0, FSF 19.30. */
21 /* Partly sync'ed with 19.36.4 */
22
23 /* #### This ENTIRE file is only used in batch mode.
24
25    We only need two things to get rid of both this and ntproc.c:
26
27    -- my `stderr-proc' ws, which adds support for a separate stderr
28       in asynch. subprocesses. (it's a feature in `old-call-process-internal'.)
29    -- a noninteractive event loop that supports processes.
30 */
31
32 #include <config.h>
33 #include "lisp.h"
34
35 #include "buffer.h"
36 #include "commands.h"
37 #include "ui/insdel.h"
38 #include "lstream.h"
39 #include "process.h"
40 #include "sysdep.h"
41 #include "ui/window.h"
42 #ifdef FILE_CODING
43 #include "mule/file-coding.h"
44 #endif
45
46 #include "systime.h"
47 #include "sysproc.h"
48 #include "sysfile.h"            /* Always include after sysproc.h */
49 #include "syssignal.h"          /* Always include before systty.h */
50 #include "ui/TTY/systty.h"
51
52
53
54 Lisp_Object Vshell_file_name;
55
56 /* The environment to pass to all subprocesses when they are started.
57    This is in the semi-bogus format of ("VAR=VAL" "VAR2=VAL2" ... )
58  */
59 Lisp_Object Vprocess_environment;
60
61 /* True iff we are about to fork off a synchronous process or if we
62    are waiting for it.  */
63 volatile int synch_process_alive;
64
65 /* Nonzero => this is a string explaining death of synchronous subprocess.  */
66 const char *synch_process_death;
67
68 /* If synch_process_death is zero,
69    this is exit code of synchronous subprocess.  */
70 int synch_process_retcode;
71 \f
72 /* Clean up when exiting Fcall_process_internal.
73    On Windows, delete the temporary file on any kind of termination.
74    On Unix, kill the process and any children on termination by signal.  */
75
76 /* Nonzero if this is termination due to exit.  */
77 static int call_process_exited;
78
79 Lisp_Object Vlisp_EXEC_SUFFIXES;
80
81 static Lisp_Object call_process_kill(Lisp_Object fdpid)
82 {
83         Lisp_Object fd = Fcar(fdpid);
84         Lisp_Object pid = Fcdr(fdpid);
85
86         if (!NILP(fd))
87                 close(XINT(fd));
88
89         if (!NILP(pid))
90                 EMACS_KILLPG(XINT(pid), SIGKILL);
91
92         synch_process_alive = 0;
93         return Qnil;
94 }
95
96 static Lisp_Object call_process_cleanup(Lisp_Object fdpid)
97 {
98         int fd = XINT(Fcar(fdpid));
99         int pid = XINT(Fcdr(fdpid));
100
101         if (!call_process_exited && EMACS_KILLPG(pid, SIGINT) == 0) {
102                 int speccount = specpdl_depth();
103
104                 record_unwind_protect(call_process_kill, fdpid);
105                 /* #### "c-G" -- need non-consing Single-key-description */
106                 message
107                     ("Waiting for process to die...(type C-g again to kill it instantly)");
108
109                 wait_for_termination(pid);
110
111                 /* "Discard" the unwind protect.  */
112                 XCAR(fdpid) = Qnil;
113                 XCDR(fdpid) = Qnil;
114                 unbind_to(speccount, Qnil);
115
116                 message("Waiting for process to die... done");
117         }
118         synch_process_alive = 0;
119         close(fd);
120         return Qnil;
121 }
122
123 static Lisp_Object fork_error;
124
125 DEFUN("old-call-process-internal", Fold_call_process_internal, 1, MANY, 0, /*
126 Call PROGRAM synchronously in separate process, with coding-system specified.
127 Arguments are
128 (PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS).
129 The program's input comes from file INFILE (nil means `/dev/null').
130 Insert output in BUFFER before point; t means current buffer;
131 nil for BUFFER means discard it; 0 means discard and don't wait.
132 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
133 REAL-BUFFER says what to do with standard output, as above,
134 while STDERR-FILE says what to do with standard error in the child.
135 STDERR-FILE may be nil (discard standard error output),
136 t (mix it with ordinary output), or a file name string.
137
138 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
139 Remaining arguments are strings passed as command arguments to PROGRAM.
140
141 If BUFFER is 0, `call-process' returns immediately with value nil.
142 Otherwise it waits for PROGRAM to terminate and returns a numeric exit status
143 or a signal description string.
144 If you quit, the process is killed with SIGINT, or SIGKILL if you
145 quit again.
146 */
147       (int nargs, Lisp_Object * args))
148 {
149         /* This function can GC */
150         Lisp_Object infile, buffer, current_dir, display, path;
151         int fd[2];
152         int filefd;
153         int pid;
154         char buf[16384];
155         char *bufptr = buf;
156         int bufsize = 16384;
157         int speccount = specpdl_depth();
158         struct gcpro gcpro1, gcpro2, gcpro3;
159         char **new_argv = alloca_array(char *, max(2, nargs - 2));
160
161         /* File to use for stderr in the child.
162            t means use same as standard output.  */
163         Lisp_Object error_file;
164
165         CHECK_STRING(args[0]);
166
167         error_file = Qt;
168
169 #if defined (NO_SUBPROCESSES)
170         /* Without asynchronous processes we cannot have BUFFER == 0.  */
171         if (nargs >= 3 && !INTP(args[2]))
172                 error
173                     ("Operating system cannot handle asynchronous subprocesses");
174 #endif                          /* NO_SUBPROCESSES */
175
176         /* Do this before building new_argv because GC in Lisp code
177          *  called by various filename-hacking routines might relocate strings */
178         locate_file(Vexec_path, args[0], Vlisp_EXEC_SUFFIXES, &path, X_OK);
179
180         /* Make sure that the child will be able to chdir to the current
181            buffer's current directory, or its unhandled equivalent.  We
182            can't just have the child check for an error when it does the
183            chdir, since it's in a vfork. */
184         {
185                 struct gcpro ngcpro1, ngcpro2;
186                 /* Do this test before building new_argv because GC in Lisp code
187                  *  called by various filename-hacking routines might relocate strings */
188                 /* Make sure that the child will be able to chdir to the current
189                    buffer's current directory.  We can't just have the child check
190                    for an error when it does the chdir, since it's in a vfork.  */
191
192                 current_dir = current_buffer->directory;
193                 NGCPRO2(current_dir, path);     /* Caller gcprotects args[] */
194                 current_dir = Funhandled_file_name_directory(current_dir);
195                 current_dir = expand_and_dir_to_file(current_dir, Qnil);
196 #if 0
197                 /* This is in FSF, but it breaks everything in the presence of
198                    ange-ftp-visited files, so away with it.  */
199                 if (NILP(Ffile_accessible_directory_p(current_dir)))
200                         report_file_error("Setting current directory",
201                                           Fcons(current_buffer->directory,
202                                                 Qnil));
203 #endif                          /* 0 */
204                 NUNGCPRO;
205         }
206
207         GCPRO2(current_dir, path);
208
209         if (nargs >= 2 && !NILP(args[1])) {
210                 struct gcpro ngcpro1;
211                 NGCPRO1(current_buffer->directory);
212                 infile = Fexpand_file_name(args[1], current_buffer->directory);
213                 NUNGCPRO;
214                 CHECK_STRING(infile);
215         } else
216                 infile = build_string(NULL_DEVICE);
217
218         UNGCPRO;
219
220         GCPRO3(infile, current_dir, path);      /* Fexpand_file_name might trash it */
221
222         if (nargs >= 3) {
223                 buffer = args[2];
224
225                 /* If BUFFER is a list, its meaning is
226                    (BUFFER-FOR-STDOUT FILE-FOR-STDERR).  */
227                 if (CONSP(buffer)) {
228                         if (CONSP(XCDR(buffer))) {
229                                 Lisp_Object file_for_stderr =
230                                     XCAR(XCDR(buffer));
231
232                                 if (NILP(file_for_stderr)
233                                     || EQ(Qt, file_for_stderr))
234                                         error_file = file_for_stderr;
235                                 else
236                                         error_file =
237                                             Fexpand_file_name(file_for_stderr,
238                                                               Qnil);
239                         }
240
241                         buffer = XCAR(buffer);
242                 }
243
244                 if (!(EQ(buffer, Qnil)
245                       || EQ(buffer, Qt)
246                       || ZEROP(buffer))) {
247                         Lisp_Object spec_buffer = buffer;
248                         buffer = Fget_buffer(buffer);
249                         /* Mention the buffer name for a better error message.  */
250                         if (NILP(buffer))
251                                 CHECK_BUFFER(spec_buffer);
252                         CHECK_BUFFER(buffer);
253                 }
254         } else
255                 buffer = Qnil;
256
257         UNGCPRO;
258
259         display = ((nargs >= 4) ? args[3] : Qnil);
260
261         /* From here we assume we won't GC (unless an error is signaled). */
262         {
263                 REGISTER int i;
264                 for (i = 4; i < nargs; i++) {
265                         CHECK_STRING(args[i]);
266                         new_argv[i - 3] = (char *)XSTRING_DATA(args[i]);
267                 }
268         }
269         new_argv[max(nargs - 3, 1)] = 0;
270
271         if (NILP(path))
272                 report_file_error("Searching for program",
273                                   Fcons(args[0], Qnil));
274         new_argv[0] = (char *)XSTRING_DATA(path);
275
276         filefd = open((char *)XSTRING_DATA(infile), O_RDONLY | OPEN_BINARY, 0);
277         if (filefd < 0)
278                 report_file_error("Opening process input file",
279                                   Fcons(infile, Qnil));
280
281         if (INTP(buffer)) {
282                 fd[1] = open(NULL_DEVICE, O_WRONLY | OPEN_BINARY, 0);
283                 fd[0] = -1;
284         } else {
285                 if( pipe(fd) < 0 )
286                         report_file_error("Opening process input file pipe",
287                                           Fcons(infile, Qnil));
288
289 #if 0
290                 /* Replaced by close_process_descs */
291                 set_exclusive_use(fd[0]);
292 #endif
293         }
294
295         {
296                 /* child_setup must clobber environ in systems with true vfork.
297                    Protect it from permanent change.  */
298                 REGISTER char **save_environ = environ;
299                 REGISTER int fd1 = fd[1];
300                 int fd_error = fd1;
301
302                 /* Record that we're about to create a synchronous process.  */
303                 synch_process_alive = 1;
304
305                 /* These vars record information from process termination.
306                    Clear them now before process can possibly terminate,
307                    to avoid timing error if process terminates soon.  */
308                 synch_process_death = 0;
309                 synch_process_retcode = 0;
310
311                 if (NILP(error_file))
312                         fd_error = open(NULL_DEVICE, O_WRONLY | OPEN_BINARY);
313                 else if (STRINGP(error_file)) {
314                         fd_error = open((const char *)XSTRING_DATA(error_file),
315                                         O_WRONLY | O_TRUNC | O_CREAT |
316                                         OPEN_BINARY, CREAT_MODE
317                             );
318                 }
319
320                 if (fd_error < 0) {
321                         int save_errno = errno;
322                         close(filefd);
323                         close(fd[0]);
324                         if (fd1 >= 0)
325                                 close(fd1);
326                         errno = save_errno;
327                         report_file_error("Cannot open",
328                                           Fcons(error_file, Qnil));
329                 }
330
331                 fork_error = Qnil;
332                 pid = fork();
333
334                 if (pid == 0) {
335                         if (fd[0] >= 0)
336                                 close(fd[0]);
337                         /* This is necessary because some shells may attempt to
338                            access the current controlling terminal and will hang
339                            if they are run in the background, as will be the case
340                            when XEmacs is started in the background.  Martin
341                            Buchholz observed this problem running a subprocess
342                            that used zsh to call gzip to uncompress an info
343                            file. */
344                         disconnect_controlling_terminal();
345                         child_setup(filefd, fd1, fd_error, new_argv,
346                                     (char *)XSTRING_DATA(current_dir));
347                 }
348                 if (fd_error >= 0)
349                         close(fd_error);
350
351                 environ = save_environ;
352
353                 /* Close most of our fd's, but not fd[0]
354                    since we will use that to read input from.  */
355                 close(filefd);
356                 if (fd1 >= 0)
357                         close(fd1);
358         }
359
360         if (!NILP(fork_error))
361                 signal_error(Qfile_error, fork_error);
362
363         if (pid < 0) {
364                 int save_errno = errno;
365                 if (fd[0] >= 0)
366                         close(fd[0]);
367                 errno = save_errno;
368                 report_file_error("Doing fork", Qnil);
369         }
370
371         if (INTP(buffer)) {
372                 if (fd[0] >= 0)
373                         close(fd[0]);
374 #if defined (NO_SUBPROCESSES)
375                 /* If Emacs has been built with asynchronous subprocess support,
376                    we don't need to do this, I think because it will then have
377                    the facilities for handling SIGCHLD.  */
378                 wait_without_blocking();
379 #endif                          /* NO_SUBPROCESSES */
380                 return Qnil;
381         }
382
383         {
384                 int nread;
385                 int total_read = 0;
386                 Lisp_Object instream;
387                 struct gcpro ngcpro1;
388
389                 /* Enable sending signal if user quits below.  */
390                 call_process_exited = 0;
391
392                 record_unwind_protect(call_process_cleanup,
393                                       Fcons(make_int(fd[0]), make_int(pid)));
394
395                 /* FSFmacs calls Fset_buffer() here.  We don't have to because
396                    we can insert into buffers other than the current one. */
397                 if (EQ(buffer, Qt))
398                         XSETBUFFER(buffer, current_buffer);
399                 instream =
400                     make_filedesc_input_stream(fd[0], 0, -1, LSTR_ALLOW_QUIT);
401 #ifdef FILE_CODING
402                 instream =
403                     make_decoding_input_stream
404                     (XLSTREAM(instream),
405                      Fget_coding_system(Vcoding_system_for_read));
406                 Lstream_set_character_mode(XLSTREAM(instream));
407 #endif
408                 NGCPRO1(instream);
409                 while (1) {
410                         QUIT;
411                         /* Repeatedly read until we've filled as much as possible
412                            of the buffer size we have.  But don't read
413                            less than 1024--save that for the next bufferfull.  */
414
415                         nread = 0;
416                         while (nread < bufsize - 1024) {
417                                 Lstream_data_count this_read
418                                     =
419                                     Lstream_read(XLSTREAM(instream),
420                                                  bufptr + nread,
421                                                  bufsize - nread);
422
423                                 if (this_read < 0)
424                                         goto give_up;
425
426                                 if (this_read == 0)
427                                         goto give_up_1;
428
429                                 nread += this_read;
430                         }
431
432                       give_up_1:
433
434                         /* Now NREAD is the total amount of data in the buffer.  */
435                         if (nread == 0)
436                                 break;
437
438
439                         total_read += nread;
440
441                         if (!NILP(buffer))
442                                 buffer_insert_raw_string(XBUFFER(buffer),
443                                                          (Bufbyte *) bufptr,
444                                                          nread);
445
446                         /* Make the buffer bigger as we continue to read more data,
447                            but not past 64k.  */
448                         if (bufsize < 64 * 1024 && total_read > 32 * bufsize) {
449                                 bufsize *= 2;
450                                 bufptr = (char *)alloca(bufsize);
451                         }
452
453                         if (!NILP(display) && INTERACTIVE) {
454                                 redisplay();
455                         }
456                 }
457               give_up:
458                 Lstream_close(XLSTREAM(instream));
459                 NUNGCPRO;
460
461                 QUIT;
462                 /* Wait for it to terminate, unless it already has.  */
463                 wait_for_termination(pid);
464
465                 /* Don't kill any children that the subprocess may have left behind
466                    when exiting.  */
467                 call_process_exited = 1;
468                 unbind_to(speccount, Qnil);
469
470                 if (synch_process_death)
471                         return build_string(synch_process_death);
472                 return make_int(synch_process_retcode);
473         }
474 }
475 \f
476 static int max_filedesc(void)
477 {
478         /* Cache it to avoid calling getrlimit all the time.
479            It won't really change over time 
480         */
481         static int maxfd = -1;
482
483         if (maxfd >= 0)
484                 return maxfd;
485         maxfd = MAXDESC;
486
487 #  ifdef HAVE_GETRLIMIT64
488         struct rlimit64 rlim;
489         (void)getrlimit64(RLIMIT_NOFILE, &rlim);
490         maxfd = rlim.rlim_cur;
491 #  elif  HAVE_GETRLIMIT
492         struct rlimit rlim;
493         (void)getrlimit(RLIMIT_NOFILE, &rlim);
494         maxfd = rlim.rlim_cur;
495 #  endif
496
497         return maxfd;
498 }
499
500
501 /* Move the file descriptor FD so that its number is not less than MIN. *
502    The original file descriptor remains open.  */
503 static int relocate_fd(int fd, int minfd)
504 {
505         int newfd = -1;
506
507         if (minfd < 0) {
508                 stderr_out("Bad relocated_fd minimum file descriptor: %d\n", 
509                            minfd);
510                 _exit(1);
511         }
512         if (fd >= minfd)
513                 return fd;
514         
515         newfd = dup(fd);
516
517         if (newfd == -1) {
518                 stderr_out("Error while setting up child: %s\n",
519                            strerror(errno));
520                 _exit(1);
521         }
522         if (newfd >= minfd )
523                 return newfd;
524         else {
525                 int recurse_fd = relocate_fd(newfd, minfd);
526                 /* Close all the previously recursivelly dup'ed
527                    file descriptors 
528                 */
529                 close(newfd);
530                 return recurse_fd;
531         }
532 }
533
534 /* This is the last thing run in a newly forked inferior
535    either synchronous or asynchronous.
536    Copy descriptors IN, OUT and ERR
537    as descriptors STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO.
538    Initialize inferior's priority, pgrp, connected dir and environment.
539    then exec another program based on new_argv.
540
541    This function may change environ for the superior process.
542    Therefore, the superior process must save and restore the value
543    of environ around the fork and the call to this function.
544
545    ENV is the environment for the subprocess.
546
547    XEmacs: We've removed the SET_PGRP argument because it's already
548    done by the callers of child_setup.
549
550    CURRENT_DIR is an elisp string giving the path of the current
551    directory the subprocess should have.  Since we can't really signal
552    a decent error from within the child, this should be verified as an
553    executable directory by the parent.  */
554
555 void
556 child_setup(int in, int out, int err, char **new_argv, const char *current_dir)
557 {
558         char **env;
559         char *pwd;
560
561 #ifdef SET_EMACS_PRIORITY
562         if (emacs_priority != 0)
563                 nice(-emacs_priority);
564 #endif
565
566         /* Under Windows, we are not in a child process at all, so we should
567            not close handles inherited from the parent -- we are the parent
568            and doing so will screw up all manner of things!  Similarly, most
569            of the rest of the cleanup done in this function is not done
570            under Windows.
571
572            #### This entire child_setup() function is an utter and complete
573            piece of shit.  I would rewrite it, at the very least splitting
574            out the Windows and non-Windows stuff into two completely
575            different functions; but instead I'm trying to make it go away
576            entirely, using the Lisp definition in process.el.  What's left
577            is to fix up the routines in event-msw.c (and in event-Xt.c and
578            event-tty.c) to allow for stream devices to be handled correctly.
579            There isn't much to do, in fact, and I'll fix it shortly.  That
580            way, the Lisp definition can be used non-interactively too. */
581 #if !defined (NO_SUBPROCESSES)
582         /* Close Emacs's descriptors that this process should not have.  */
583         close_process_descs();
584 #endif                          /* not NO_SUBPROCESSES */
585         close_load_descs();
586
587         /* Note that use of alloca is always safe here.  It's obvious for systems
588            that do not have true vfork or that have true (stack) alloca.
589            If using vfork and C_ALLOCA it is safe because that changes
590            the superior's static variables as if the superior had done alloca
591            and will be cleaned up in the usual way.  */
592         {
593                 REGISTER int i;
594
595                 i = strlen(current_dir);
596                 pwd = alloca_array(char, i + 6);
597                 memcpy(pwd, "PWD=", 4);
598                 memcpy(pwd + 4, current_dir, i);
599                 i += 4;
600                 if (!IS_DIRECTORY_SEP(pwd[i - 1]))
601                         pwd[i++] = DIRECTORY_SEP;
602                 pwd[i] = 0;
603
604                 /* We can't signal an Elisp error here; we're in a vfork.  Since
605                    the callers check the current directory before forking, this
606                    should only return an error if the directory's permissions
607                    are changed between the check and this chdir, but we should
608                    at least check.  */
609                 if (chdir(pwd + 4) < 0) {
610                         /* Don't report the chdir error, or ange-ftp.el doesn't work. */
611                         /* (FSFmacs does _exit (errno) here.) */
612                         pwd = 0;
613                 } else {
614                         /* Strip trailing "/".  Cretinous *[]&@$#^%@#$% Un*x */
615                         /* leave "//" (from FSF) */
616                         while (i > 6 && IS_DIRECTORY_SEP(pwd[i - 1]))
617                                 pwd[--i] = 0;
618                 }
619         }
620
621         /* Set `env' to a vector of the strings in Vprocess_environment.  */
622         /* + 2 to include PWD and terminating 0.  */
623         env = alloca_array(char *, XINT(Flength(Vprocess_environment)) + 2);
624         {
625                 REGISTER Lisp_Object tail;
626                 char **new_env = env;
627
628                 /* If we have a PWD envvar and we know the real current directory,
629                    pass one down, but with corrected value.  */
630                 if (pwd && getenv("PWD"))
631                         *new_env++ = pwd;
632
633                 /* Copy the Vprocess_environment strings into new_env.  */
634                 for (tail = Vprocess_environment;
635                      CONSP(tail) && STRINGP(XCAR(tail)); tail = XCDR(tail)) {
636                         char **ep = env;
637                         char *envvar_external;
638
639                         TO_EXTERNAL_FORMAT(LISP_STRING, XCAR(tail),
640                                            C_STRING_ALLOCA, envvar_external,
641                                            Qfile_name);
642
643                         /* See if envvar_external duplicates any string already in the env.
644                            If so, don't put it in.
645                            When an env var has multiple definitions,
646                            we keep the definition that comes first in process-environment.  */
647                         for (; ep != new_env; ep++) {
648                                 char *p = *ep, *q = envvar_external;
649                                 while (1) {
650                                         if (*q == 0)
651                                                 /* The string is malformed; might as well drop it.  */
652                                                 goto duplicate;
653                                         if (*q != *p)
654                                                 break;
655                                         if (*q == '=')
656                                                 goto duplicate;
657                                         p++, q++;
658                                 }
659                         }
660                         if (pwd && !strncmp("PWD=", envvar_external, 4)) {
661                                 *new_env++ = pwd;
662                                 pwd = 0;
663                         } else
664                                 *new_env++ = envvar_external;
665
666                       duplicate:;
667                 }
668                 *new_env = 0;
669         }
670
671         /* Make sure that in, out, and err are not actually already in
672            descriptors zero, one, or two; this could happen if Emacs is
673            started with its standard in, out, or error closed, as might
674            happen under X.  */
675         in = relocate_fd(in, 3);
676         out = relocate_fd(out, 3);
677         err = relocate_fd(err, 3);
678
679
680 #ifdef HAVE_DUP2
681         /* dup2 will automatically close STD* handles before duping
682            them 
683         */
684         dup2(in, STDIN_FILENO);
685         dup2(out, STDOUT_FILENO);
686         dup2(err, STDERR_FILENO);
687 #else
688         /* Set the standard input/output channels of the new process.  */
689         close(STDIN_FILENO);
690         close(STDOUT_FILENO);
691         close(STDERR_FILENO);
692
693         /* Sub-optimally hoping that dup will use the just closed STD*
694            handles */
695         dup(in);
696         dup(out);
697         dup(err);
698 #endif
699
700         close(in);
701         close(out);
702         close(err);
703
704         /* Close non-process-related file descriptors. It would be cleaner to
705            close just the ones that need to be, but the following brute
706            force approach is certainly effective, and not too slow. */
707
708         {
709                 int fd;
710
711                 for (fd = 3; fd < max_filedesc(); fd++)
712                         close(fd);
713         }
714
715 #ifdef vipc
716         something missing here;
717 #endif                          /* vipc */
718
719         /* execvp does not accept an environment arg so the only way
720            to pass this environment is to set environ.  Our caller
721            is responsible for restoring the ambient value of environ.  */
722         environ = env;
723         execvp(new_argv[0], new_argv);
724
725         stdout_out("Can't exec program %s\n", new_argv[0]);
726         _exit(1);
727 }
728
729 static int
730 getenv_internal(const Bufbyte * var,
731                 Bytecount varlen, Bufbyte ** value, Bytecount * valuelen)
732 {
733         Lisp_Object scan;
734
735         for (scan = Vprocess_environment; CONSP(scan); scan = XCDR(scan)) {
736                 Lisp_Object entry = XCAR(scan);
737
738                 if (STRINGP(entry)
739                     && XSTRING_LENGTH(entry) > varlen
740                     && XSTRING_BYTE(entry, varlen) == '='
741                     && !memcmp(XSTRING_DATA(entry), var, varlen)
742                     ) {
743                         *value = XSTRING_DATA(entry) + (varlen + 1);
744                         *valuelen = XSTRING_LENGTH(entry) - (varlen + 1);
745                         return 1;
746                 }
747         }
748
749         return 0;
750 }
751
752 DEFUN("getenv", Fgetenv, 1, 2, "sEnvironment variable: \np",    /*
753 Return the value of environment variable VAR, as a string.
754 VAR is a string, the name of the variable.
755 When invoked interactively, prints the value in the echo area.
756 */
757       (var, interactivep))
758 {
759         Bufbyte *value = NULL;
760         Bytecount valuelen;
761         Lisp_Object v = Qnil;
762         struct gcpro gcpro1;
763
764         CHECK_STRING(var);
765         GCPRO1(v);
766         if (getenv_internal(XSTRING_DATA(var), XSTRING_LENGTH(var),
767                             &value, &valuelen)) {
768                 v = make_string(value, valuelen);
769         }
770         if (!NILP(interactivep)) {
771                 if (NILP(v))
772                         message("%s not defined in environment",
773                                 XSTRING_DATA(var));
774                 else
775                         /* #### Should use Fprin1_to_string or Fprin1 to handle string
776                            containing quotes correctly.  */
777                         message("\"%s\"", value);
778         }
779         RETURN_UNGCPRO(v);
780 }
781
782 /* A version of getenv that consults process_environment, easily
783    callable from C.  */
784 char *egetenv(const char *var)
785 {
786         /* This cannot GC -- 7-28-00 ben */
787         Bufbyte *value;
788         Bytecount valuelen;
789
790         if (getenv_internal
791             ((const Bufbyte *)var, strlen(var), &value, &valuelen))
792                 return (char *)value;
793         else
794                 return 0;
795 }
796 \f
797 void init_callproc(void)
798 {
799         /* This function can GC */
800
801         {
802                 /* jwz: always initialize Vprocess_environment, so that egetenv()
803                    works in temacs. */
804                 char **envp;
805                 Vprocess_environment = Qnil;
806                 for (envp = environ; envp && *envp; envp++)
807                         Vprocess_environment =
808                             Fcons(build_ext_string(*envp, Qfile_name),
809                                   Vprocess_environment);
810         }
811
812         {
813                 /* Initialize shell-file-name from environment variables or best guess. */
814                 const char *shell = egetenv("SHELL");
815                 if (!shell)
816                         shell = "/bin/sh";
817                 Vshell_file_name = build_string(shell);
818         }
819 }
820
821 #if 0
822 void set_process_environment(void)
823 {
824         REGISTER char **envp;
825
826         Vprocess_environment = Qnil;
827 #ifndef CANNOT_DUMP
828         if (initialized)
829 #endif
830                 for (envp = environ; *envp; envp++)
831                         Vprocess_environment = Fcons(build_string(*envp),
832                                                      Vprocess_environment);
833 }
834 #endif                          /* unused */
835
836 void syms_of_callproc(void)
837 {
838         DEFSUBR(Fold_call_process_internal);
839         DEFSUBR(Fgetenv);
840 }
841
842 void vars_of_callproc(void)
843 {
844         /* This function can GC */
845
846         DEFVAR_LISP("shell-file-name", &Vshell_file_name        /*
847 *File name to load inferior shells from.
848 Initialized from the SHELL environment variable.
849                                                                  */ );
850
851         DEFVAR_LISP("process-environment", &Vprocess_environment        /*
852 List of environment variables for subprocesses to inherit.
853 Each element should be a string of the form ENVVARNAME=VALUE.
854 The environment which Emacs inherits is placed in this variable
855 when Emacs starts.
856                                                                          */ );
857
858         Vlisp_EXEC_SUFFIXES = build_string(EXEC_SUFFIXES);
859         staticpro(&Vlisp_EXEC_SUFFIXES);
860 }