Tue Mar 19 20:21:34 1996 Roland McGrath <roland@charlie-brown.gnu.ai.mit.edu>
[make.git] / job.c
blob90ae9d9700587d20dd39b28f49ecf8f0a9a32255
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96
3 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make 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.
11 GNU Make 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.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
20 #include "make.h"
21 #include "job.h"
22 #include "filedef.h"
23 #include "commands.h"
24 #include "variable.h"
25 #include <assert.h>
27 /* Default shell to use. */
28 char default_shell[] = "/bin/sh";
30 #ifdef __MSDOS__
31 #include <process.h>
32 static int dos_pid = 123;
33 static int dos_status;
34 static char *dos_bname;
35 static char *dos_bename;
36 static int dos_batch_file;
37 #endif /* MSDOS. */
39 #ifdef VMS
40 #include <time.h>
41 #include <processes.h>
42 #include <starlet.h>
43 #include <lib$routines.h>
44 #endif
46 #ifdef HAVE_FCNTL_H
47 #include <fcntl.h>
48 #else
49 #include <sys/file.h>
50 #endif
52 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
53 #include <sys/wait.h>
54 #endif
56 #ifdef HAVE_WAITPID
57 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
58 #else /* Don't have waitpid. */
59 #ifdef HAVE_WAIT3
60 #ifndef wait3
61 extern int wait3 ();
62 #endif
63 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
64 #endif /* Have wait3. */
65 #endif /* Have waitpid. */
67 #if !defined (wait) && !defined (POSIX)
68 extern int wait ();
69 #endif
71 #ifndef HAVE_UNION_WAIT
73 #define WAIT_T int
75 #ifndef WTERMSIG
76 #define WTERMSIG(x) ((x) & 0x7f)
77 #endif
78 #ifndef WCOREDUMP
79 #define WCOREDUMP(x) ((x) & 0x80)
80 #endif
81 #ifndef WEXITSTATUS
82 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
83 #endif
84 #ifndef WIFSIGNALED
85 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
86 #endif
87 #ifndef WIFEXITED
88 #define WIFEXITED(x) (WTERMSIG (x) == 0)
89 #endif
91 #else /* Have `union wait'. */
93 #define WAIT_T union wait
94 #ifndef WTERMSIG
95 #define WTERMSIG(x) ((x).w_termsig)
96 #endif
97 #ifndef WCOREDUMP
98 #define WCOREDUMP(x) ((x).w_coredump)
99 #endif
100 #ifndef WEXITSTATUS
101 #define WEXITSTATUS(x) ((x).w_retcode)
102 #endif
103 #ifndef WIFSIGNALED
104 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
105 #endif
106 #ifndef WIFEXITED
107 #define WIFEXITED(x) (WTERMSIG(x) == 0)
108 #endif
110 #endif /* Don't have `union wait'. */
112 #ifdef VMS
113 static int vms_jobsefnmask=0;
114 #endif /* !VMS */
116 #ifndef HAVE_UNISTD_H
117 extern int dup2 ();
118 extern int execve ();
119 extern void _exit ();
120 #ifndef VMS
121 extern int geteuid ();
122 extern int getegid ();
123 extern int setgid ();
124 extern int getgid ();
125 #endif
126 #endif
128 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
130 extern int getloadavg PARAMS ((double loadavg[], int nelem));
131 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
132 int *is_remote, int *id_ptr, int *used_stdin));
133 extern int start_remote_job_p PARAMS ((void));
134 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
135 int *coredump_ptr, int block));
137 RETSIGTYPE child_handler PARAMS ((int));
138 static void free_child PARAMS ((struct child *));
139 static void start_job_command PARAMS ((struct child *child));
140 static int load_too_high PARAMS ((void));
141 static int job_next_command PARAMS ((struct child *));
142 static int start_waiting_job PARAMS ((struct child *));
143 #ifdef VMS
144 static void vmsWaitForChildren PARAMS ((int *));
145 #endif
147 /* Chain of all live (or recently deceased) children. */
149 struct child *children = 0;
151 /* Number of children currently running. */
153 unsigned int job_slots_used = 0;
155 /* Nonzero if the `good' standard input is in use. */
157 static int good_stdin_used = 0;
159 /* Chain of children waiting to run until the load average goes down. */
161 static struct child *waiting_jobs = 0;
163 /* Write an error message describing the exit status given in
164 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
165 Append "(ignored)" if IGNORED is nonzero. */
167 static void
168 child_error (target_name, exit_code, exit_sig, coredump, ignored)
169 char *target_name;
170 int exit_code, exit_sig, coredump;
171 int ignored;
173 if (ignored && silent_flag)
174 return;
176 #ifdef VMS
177 if (!(exit_code & 1))
178 error("*** [%s] Error 0x%x%s", target_name, exit_code, ((ignored)? " (ignored)" : ""));
179 #else
180 if (exit_sig == 0)
181 error (ignored ? "[%s] Error %d (ignored)" :
182 "*** [%s] Error %d",
183 target_name, exit_code);
184 else
185 error ("*** [%s] %s%s",
186 target_name, strsignal (exit_sig),
187 coredump ? " (core dumped)" : "");
188 #endif
191 static unsigned int dead_children = 0;
193 #ifdef VMS
194 /* Wait for nchildren children to terminate */
195 static void
196 vmsWaitForChildren(int *status)
198 while (1)
200 if (!vms_jobsefnmask)
202 *status = 0;
203 return;
206 *status = sys$wflor (32, vms_jobsefnmask);
208 return;
210 #endif
213 /* Notice that a child died.
214 reap_children should be called when convenient. */
215 RETSIGTYPE
216 child_handler (sig)
217 int sig;
219 ++dead_children;
221 if (debug_flag)
222 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
225 extern int shell_function_pid, shell_function_completed;
227 /* Reap dead children, storing the returned status and the new command
228 state (`cs_finished') in the `file' member of the `struct child' for the
229 dead child, and removing the child from the chain. If BLOCK nonzero,
230 reap at least one child, waiting for it to die if necessary. If ERR is
231 nonzero, print an error message first. */
233 void
234 reap_children (block, err)
235 int block, err;
237 WAIT_T status;
239 while ((children != 0 || shell_function_pid != 0) &&
240 (block || dead_children > 0))
242 int remote = 0;
243 register int pid;
244 int exit_code, exit_sig, coredump;
245 register struct child *lastc, *c;
246 int child_failed;
247 int any_remote, any_local;
249 if (err && dead_children == 0)
251 /* We might block for a while, so let the user know why. */
252 fflush (stdout);
253 error ("*** Waiting for unfinished jobs....");
256 /* We have one less dead child to reap.
257 The test and decrement are not atomic; if it is compiled into:
258 register = dead_children - 1;
259 dead_children = register;
260 a SIGCHLD could come between the two instructions.
261 child_handler increments dead_children.
262 The second instruction here would lose that increment. But the
263 only effect of dead_children being wrong is that we might wait
264 longer than necessary to reap a child, and lose some parallelism;
265 and we might print the "Waiting for unfinished jobs" message above
266 when not necessary. */
268 if (dead_children > 0)
269 --dead_children;
271 any_remote = 0;
272 any_local = shell_function_pid != -1;
273 for (c = children; c != 0; c = c->next)
275 any_remote |= c->remote;
276 any_local |= ! c->remote;
277 if (debug_flag)
278 printf ("Live child 0x%08lx PID %d%s\n",
279 (unsigned long int) c,
280 c->pid, c->remote ? " (remote)" : "");
281 #ifdef VMS
282 break;
283 #endif
286 /* First, check for remote children. */
287 if (any_remote)
288 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
289 else
290 pid = 0;
292 if (pid < 0)
294 remote_status_lose:
295 #ifdef EINTR
296 if (errno == EINTR)
297 continue;
298 #endif
299 pfatal_with_name ("remote_status");
301 else if (pid == 0)
303 #ifndef __MSDOS__
304 /* No remote children. Check for local children. */
306 if (any_local)
308 #ifdef VMS
309 vmsWaitForChildren (&status);
310 pid = c->pid;
311 #else
312 #ifdef WAIT_NOHANG
313 if (!block)
314 pid = WAIT_NOHANG (&status);
315 else
316 #endif
317 pid = wait (&status);
318 #endif /* !VMS */
320 else
321 pid = 0;
323 if (pid < 0)
325 #ifdef EINTR
326 if (errno == EINTR)
327 continue;
328 #endif
329 pfatal_with_name ("wait");
331 else if (pid == 0)
333 /* No local children. */
334 if (block && any_remote)
336 /* Now try a blocking wait for a remote child. */
337 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
338 if (pid < 0)
339 goto remote_status_lose;
340 else if (pid == 0)
341 /* No remote children either. Finally give up. */
342 break;
343 else
344 /* We got a remote child. */
345 remote = 1;
347 else
348 break;
350 else
352 /* Chop the status word up. */
353 exit_code = WEXITSTATUS (status);
354 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
355 coredump = WCOREDUMP (status);
357 #else /* MSDOS. */
358 /* Life is very different on MSDOS. */
359 pid = dos_pid - 1;
360 status = dos_status;
361 exit_code = dos_status;
362 exit_sig = 0;
363 coredump = 0;
364 #endif /* Not MSDOS. */
366 else
367 /* We got a remote child. */
368 remote = 1;
370 /* Check if this is the child of the `shell' function. */
371 if (!remote && pid == shell_function_pid)
373 /* It is. Leave an indicator for the `shell' function. */
374 if (exit_sig == 0 && exit_code == 127)
375 shell_function_completed = -1;
376 else
377 shell_function_completed = 1;
378 break;
381 child_failed = exit_sig != 0 || exit_code != 0;
383 /* Search for a child matching the deceased one. */
384 lastc = 0;
385 for (c = children; c != 0; lastc = c, c = c->next)
386 if (c->remote == remote && c->pid == pid)
387 break;
389 if (c == 0)
391 /* An unknown child died. */
392 char buf[100];
393 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
394 if (child_failed)
395 child_error (buf, exit_code, exit_sig, coredump,
396 ignore_errors_flag);
397 else
398 error ("%s finished.", buf);
400 else
402 if (debug_flag)
403 printf ("Reaping %s child 0x%08lx PID %d%s\n",
404 child_failed ? "losing" : "winning",
405 (unsigned long int) c,
406 c->pid, c->remote ? " (remote)" : "");
408 /* If this child had the good stdin, say it is now free. */
409 if (c->good_stdin)
410 good_stdin_used = 0;
412 if (child_failed && !c->noerror && !ignore_errors_flag)
414 /* The commands failed. Write an error message,
415 delete non-precious targets, and abort. */
416 static int delete_on_error = -1;
417 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
418 c->file->update_status = 2;
419 if (delete_on_error == -1)
421 struct file *f = lookup_file (".DELETE_ON_ERROR");
422 delete_on_error = f != 0 && f->is_target;
424 if (exit_sig != 0 || delete_on_error)
425 delete_child_targets (c);
427 else
429 if (child_failed)
431 /* The commands failed, but we don't care. */
432 child_error (c->file->name,
433 exit_code, exit_sig, coredump, 1);
434 child_failed = 0;
437 /* If there are more commands to run, try to start them. */
438 if (job_next_command (c))
440 if (handling_fatal_signal)
442 /* Never start new commands while we are dying.
443 Since there are more commands that wanted to be run,
444 the target was not completely remade. So we treat
445 this as if a command had failed. */
446 c->file->update_status = 2;
448 else
450 /* Check again whether to start remotely.
451 Whether or not we want to changes over time.
452 Also, start_remote_job may need state set up
453 by start_remote_job_p. */
454 c->remote = start_remote_job_p ();
455 start_job_command (c);
456 /* Fatal signals are left blocked in case we were
457 about to put that child on the chain. But it is
458 already there, so it is safe for a fatal signal to
459 arrive now; it will clean up this child's targets. */
460 unblock_sigs ();
461 if (c->file->command_state == cs_running)
462 /* We successfully started the new command.
463 Loop to reap more children. */
464 continue;
467 if (c->file->update_status != 0)
468 /* We failed to start the commands. */
469 delete_child_targets (c);
471 else
472 /* There are no more commands. We got through them all
473 without an unignored error. Now the target has been
474 successfully updated. */
475 c->file->update_status = 0;
478 /* When we get here, all the commands for C->file are finished
479 (or aborted) and C->file->update_status contains 0 or 2. But
480 C->file->command_state is still cs_running if all the commands
481 ran; notice_finish_file looks for cs_running to tell it that
482 it's interesting to check the file's modtime again now. */
484 if (! handling_fatal_signal)
485 /* Notice if the target of the commands has been changed.
486 This also propagates its values for command_state and
487 update_status to its also_make files. */
488 notice_finished_file (c->file);
490 if (debug_flag)
491 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
492 (unsigned long int) c,
493 c->pid, c->remote ? " (remote)" : "");
495 /* Remove the child from the chain and free it. */
496 if (lastc == 0)
497 children = c->next;
498 else
499 lastc->next = c->next;
500 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
501 free_child (c);
503 /* There is now another slot open. */
504 if (job_slots_used > 0)
505 --job_slots_used;
507 /* If the job failed, and the -k flag was not given, die,
508 unless we are already in the process of dying. */
509 if (!err && child_failed && !keep_going_flag)
510 die (2);
513 /* Only block for one child. */
514 block = 0;
516 return;
519 /* Free the storage allocated for CHILD. */
521 static void
522 free_child (child)
523 register struct child *child;
525 if (child->command_lines != 0)
527 register unsigned int i;
528 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
529 free (child->command_lines[i]);
530 free ((char *) child->command_lines);
533 if (child->environment != 0)
535 register char **ep = child->environment;
536 while (*ep != 0)
537 free (*ep++);
538 free ((char *) child->environment);
541 free ((char *) child);
544 #ifdef POSIX
545 #ifdef __MSDOS__
546 void
547 unblock_sigs ()
549 return;
551 #else
552 extern sigset_t fatal_signal_set;
554 void
555 unblock_sigs ()
557 sigset_t empty;
558 sigemptyset (&empty);
559 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
561 #endif
562 #endif
564 /* Start a job to run the commands specified in CHILD.
565 CHILD is updated to reflect the commands and ID of the child process.
567 NOTE: On return fatal signals are blocked! The caller is responsible
568 for calling `unblock_sigs', once the new child is safely on the chain so
569 it can be cleaned up in the event of a fatal signal. */
571 static void
572 start_job_command (child)
573 register struct child *child;
575 static int bad_stdin = -1;
576 register char *p;
577 int flags;
578 #ifdef VMS
579 char *argv;
580 #else
581 char **argv;
582 #endif
584 /* Combine the flags parsed for the line itself with
585 the flags specified globally for this target. */
586 flags = (child->file->command_flags
587 | child->file->cmds->lines_flags[child->command_line - 1]);
589 p = child->command_ptr;
590 child->noerror = flags & COMMANDS_NOERROR;
592 while (*p != '\0')
594 if (*p == '@')
595 flags |= COMMANDS_SILENT;
596 else if (*p == '+')
597 flags |= COMMANDS_RECURSE;
598 else if (*p == '-')
599 child->noerror = 1;
600 else if (!isblank (*p) && *p != '+')
601 break;
602 ++p;
605 /* If -q was given, just say that updating `failed'. The exit status of
606 1 tells the user that -q is saying `something to do'; the exit status
607 for a random error is 2. */
608 if (question_flag && !(flags & COMMANDS_RECURSE))
610 child->file->update_status = 1;
611 notice_finished_file (child->file);
612 return;
615 /* There may be some preceding whitespace left if there
616 was nothing but a backslash on the first line. */
617 p = next_token (p);
619 /* Figure out an argument list from this command line. */
622 char *end = 0;
623 #ifdef VMS
624 argv = p;
625 #else
626 argv = construct_command_argv (p, &end, child->file);
627 #endif
628 if (end == NULL)
629 child->command_ptr = NULL;
630 else
632 *end++ = '\0';
633 child->command_ptr = end;
637 if (touch_flag && !(flags & COMMANDS_RECURSE))
639 /* Go on to the next command. It might be the recursive one.
640 We construct ARGV only to find the end of the command line. */
641 #ifndef VMS
642 free (argv[0]);
643 free ((char *) argv);
644 #endif
645 argv = 0;
648 if (argv == 0)
650 next_command:
651 /* This line has no commands. Go to the next. */
652 if (job_next_command (child))
653 start_job_command (child);
654 else
656 /* No more commands. All done. */
657 child->file->update_status = 0;
658 notice_finished_file (child->file);
660 return;
663 /* Print out the command. If silent, we call `message' with null so it
664 can log the working directory before the command's own error messages
665 appear. */
667 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
668 ? "%s" : (char *) 0, p);
670 /* Tell update_goal_chain that a command has been started on behalf of
671 this target. It is important that this happens here and not in
672 reap_children (where we used to do it), because reap_children might be
673 reaping children from a different target. We want this increment to
674 guaranteedly indicate that a command was started for the dependency
675 chain (i.e., update_file recursion chain) we are processing. */
677 ++commands_started;
679 /* If -n was given, recurse to get the next line in the sequence. */
681 if (just_print_flag && !(flags & COMMANDS_RECURSE))
683 #ifndef VMS
684 free (argv[0]);
685 free ((char *) argv);
686 #endif
687 goto next_command;
690 /* Flush the output streams so they won't have things written twice. */
692 fflush (stdout);
693 fflush (stderr);
695 #ifndef VMS
697 /* Set up a bad standard input that reads from a broken pipe. */
699 if (bad_stdin == -1)
701 /* Make a file descriptor that is the read end of a broken pipe.
702 This will be used for some children's standard inputs. */
703 int pd[2];
704 if (pipe (pd) == 0)
706 /* Close the write side. */
707 (void) close (pd[1]);
708 /* Save the read side. */
709 bad_stdin = pd[0];
711 /* Set the descriptor to close on exec, so it does not litter any
712 child's descriptor table. When it is dup2'd onto descriptor 0,
713 that descriptor will not close on exec. */
714 #ifdef FD_SETFD
715 #ifndef FD_CLOEXEC
716 #define FD_CLOEXEC 1
717 #endif
718 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
719 #endif
723 /* Decide whether to give this child the `good' standard input
724 (one that points to the terminal or whatever), or the `bad' one
725 that points to the read side of a broken pipe. */
727 child->good_stdin = !good_stdin_used;
728 if (child->good_stdin)
729 good_stdin_used = 1;
731 #endif /* !VMS */
733 child->deleted = 0;
735 /* Set up the environment for the child. */
736 if (child->environment == 0)
737 child->environment = target_environment (child->file);
739 #ifndef __MSDOS__
741 #ifndef VMS
742 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
743 if (child->remote)
745 int is_remote, id, used_stdin;
746 if (start_remote_job (argv, child->environment,
747 child->good_stdin ? 0 : bad_stdin,
748 &is_remote, &id, &used_stdin))
749 goto error;
750 else
752 if (child->good_stdin && !used_stdin)
754 child->good_stdin = 0;
755 good_stdin_used = 0;
757 child->remote = is_remote;
758 child->pid = id;
761 else
762 #endif /* !VMS */
764 /* Fork the child process. */
766 char **parent_environ;
768 #ifdef POSIX
769 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
770 #else
771 #ifdef HAVE_SIGSETMASK
772 (void) sigblock (fatal_signal_mask);
773 #endif
774 #endif
776 child->remote = 0;
778 #ifdef VMS
780 if (!child_execute_job (argv, child)) {
781 /* Fork failed! */
782 perror_with_name ("vfork", "");
783 goto error;
786 #else
788 parent_environ = environ;
789 child->pid = vfork ();
790 environ = parent_environ; /* Restore value child may have clobbered. */
791 if (child->pid == 0)
793 /* We are the child side. */
794 unblock_sigs ();
795 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
796 argv, child->environment);
798 else if (child->pid < 0)
800 /* Fork failed! */
801 unblock_sigs ();
802 perror_with_name ("vfork", "");
803 goto error;
805 #endif /* !VMS */
808 #else /* MSDOS. */
810 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
811 ++dead_children;
812 child->pid = dos_pid++;
813 if (dos_batch_file)
815 dos_batch_file = 0;
816 remove (dos_bname); /* Ignore errors. */
817 if (access (dos_bename, 0))
818 dos_status = 1;
819 else
820 dos_status = 0;
821 remove (dos_bename);
823 #endif /* Not MSDOS. */
825 /* We are the parent side. Set the state to
826 say the commands are running and return. */
828 set_command_state (child->file, cs_running);
830 /* Free the storage used by the child's argument list. */
831 #ifndef VMS
832 free (argv[0]);
833 free ((char *) argv);
834 #endif
836 return;
838 error:
839 child->file->update_status = 2;
840 notice_finished_file (child->file);
841 return;
844 /* Try to start a child running.
845 Returns nonzero if the child was started (and maybe finished), or zero if
846 the load was too high and the child was put on the `waiting_jobs' chain. */
848 static int
849 start_waiting_job (c)
850 struct child *c;
852 /* If we can start a job remotely, we always want to, and don't care about
853 the local load average. We record that the job should be started
854 remotely in C->remote for start_job_command to test. */
856 c->remote = start_remote_job_p ();
858 /* If this job is to be started locally, and we are already running
859 some jobs, make this one wait if the load average is too high. */
860 if (!c->remote && job_slots_used > 0 && load_too_high ())
862 /* Put this child on the chain of children waiting
863 for the load average to go down. */
864 set_command_state (c->file, cs_running);
865 c->next = waiting_jobs;
866 waiting_jobs = c;
867 return 0;
870 /* Start the first command; reap_children will run later command lines. */
871 start_job_command (c);
873 switch (c->file->command_state)
875 case cs_running:
876 c->next = children;
877 if (debug_flag)
878 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
879 (unsigned long int) c,
880 c->pid, c->remote ? " (remote)" : "");
881 children = c;
882 /* One more job slot is in use. */
883 ++job_slots_used;
884 unblock_sigs ();
885 break;
887 case cs_not_started:
888 /* All the command lines turned out to be empty. */
889 c->file->update_status = 0;
890 /* FALLTHROUGH */
892 case cs_finished:
893 notice_finished_file (c->file);
894 free_child (c);
895 break;
897 default:
898 assert (c->file->command_state == cs_finished);
899 break;
902 return 1;
905 /* Create a `struct child' for FILE and start its commands running. */
907 void
908 new_job (file)
909 register struct file *file;
911 register struct commands *cmds = file->cmds;
912 register struct child *c;
913 char **lines;
914 register unsigned int i;
916 /* Let any previously decided-upon jobs that are waiting
917 for the load to go down start before this new one. */
918 start_waiting_jobs ();
920 /* Reap any children that might have finished recently. */
921 reap_children (0, 0);
923 /* Chop the commands up into lines if they aren't already. */
924 chop_commands (cmds);
926 if (job_slots != 0)
927 /* Wait for a job slot to be freed up. */
928 while (job_slots_used == job_slots)
929 reap_children (1, 0);
931 /* Expand the command lines and store the results in LINES. */
932 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
933 for (i = 0; i < cmds->ncommand_lines; ++i)
935 /* Collapse backslash-newline combinations that are inside variable
936 or function references. These are left alone by the parser so
937 that they will appear in the echoing of commands (where they look
938 nice); and collapsed by construct_command_argv when it tokenizes.
939 But letting them survive inside function invocations loses because
940 we don't want the functions to see them as part of the text. */
942 char *in, *out, *ref;
944 /* IN points to where in the line we are scanning.
945 OUT points to where in the line we are writing.
946 When we collapse a backslash-newline combination,
947 IN gets ahead out OUT. */
949 in = out = cmds->command_lines[i];
950 while ((ref = index (in, '$')) != 0)
952 ++ref; /* Move past the $. */
954 if (out != in)
955 /* Copy the text between the end of the last chunk
956 we processed (where IN points) and the new chunk
957 we are about to process (where REF points). */
958 bcopy (in, out, ref - in);
960 /* Move both pointers past the boring stuff. */
961 out += ref - in;
962 in = ref;
964 if (*ref == '(' || *ref == '{')
966 char openparen = *ref;
967 char closeparen = openparen == '(' ? ')' : '}';
968 int count;
969 char *p;
971 *out++ = *in++; /* Copy OPENPAREN. */
972 /* IN now points past the opening paren or brace.
973 Count parens or braces until it is matched. */
974 count = 0;
975 while (*in != '\0')
977 if (*in == closeparen && --count < 0)
978 break;
979 else if (*in == '\\' && in[1] == '\n')
981 /* We have found a backslash-newline inside a
982 variable or function reference. Eat it and
983 any following whitespace. */
985 int quoted = 0;
986 for (p = in - 1; p > ref && *p == '\\'; --p)
987 quoted = !quoted;
989 if (quoted)
990 /* There were two or more backslashes, so this is
991 not really a continuation line. We don't collapse
992 the quoting backslashes here as is done in
993 collapse_continuations, because the line will
994 be collapsed again after expansion. */
995 *out++ = *in++;
996 else
998 /* Skip the backslash, newline and
999 any following whitespace. */
1000 in = next_token (in + 2);
1002 /* Discard any preceding whitespace that has
1003 already been written to the output. */
1004 while (out > ref && isblank (out[-1]))
1005 --out;
1007 /* Replace it all with a single space. */
1008 *out++ = ' ';
1011 else
1013 if (*in == openparen)
1014 ++count;
1016 *out++ = *in++;
1022 /* There are no more references in this line to worry about.
1023 Copy the remaining uninteresting text to the output. */
1024 if (out != in)
1025 strcpy (out, in);
1027 /* Finally, expand the line. */
1028 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1029 file);
1032 /* Start the command sequence, record it in a new
1033 `struct child', and add that to the chain. */
1035 c = (struct child *) xmalloc (sizeof (struct child));
1036 c->file = file;
1037 c->command_lines = lines;
1038 c->command_line = 0;
1039 c->command_ptr = 0;
1040 c->environment = 0;
1042 /* Fetch the first command line to be run. */
1043 job_next_command (c);
1045 /* The job is now primed. Start it running.
1046 (This will notice if there are in fact no commands.) */
1047 (void)start_waiting_job (c);
1049 if (job_slots == 1)
1050 /* Since there is only one job slot, make things run linearly.
1051 Wait for the child to die, setting the state to `cs_finished'. */
1052 while (file->command_state == cs_running)
1053 reap_children (1, 0);
1055 return;
1058 /* Move CHILD's pointers to the next command for it to execute.
1059 Returns nonzero if there is another command. */
1061 static int
1062 job_next_command (child)
1063 struct child *child;
1065 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1067 /* There are no more lines in the expansion of this line. */
1068 if (child->command_line == child->file->cmds->ncommand_lines)
1070 /* There are no more lines to be expanded. */
1071 child->command_ptr = 0;
1072 return 0;
1074 else
1075 /* Get the next line to run. */
1076 child->command_ptr = child->command_lines[child->command_line++];
1078 return 1;
1081 static int
1082 load_too_high ()
1084 #if defined(__MSDOS__) || defined(VMS)
1085 return 1;
1086 #else
1087 double load;
1089 if (max_load_average < 0)
1090 return 0;
1092 make_access ();
1093 if (getloadavg (&load, 1) != 1)
1095 static int lossage = -1;
1096 /* Complain only once for the same error. */
1097 if (lossage == -1 || errno != lossage)
1099 if (errno == 0)
1100 /* An errno value of zero means getloadavg is just unsupported. */
1101 error ("cannot enforce load limits on this operating system");
1102 else
1103 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1105 lossage = errno;
1106 load = 0;
1108 user_access ();
1110 return load >= max_load_average;
1111 #endif
1114 /* Start jobs that are waiting for the load to be lower. */
1116 void
1117 start_waiting_jobs ()
1119 struct child *job;
1121 if (waiting_jobs == 0)
1122 return;
1126 /* Check for recently deceased descendants. */
1127 reap_children (0, 0);
1129 /* Take a job off the waiting list. */
1130 job = waiting_jobs;
1131 waiting_jobs = job->next;
1133 /* Try to start that job. We break out of the loop as soon
1134 as start_waiting_job puts one back on the waiting list. */
1136 while (start_waiting_job (job) && waiting_jobs != 0);
1138 return;
1141 #ifdef VMS
1142 #include <descrip.h>
1143 #include <clidef.h>
1145 /* This is called as an AST when a child process dies (it won't get
1146 interrupted by anything except a higher level AST).
1148 int vmsHandleChildTerm(struct child *child)
1150 int status;
1151 register struct child *lastc, *c;
1152 int child_failed;
1154 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1156 lib$free_ef(&child->efn);
1158 (void) sigblock (fatal_signal_mask);
1160 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1162 /* Search for a child matching the deceased one. */
1163 lastc = 0;
1164 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1165 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1166 #else
1167 c = child;
1168 #endif
1170 if (child_failed && !c->noerror && !ignore_errors_flag)
1172 /* The commands failed. Write an error message,
1173 delete non-precious targets, and abort. */
1174 child_error (c->file->name, c->cstatus, 0, 0, 0);
1175 c->file->update_status = 1;
1176 delete_child_targets (c);
1178 else
1180 if (child_failed)
1182 /* The commands failed, but we don't care. */
1183 child_error (c->file->name, c->cstatus, 0, 0, 1);
1184 child_failed = 0;
1187 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1188 /* If there are more commands to run, try to start them. */
1189 start_job (c);
1191 switch (c->file->command_state)
1193 case cs_running:
1194 /* Successfully started. */
1195 break;
1197 case cs_finished:
1198 if (c->file->update_status != 0) {
1199 /* We failed to start the commands. */
1200 delete_child_targets (c);
1202 break;
1204 default:
1205 error ("internal error: `%s' command_state \
1206 %d in child_handler", c->file->name);
1207 abort ();
1208 break;
1210 #endif /* RECURSIVEJOBS */
1213 /* Set the state flag to say the commands have finished. */
1214 c->file->command_state = cs_finished;
1215 notice_finished_file (c->file);
1217 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1218 /* Remove the child from the chain and free it. */
1219 if (lastc == 0)
1220 children = c->next;
1221 else
1222 lastc->next = c->next;
1223 free_child (c);
1224 #endif /* RECURSIVEJOBS */
1226 /* There is now another slot open. */
1227 if (job_slots_used > 0)
1228 --job_slots_used;
1230 /* If the job failed, and the -k flag was not given, die. */
1231 if (child_failed && !keep_going_flag)
1232 die (EXIT_FAILURE);
1234 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1236 return 1;
1239 /* VMS:
1240 Spawn a process executing the command in ARGV and return its pid. */
1242 #define MAXCMDLEN 200
1245 child_execute_job (argv, child)
1246 char *argv;
1247 struct child *child;
1249 int i;
1250 static struct dsc$descriptor_s cmddsc;
1251 #ifndef DONTWAITFORCHILD
1252 int spflags = 0;
1253 #else
1254 int spflags = CLI$M_NOWAIT;
1255 #endif
1256 int status;
1257 char cmd[4096],*p,*c;
1258 char comname[50];
1260 /* Remove backslashes */
1261 for (p = argv, c = cmd; *p; p++,c++)
1263 if (*p == '\\') p++;
1264 *c = *p;
1266 *c = *p;
1268 /* check for maximum dcl length and create *.com file if neccesary */
1270 comname[0] = '\0';
1272 if (strlen (cmd) > MAXCMDLEN)
1274 FILE *outfile;
1275 char tmp;
1277 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1278 (void) mktemp (comname);
1280 outfile = fopen (comname, "w");
1281 if (outfile == 0)
1282 pfatal_with_name (comname);
1284 fprintf (outfile, "$ ");
1285 c = cmd;
1287 while (c)
1289 p = strchr (c, ',');
1290 if ((p == NULL) || (p-c > MAXCMDLEN))
1291 p = strchr (c, ' ');
1292 if (p != NULL)
1294 p++;
1295 tmp = *p;
1296 *p = '\0';
1298 else
1299 tmp = '\0';
1300 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1301 if (p != NULL)
1302 *p = tmp;
1303 c = p;
1306 fclose (outfile);
1308 sprintf (cmd, "$ @%s", comname);
1310 if (debug_flag)
1311 printf ("Executing %s instead\n", cmd);
1314 cmddsc.dsc$w_length = strlen(cmd);
1315 cmddsc.dsc$a_pointer = cmd;
1316 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1317 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1319 child->efn = 0;
1320 while (child->efn < 32 || child->efn > 63)
1322 status = lib$get_ef(&child->efn);
1323 if (!(status & 1))
1324 return 0;
1327 sys$clref(child->efn);
1329 vms_jobsefnmask |= (1 << (child->efn - 32));
1331 #ifndef DONTWAITFORCHILD
1332 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1333 &child->efn,0,0);
1334 vmsHandleChildTerm(child);
1335 #else
1336 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1337 &child->efn,vmsHandleChildTerm,child);
1338 #endif
1340 if (!(status & 1))
1342 printf("Error spawning, %d\n",status);
1343 fflush(stdout);
1346 unlink (comname);
1348 return (status & 1);
1351 #else /* !VMS */
1353 /* UNIX:
1354 Replace the current process with one executing the command in ARGV.
1355 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1356 the environment of the new program. This function does not return. */
1358 void
1359 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1360 int stdin_fd, stdout_fd;
1361 char **argv, **envp;
1363 if (stdin_fd != 0)
1364 (void) dup2 (stdin_fd, 0);
1365 if (stdout_fd != 1)
1366 (void) dup2 (stdout_fd, 1);
1367 if (stdin_fd != 0)
1368 (void) close (stdin_fd);
1369 if (stdout_fd != 1)
1370 (void) close (stdout_fd);
1372 /* Run the command. */
1373 exec_command (argv, envp);
1375 #endif /* !VMS */
1377 /* Replace the current process with one running the command in ARGV,
1378 with environment ENVP. This function does not return. */
1380 void
1381 exec_command (argv, envp)
1382 char **argv, **envp;
1384 #ifdef VMS
1385 /* Run the program. */
1386 execve (argv[0], argv, envp);
1387 perror_with_name ("execve: ", argv[0]);
1388 _exit (EXIT_FAILURE);
1389 #else
1390 /* Be the user, permanently. */
1391 child_access ();
1393 /* Run the program. */
1394 environ = envp;
1395 execvp (argv[0], argv);
1397 switch (errno)
1399 case ENOENT:
1400 error ("%s: Command not found", argv[0]);
1401 break;
1402 case ENOEXEC:
1404 /* The file is not executable. Try it as a shell script. */
1405 extern char *getenv ();
1406 char *shell;
1407 char **new_argv;
1408 int argc;
1410 shell = getenv ("SHELL");
1411 if (shell == 0)
1412 shell = default_shell;
1414 argc = 1;
1415 while (argv[argc] != 0)
1416 ++argc;
1418 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1419 new_argv[0] = shell;
1420 new_argv[1] = argv[0];
1421 while (argc > 0)
1423 new_argv[1 + argc] = argv[argc];
1424 --argc;
1427 execvp (shell, new_argv);
1428 if (errno == ENOENT)
1429 error ("%s: Shell program not found", shell);
1430 else
1431 perror_with_name ("execvp: ", shell);
1432 break;
1435 default:
1436 perror_with_name ("execvp: ", argv[0]);
1437 break;
1440 _exit (127);
1441 #endif /* !VMS */
1444 #ifndef VMS
1445 /* Figure out the argument list necessary to run LINE as a command. Try to
1446 avoid using a shell. This routine handles only ' quoting, and " quoting
1447 when no backslash, $ or ` characters are seen in the quotes. Starting
1448 quotes may be escaped with a backslash. If any of the characters in
1449 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1450 is the first word of a line, the shell is used.
1452 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1453 If *RESTP is NULL, newlines will be ignored.
1455 SHELL is the shell to use, or nil to use the default shell.
1456 IFS is the value of $IFS, or nil (meaning the default). */
1458 static char **
1459 construct_command_argv_internal (line, restp, shell, ifs)
1460 char *line, **restp;
1461 char *shell, *ifs;
1463 #ifdef __MSDOS__
1464 static char sh_chars[] = "\"|<>";
1465 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1466 "copy", "ctty", "date", "del", "dir", "echo",
1467 "erase", "exit", "for", "goto", "if", "if", "md",
1468 "mkdir", "path", "pause", "prompt", "rem", "ren",
1469 "rename", "set", "shift", "time", "type",
1470 "ver", "verify", "vol", ":", 0 };
1471 #else
1472 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1473 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1474 "logout", "set", "umask", "wait", "while", "for",
1475 "case", "if", ":", ".", "break", "continue",
1476 "export", "read", "readonly", "shift", "times",
1477 "trap", "switch", 0 };
1478 #endif
1479 register int i;
1480 register char *p;
1481 register char *ap;
1482 char *end;
1483 int instring, word_has_equals, seen_nonequals;
1484 char **new_argv = 0;
1486 if (restp != NULL)
1487 *restp = NULL;
1489 /* Make sure not to bother processing an empty line. */
1490 while (isblank (*line))
1491 ++line;
1492 if (*line == '\0')
1493 return 0;
1495 /* See if it is safe to parse commands internally. */
1496 if (shell == 0)
1497 shell = default_shell;
1498 else if (strcmp (shell, default_shell))
1499 goto slow;
1501 if (ifs != 0)
1502 for (ap = ifs; *ap != '\0'; ++ap)
1503 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1504 goto slow;
1506 i = strlen (line) + 1;
1508 /* More than 1 arg per character is impossible. */
1509 new_argv = (char **) xmalloc (i * sizeof (char *));
1511 /* All the args can fit in a buffer as big as LINE is. */
1512 ap = new_argv[0] = (char *) xmalloc (i);
1513 end = ap + i;
1515 /* I is how many complete arguments have been found. */
1516 i = 0;
1517 instring = word_has_equals = seen_nonequals = 0;
1518 for (p = line; *p != '\0'; ++p)
1520 if (ap > end)
1521 abort ();
1523 if (instring)
1525 string_char:
1526 /* Inside a string, just copy any char except a closing quote
1527 or a backslash-newline combination. */
1528 if (*p == instring)
1529 instring = 0;
1530 else if (*p == '\\' && p[1] == '\n')
1531 goto swallow_escaped_newline;
1532 else if (*p == '\n' && restp != NULL)
1534 /* End of the command line. */
1535 *restp = p;
1536 goto end_of_line;
1538 /* Backslash, $, and ` are special inside double quotes.
1539 If we see any of those, punt. */
1540 else if (instring == '"' && index ("\\$`", *p) != 0)
1541 goto slow;
1542 else
1543 *ap++ = *p;
1545 else if (index (sh_chars, *p) != 0)
1546 /* Not inside a string, but it's a special char. */
1547 goto slow;
1548 else
1549 /* Not a special char. */
1550 switch (*p)
1552 case '=':
1553 /* Equals is a special character in leading words before the
1554 first word with no equals sign in it. This is not the case
1555 with sh -k, but we never get here when using nonstandard
1556 shell flags. */
1557 if (! seen_nonequals)
1558 goto slow;
1559 word_has_equals = 1;
1560 *ap++ = '=';
1561 break;
1563 case '\\':
1564 /* Backslash-newline combinations are eaten. */
1565 if (p[1] == '\n')
1567 swallow_escaped_newline:
1569 /* Eat the backslash, the newline, and following whitespace,
1570 replacing it all with a single space. */
1571 p += 2;
1573 /* If there is a tab after a backslash-newline,
1574 remove it from the source line which will be echoed,
1575 since it was most likely used to line
1576 up the continued line with the previous one. */
1577 if (*p == '\t')
1578 strcpy (p, p + 1);
1580 if (instring)
1581 goto string_char;
1582 else
1584 if (ap != new_argv[i])
1585 /* Treat this as a space, ending the arg.
1586 But if it's at the beginning of the arg, it should
1587 just get eaten, rather than becoming an empty arg. */
1588 goto end_of_arg;
1589 else
1590 p = next_token (p) - 1;
1593 else if (p[1] != '\0')
1594 /* Copy and skip the following char. */
1595 *ap++ = *++p;
1596 break;
1598 case '\'':
1599 case '"':
1600 instring = *p;
1601 break;
1603 case '\n':
1604 if (restp != NULL)
1606 /* End of the command line. */
1607 *restp = p;
1608 goto end_of_line;
1610 else
1611 /* Newlines are not special. */
1612 *ap++ = '\n';
1613 break;
1615 case ' ':
1616 case '\t':
1617 end_of_arg:
1618 /* We have the end of an argument.
1619 Terminate the text of the argument. */
1620 *ap++ = '\0';
1621 new_argv[++i] = ap;
1623 /* Update SEEN_NONEQUALS, which tells us if every word
1624 heretofore has contained an `='. */
1625 seen_nonequals |= ! word_has_equals;
1626 if (word_has_equals && ! seen_nonequals)
1627 /* An `=' in a word before the first
1628 word without one is magical. */
1629 goto slow;
1630 word_has_equals = 0; /* Prepare for the next word. */
1632 /* If this argument is the command name,
1633 see if it is a built-in shell command.
1634 If so, have the shell handle it. */
1635 if (i == 1)
1637 register int j;
1638 for (j = 0; sh_cmds[j] != 0; ++j)
1639 if (streq (sh_cmds[j], new_argv[0]))
1640 goto slow;
1643 /* Ignore multiple whitespace chars. */
1644 p = next_token (p);
1645 /* Next iteration should examine the first nonwhite char. */
1646 --p;
1647 break;
1649 default:
1650 *ap++ = *p;
1651 break;
1654 end_of_line:
1656 if (instring)
1657 /* Let the shell deal with an unterminated quote. */
1658 goto slow;
1660 /* Terminate the last argument and the argument list. */
1662 *ap = '\0';
1663 if (new_argv[i][0] != '\0')
1664 ++i;
1665 new_argv[i] = 0;
1667 if (i == 1)
1669 register int j;
1670 for (j = 0; sh_cmds[j] != 0; ++j)
1671 if (streq (sh_cmds[j], new_argv[0]))
1672 goto slow;
1675 if (new_argv[0] == 0)
1676 /* Line was empty. */
1677 return 0;
1678 else
1679 return new_argv;
1681 slow:;
1682 /* We must use the shell. */
1684 if (new_argv != 0)
1686 /* Free the old argument list we were working on. */
1687 free (new_argv[0]);
1688 free ((void *)new_argv);
1691 #ifdef __MSDOS__
1693 FILE *batch;
1694 dos_batch_file = 1;
1695 if (dos_bname == 0)
1697 dos_bname = tempnam (".", "mk");
1698 for (i = 0; dos_bname[i] != '\0'; ++i)
1699 if (dos_bname[i] == '/')
1700 dos_bname[i] = '\\';
1701 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1702 strcpy (dos_bename, dos_bname);
1703 strcat (dos_bname, ".bat");
1704 strcat (dos_bename, ".err");
1706 batch = fopen (dos_bename, "w"); /* Create a file. */
1707 if (batch != NULL)
1708 fclose (batch);
1709 batch = fopen (dos_bname, "w");
1710 fputs ("@echo off\n", batch);
1711 fputs (line, batch);
1712 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1713 fclose (batch);
1714 new_argv = (char **) xmalloc(2 * sizeof(char *));
1715 new_argv[0] = strdup (dos_bname);
1716 new_argv[1] = 0;
1718 #else /* Not MSDOS. */
1720 /* SHELL may be a multi-word command. Construct a command line
1721 "SHELL -c LINE", with all special chars in LINE escaped.
1722 Then recurse, expanding this command line to get the final
1723 argument list. */
1725 unsigned int shell_len = strlen (shell);
1726 static char minus_c[] = " -c ";
1727 unsigned int line_len = strlen (line);
1729 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1730 + (line_len * 2) + 1);
1732 ap = new_line;
1733 bcopy (shell, ap, shell_len);
1734 ap += shell_len;
1735 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1736 ap += sizeof (minus_c) - 1;
1737 for (p = line; *p != '\0'; ++p)
1739 if (restp != NULL && *p == '\n')
1741 *restp = p;
1742 break;
1744 else if (*p == '\\' && p[1] == '\n')
1746 /* Eat the backslash, the newline, and following whitespace,
1747 replacing it all with a single space (which is escaped
1748 from the shell). */
1749 p += 2;
1751 /* If there is a tab after a backslash-newline,
1752 remove it from the source line which will be echoed,
1753 since it was most likely used to line
1754 up the continued line with the previous one. */
1755 if (*p == '\t')
1756 strcpy (p, p + 1);
1758 p = next_token (p);
1759 --p;
1760 *ap++ = '\\';
1761 *ap++ = ' ';
1762 continue;
1765 if (*p == '\\' || *p == '\'' || *p == '"'
1766 || isspace (*p)
1767 || index (sh_chars, *p) != 0)
1768 *ap++ = '\\';
1769 *ap++ = *p;
1771 *ap = '\0';
1773 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1774 (char *) 0, (char *) 0);
1776 #endif /* MSDOS. */
1778 return new_argv;
1781 /* Figure out the argument list necessary to run LINE as a command. Try to
1782 avoid using a shell. This routine handles only ' quoting, and " quoting
1783 when no backslash, $ or ` characters are seen in the quotes. Starting
1784 quotes may be escaped with a backslash. If any of the characters in
1785 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1786 is the first word of a line, the shell is used.
1788 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1789 If *RESTP is NULL, newlines will be ignored.
1791 FILE is the target whose commands these are. It is used for
1792 variable expansion for $(SHELL) and $(IFS). */
1794 char **
1795 construct_command_argv (line, restp, file)
1796 char *line, **restp;
1797 struct file *file;
1799 char *shell, *ifs;
1800 char **argv;
1803 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1804 int save = warn_undefined_variables_flag;
1805 warn_undefined_variables_flag = 0;
1807 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1808 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1810 warn_undefined_variables_flag = save;
1813 argv = construct_command_argv_internal (line, restp, shell, ifs);
1815 free (shell);
1816 free (ifs);
1818 return argv;
1820 #endif /* !VMS */
1822 #ifndef HAVE_DUP2
1824 dup2 (old, new)
1825 int old, new;
1827 int fd;
1829 (void) close (new);
1830 fd = dup (old);
1831 if (fd != new)
1833 (void) close (fd);
1834 errno = EMFILE;
1835 return -1;
1838 return fd;
1840 #endif