Mon May 13 14:37:42 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu>
[make.git] / job.c
blobb2cc86f78672aa42a4641446596ab83a0975730c
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 #ifndef _AMIGA
29 char default_shell[] = "/bin/sh";
30 #else
31 char default_shell[] = "";
32 extern int MyExecute (char **);
33 #endif
35 #ifdef __MSDOS__
36 #include <process.h>
37 static int dos_pid = 123;
38 static int dos_status;
39 static char *dos_bname;
40 static char *dos_bename;
41 static int dos_batch_file;
42 #endif /* MSDOS. */
43 #ifdef _AMIGA
44 #include <proto/dos.h>
45 static int amiga_pid = 123;
46 static int amiga_status;
47 static char amiga_bname[32];
48 static int amiga_batch_file;
49 #endif /* Amiga. */
51 #ifdef VMS
52 #include <time.h>
53 #include <processes.h>
54 #include <starlet.h>
55 #include <lib$routines.h>
56 #endif
58 #ifdef HAVE_FCNTL_H
59 #include <fcntl.h>
60 #else
61 #include <sys/file.h>
62 #endif
64 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
65 #include <sys/wait.h>
66 #endif
68 #ifdef HAVE_WAITPID
69 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
70 #else /* Don't have waitpid. */
71 #ifdef HAVE_WAIT3
72 #ifndef wait3
73 extern int wait3 ();
74 #endif
75 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
76 #endif /* Have wait3. */
77 #endif /* Have waitpid. */
79 #if !defined (wait) && !defined (POSIX)
80 extern int wait ();
81 #endif
83 #ifndef HAVE_UNION_WAIT
85 #define WAIT_T int
87 #ifndef WTERMSIG
88 #define WTERMSIG(x) ((x) & 0x7f)
89 #endif
90 #ifndef WCOREDUMP
91 #define WCOREDUMP(x) ((x) & 0x80)
92 #endif
93 #ifndef WEXITSTATUS
94 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
95 #endif
96 #ifndef WIFSIGNALED
97 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
98 #endif
99 #ifndef WIFEXITED
100 #define WIFEXITED(x) (WTERMSIG (x) == 0)
101 #endif
103 #else /* Have `union wait'. */
105 #define WAIT_T union wait
106 #ifndef WTERMSIG
107 #define WTERMSIG(x) ((x).w_termsig)
108 #endif
109 #ifndef WCOREDUMP
110 #define WCOREDUMP(x) ((x).w_coredump)
111 #endif
112 #ifndef WEXITSTATUS
113 #define WEXITSTATUS(x) ((x).w_retcode)
114 #endif
115 #ifndef WIFSIGNALED
116 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
117 #endif
118 #ifndef WIFEXITED
119 #define WIFEXITED(x) (WTERMSIG(x) == 0)
120 #endif
122 #endif /* Don't have `union wait'. */
124 #ifdef VMS
125 static int vms_jobsefnmask=0;
126 #endif /* !VMS */
128 #ifndef HAVE_UNISTD_H
129 extern int dup2 ();
130 extern int execve ();
131 extern void _exit ();
132 #ifndef VMS
133 extern int geteuid ();
134 extern int getegid ();
135 extern int setgid ();
136 extern int getgid ();
137 #endif
138 #endif
140 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
142 extern int getloadavg PARAMS ((double loadavg[], int nelem));
143 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
144 int *is_remote, int *id_ptr, int *used_stdin));
145 extern int start_remote_job_p PARAMS ((void));
146 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
147 int *coredump_ptr, int block));
149 RETSIGTYPE child_handler PARAMS ((int));
150 static void free_child PARAMS ((struct child *));
151 static void start_job_command PARAMS ((struct child *child));
152 static int load_too_high PARAMS ((void));
153 static int job_next_command PARAMS ((struct child *));
154 static int start_waiting_job PARAMS ((struct child *));
155 #ifdef VMS
156 static void vmsWaitForChildren PARAMS ((int *));
157 #endif
159 /* Chain of all live (or recently deceased) children. */
161 struct child *children = 0;
163 /* Number of children currently running. */
165 unsigned int job_slots_used = 0;
167 /* Nonzero if the `good' standard input is in use. */
169 static int good_stdin_used = 0;
171 /* Chain of children waiting to run until the load average goes down. */
173 static struct child *waiting_jobs = 0;
175 /* Write an error message describing the exit status given in
176 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
177 Append "(ignored)" if IGNORED is nonzero. */
179 static void
180 child_error (target_name, exit_code, exit_sig, coredump, ignored)
181 char *target_name;
182 int exit_code, exit_sig, coredump;
183 int ignored;
185 if (ignored && silent_flag)
186 return;
188 #ifdef VMS
189 if (!(exit_code & 1))
190 error("*** [%s] Error 0x%x%s", target_name, exit_code, ((ignored)? " (ignored)" : ""));
191 #else
192 if (exit_sig == 0)
193 error (ignored ? "[%s] Error %d (ignored)" :
194 "*** [%s] Error %d",
195 target_name, exit_code);
196 else
197 error ("*** [%s] %s%s",
198 target_name, strsignal (exit_sig),
199 coredump ? " (core dumped)" : "");
200 #endif /* VMS */
203 static unsigned int dead_children = 0;
205 #ifdef VMS
206 /* Wait for nchildren children to terminate */
207 static void
208 vmsWaitForChildren(int *status)
210 while (1)
212 if (!vms_jobsefnmask)
214 *status = 0;
215 return;
218 *status = sys$wflor (32, vms_jobsefnmask);
220 return;
222 #endif
225 /* Notice that a child died.
226 reap_children should be called when convenient. */
227 RETSIGTYPE
228 child_handler (sig)
229 int sig;
231 ++dead_children;
233 if (debug_flag)
234 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
237 extern int shell_function_pid, shell_function_completed;
239 /* Reap dead children, storing the returned status and the new command
240 state (`cs_finished') in the `file' member of the `struct child' for the
241 dead child, and removing the child from the chain. If BLOCK nonzero,
242 reap at least one child, waiting for it to die if necessary. If ERR is
243 nonzero, print an error message first. */
245 void
246 reap_children (block, err)
247 int block, err;
249 WAIT_T status;
251 while ((children != 0 || shell_function_pid != 0) &&
252 (block || dead_children > 0))
254 int remote = 0;
255 register int pid;
256 int exit_code, exit_sig, coredump;
257 register struct child *lastc, *c;
258 int child_failed;
259 int any_remote, any_local;
261 if (err && dead_children == 0)
263 /* We might block for a while, so let the user know why. */
264 fflush (stdout);
265 error ("*** Waiting for unfinished jobs....");
268 /* We have one less dead child to reap.
269 The test and decrement are not atomic; if it is compiled into:
270 register = dead_children - 1;
271 dead_children = register;
272 a SIGCHLD could come between the two instructions.
273 child_handler increments dead_children.
274 The second instruction here would lose that increment. But the
275 only effect of dead_children being wrong is that we might wait
276 longer than necessary to reap a child, and lose some parallelism;
277 and we might print the "Waiting for unfinished jobs" message above
278 when not necessary. */
280 if (dead_children > 0)
281 --dead_children;
283 any_remote = 0;
284 any_local = shell_function_pid != -1;
285 for (c = children; c != 0; c = c->next)
287 any_remote |= c->remote;
288 any_local |= ! c->remote;
289 if (debug_flag)
290 printf ("Live child 0x%08lx PID %d%s\n",
291 (unsigned long int) c,
292 c->pid, c->remote ? " (remote)" : "");
293 #ifdef VMS
294 break;
295 #endif
298 /* First, check for remote children. */
299 if (any_remote)
300 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
301 else
302 pid = 0;
304 if (pid < 0)
306 remote_status_lose:
307 #ifdef EINTR
308 if (errno == EINTR)
309 continue;
310 #endif
311 pfatal_with_name ("remote_status");
313 else if (pid == 0)
315 #if !defined(__MSDOS__) && !defined(_AMIGA)
316 /* No remote children. Check for local children. */
318 if (any_local)
320 #ifdef VMS
321 vmsWaitForChildren (&status);
322 pid = c->pid;
323 #else
324 #ifdef WAIT_NOHANG
325 if (!block)
326 pid = WAIT_NOHANG (&status);
327 else
328 #endif
329 pid = wait (&status);
330 #endif /* !VMS */
332 else
333 pid = 0;
335 if (pid < 0)
337 #ifdef EINTR
338 if (errno == EINTR)
339 continue;
340 #endif
341 pfatal_with_name ("wait");
343 else if (pid == 0)
345 /* No local children. */
346 if (block && any_remote)
348 /* Now try a blocking wait for a remote child. */
349 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
350 if (pid < 0)
351 goto remote_status_lose;
352 else if (pid == 0)
353 /* No remote children either. Finally give up. */
354 break;
355 else
356 /* We got a remote child. */
357 remote = 1;
359 else
360 break;
362 else
364 /* Chop the status word up. */
365 exit_code = WEXITSTATUS (status);
366 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
367 coredump = WCOREDUMP (status);
369 #else /* MSDOS. */
370 #ifdef __MSDOS__
371 /* Life is very different on MSDOS. */
372 pid = dos_pid - 1;
373 status = dos_status;
374 exit_code = dos_status;
375 exit_sig = 0;
376 coredump = 0;
377 #else
378 /* Same on Amiga */
379 pid = amiga_pid - 1;
380 status = amiga_status;
381 exit_code = amiga_status;
382 exit_sig = 0;
383 coredump = 0;
384 #endif
385 #endif /* Not MSDOS. */
387 else
388 /* We got a remote child. */
389 remote = 1;
391 /* Check if this is the child of the `shell' function. */
392 if (!remote && pid == shell_function_pid)
394 /* It is. Leave an indicator for the `shell' function. */
395 if (exit_sig == 0 && exit_code == 127)
396 shell_function_completed = -1;
397 else
398 shell_function_completed = 1;
399 break;
402 child_failed = exit_sig != 0 || exit_code != 0;
404 /* Search for a child matching the deceased one. */
405 lastc = 0;
406 for (c = children; c != 0; lastc = c, c = c->next)
407 if (c->remote == remote && c->pid == pid)
408 break;
410 if (c == 0)
412 /* An unknown child died. */
413 char buf[100];
414 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
415 if (child_failed)
416 child_error (buf, exit_code, exit_sig, coredump,
417 ignore_errors_flag);
418 else
419 error ("%s finished.", buf);
421 else
423 if (debug_flag)
424 printf ("Reaping %s child 0x%08lx PID %d%s\n",
425 child_failed ? "losing" : "winning",
426 (unsigned long int) c,
427 c->pid, c->remote ? " (remote)" : "");
429 /* If this child had the good stdin, say it is now free. */
430 if (c->good_stdin)
431 good_stdin_used = 0;
433 if (child_failed && !c->noerror && !ignore_errors_flag)
435 /* The commands failed. Write an error message,
436 delete non-precious targets, and abort. */
437 static int delete_on_error = -1;
438 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
439 c->file->update_status = 2;
440 if (delete_on_error == -1)
442 struct file *f = lookup_file (".DELETE_ON_ERROR");
443 delete_on_error = f != 0 && f->is_target;
445 if (exit_sig != 0 || delete_on_error)
446 delete_child_targets (c);
448 else
450 if (child_failed)
452 /* The commands failed, but we don't care. */
453 child_error (c->file->name,
454 exit_code, exit_sig, coredump, 1);
455 child_failed = 0;
458 /* If there are more commands to run, try to start them. */
459 if (job_next_command (c))
461 if (handling_fatal_signal)
463 /* Never start new commands while we are dying.
464 Since there are more commands that wanted to be run,
465 the target was not completely remade. So we treat
466 this as if a command had failed. */
467 c->file->update_status = 2;
469 else
471 /* Check again whether to start remotely.
472 Whether or not we want to changes over time.
473 Also, start_remote_job may need state set up
474 by start_remote_job_p. */
475 c->remote = start_remote_job_p ();
476 start_job_command (c);
477 /* Fatal signals are left blocked in case we were
478 about to put that child on the chain. But it is
479 already there, so it is safe for a fatal signal to
480 arrive now; it will clean up this child's targets. */
481 unblock_sigs ();
482 if (c->file->command_state == cs_running)
483 /* We successfully started the new command.
484 Loop to reap more children. */
485 continue;
488 if (c->file->update_status != 0)
489 /* We failed to start the commands. */
490 delete_child_targets (c);
492 else
493 /* There are no more commands. We got through them all
494 without an unignored error. Now the target has been
495 successfully updated. */
496 c->file->update_status = 0;
499 /* When we get here, all the commands for C->file are finished
500 (or aborted) and C->file->update_status contains 0 or 2. But
501 C->file->command_state is still cs_running if all the commands
502 ran; notice_finish_file looks for cs_running to tell it that
503 it's interesting to check the file's modtime again now. */
505 if (! handling_fatal_signal)
506 /* Notice if the target of the commands has been changed.
507 This also propagates its values for command_state and
508 update_status to its also_make files. */
509 notice_finished_file (c->file);
511 if (debug_flag)
512 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
513 (unsigned long int) c,
514 c->pid, c->remote ? " (remote)" : "");
516 /* Remove the child from the chain and free it. */
517 if (lastc == 0)
518 children = c->next;
519 else
520 lastc->next = c->next;
521 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
522 free_child (c);
524 /* There is now another slot open. */
525 if (job_slots_used > 0)
526 --job_slots_used;
528 /* If the job failed, and the -k flag was not given, die,
529 unless we are already in the process of dying. */
530 if (!err && child_failed && !keep_going_flag)
531 die (2);
534 /* Only block for one child. */
535 block = 0;
537 return;
540 /* Free the storage allocated for CHILD. */
542 static void
543 free_child (child)
544 register struct child *child;
546 if (child->command_lines != 0)
548 register unsigned int i;
549 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
550 free (child->command_lines[i]);
551 free ((char *) child->command_lines);
554 if (child->environment != 0)
556 register char **ep = child->environment;
557 while (*ep != 0)
558 free (*ep++);
559 free ((char *) child->environment);
562 free ((char *) child);
565 #ifdef POSIX
566 #ifdef __MSDOS__
567 void
568 unblock_sigs ()
570 return;
572 #else
573 extern sigset_t fatal_signal_set;
575 void
576 unblock_sigs ()
578 sigset_t empty;
579 sigemptyset (&empty);
580 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
582 #endif
583 #endif
585 /* Start a job to run the commands specified in CHILD.
586 CHILD is updated to reflect the commands and ID of the child process.
588 NOTE: On return fatal signals are blocked! The caller is responsible
589 for calling `unblock_sigs', once the new child is safely on the chain so
590 it can be cleaned up in the event of a fatal signal. */
592 static void
593 start_job_command (child)
594 register struct child *child;
596 #ifndef _AMIGA
597 static int bad_stdin = -1;
598 #endif
599 register char *p;
600 int flags;
601 #ifdef VMS
602 char *argv;
603 #else
604 char **argv;
605 #endif
607 /* Combine the flags parsed for the line itself with
608 the flags specified globally for this target. */
609 flags = (child->file->command_flags
610 | child->file->cmds->lines_flags[child->command_line - 1]);
612 p = child->command_ptr;
613 child->noerror = flags & COMMANDS_NOERROR;
615 while (*p != '\0')
617 if (*p == '@')
618 flags |= COMMANDS_SILENT;
619 else if (*p == '+')
620 flags |= COMMANDS_RECURSE;
621 else if (*p == '-')
622 child->noerror = 1;
623 else if (!isblank (*p) && *p != '+')
624 break;
625 ++p;
628 /* If -q was given, just say that updating `failed'. The exit status of
629 1 tells the user that -q is saying `something to do'; the exit status
630 for a random error is 2. */
631 if (question_flag && !(flags & COMMANDS_RECURSE))
633 child->file->update_status = 1;
634 notice_finished_file (child->file);
635 return;
638 /* There may be some preceding whitespace left if there
639 was nothing but a backslash on the first line. */
640 p = next_token (p);
642 /* Figure out an argument list from this command line. */
645 char *end = 0;
646 #ifdef VMS
647 argv = p;
648 #else
649 argv = construct_command_argv (p, &end, child->file);
650 #endif
651 if (end == NULL)
652 child->command_ptr = NULL;
653 else
655 *end++ = '\0';
656 child->command_ptr = end;
660 if (touch_flag && !(flags & COMMANDS_RECURSE))
662 /* Go on to the next command. It might be the recursive one.
663 We construct ARGV only to find the end of the command line. */
664 #ifndef VMS
665 free (argv[0]);
666 free ((char *) argv);
667 #endif
668 argv = 0;
671 if (argv == 0)
673 next_command:
674 /* This line has no commands. Go to the next. */
675 if (job_next_command (child))
676 start_job_command (child);
677 else
679 /* No more commands. All done. */
680 child->file->update_status = 0;
681 notice_finished_file (child->file);
683 return;
686 /* Print out the command. If silent, we call `message' with null so it
687 can log the working directory before the command's own error messages
688 appear. */
690 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
691 ? "%s" : (char *) 0, p);
693 /* Tell update_goal_chain that a command has been started on behalf of
694 this target. It is important that this happens here and not in
695 reap_children (where we used to do it), because reap_children might be
696 reaping children from a different target. We want this increment to
697 guaranteedly indicate that a command was started for the dependency
698 chain (i.e., update_file recursion chain) we are processing. */
700 ++commands_started;
702 /* If -n was given, recurse to get the next line in the sequence. */
704 if (just_print_flag && !(flags & COMMANDS_RECURSE))
706 #ifndef VMS
707 free (argv[0]);
708 free ((char *) argv);
709 #endif
710 goto next_command;
713 /* Flush the output streams so they won't have things written twice. */
715 fflush (stdout);
716 fflush (stderr);
718 #ifndef _AMIGA
719 #ifndef VMS
721 /* Set up a bad standard input that reads from a broken pipe. */
723 if (bad_stdin == -1)
725 /* Make a file descriptor that is the read end of a broken pipe.
726 This will be used for some children's standard inputs. */
727 int pd[2];
728 if (pipe (pd) == 0)
730 /* Close the write side. */
731 (void) close (pd[1]);
732 /* Save the read side. */
733 bad_stdin = pd[0];
735 /* Set the descriptor to close on exec, so it does not litter any
736 child's descriptor table. When it is dup2'd onto descriptor 0,
737 that descriptor will not close on exec. */
738 #ifdef FD_SETFD
739 #ifndef FD_CLOEXEC
740 #define FD_CLOEXEC 1
741 #endif
742 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
743 #endif
747 #endif /* !AMIGA */
749 /* Decide whether to give this child the `good' standard input
750 (one that points to the terminal or whatever), or the `bad' one
751 that points to the read side of a broken pipe. */
753 child->good_stdin = !good_stdin_used;
754 if (child->good_stdin)
755 good_stdin_used = 1;
757 #endif /* Not VMS */
759 child->deleted = 0;
761 #ifndef _AMIGA
762 /* Set up the environment for the child. */
763 if (child->environment == 0)
764 child->environment = target_environment (child->file);
765 #endif
767 #if !defined(__MSDOS__) && !defined(_AMIGA)
769 #ifndef VMS
770 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
771 if (child->remote)
773 int is_remote, id, used_stdin;
774 if (start_remote_job (argv, child->environment,
775 child->good_stdin ? 0 : bad_stdin,
776 &is_remote, &id, &used_stdin))
777 goto error;
778 else
780 if (child->good_stdin && !used_stdin)
782 child->good_stdin = 0;
783 good_stdin_used = 0;
785 child->remote = is_remote;
786 child->pid = id;
789 else
790 #endif /* !VMS */
792 /* Fork the child process. */
794 char **parent_environ;
796 #ifdef POSIX
797 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
798 #else
799 #ifdef HAVE_SIGSETMASK
800 (void) sigblock (fatal_signal_mask);
801 #endif
802 #endif
804 child->remote = 0;
806 #ifdef VMS
808 if (!child_execute_job (argv, child)) {
809 /* Fork failed! */
810 perror_with_name ("vfork", "");
811 goto error;
814 #else
816 parent_environ = environ;
817 child->pid = vfork ();
818 environ = parent_environ; /* Restore value child may have clobbered. */
819 if (child->pid == 0)
821 /* We are the child side. */
822 unblock_sigs ();
823 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
824 argv, child->environment);
826 else if (child->pid < 0)
828 /* Fork failed! */
829 unblock_sigs ();
830 perror_with_name ("vfork", "");
831 goto error;
833 #endif /* !VMS */
836 #else /* MSDOS or Amiga. */
837 #ifdef __MSDOS__
838 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
839 ++dead_children;
840 child->pid = dos_pid++;
841 if (dos_batch_file)
843 dos_batch_file = 0;
844 remove (dos_bname); /* Ignore errors. */
845 if (access (dos_bename, 0))
846 dos_status = 1;
847 else
848 dos_status = 0;
849 remove (dos_bename);
851 #else
852 amiga_status = MyExecute (argv);
854 ++dead_children;
855 child->pid = amiga_pid++;
856 if (amiga_batch_file)
858 amiga_batch_file = 0;
859 DeleteFile (amiga_bname); /* Ignore errors. */
861 #endif /* Not Amiga */
862 #endif /* Not MSDOS. */
864 /* We are the parent side. Set the state to
865 say the commands are running and return. */
867 set_command_state (child->file, cs_running);
869 /* Free the storage used by the child's argument list. */
870 #ifndef VMS
871 free (argv[0]);
872 free ((char *) argv);
873 #endif
875 return;
877 error:
878 child->file->update_status = 2;
879 notice_finished_file (child->file);
880 return;
883 /* Try to start a child running.
884 Returns nonzero if the child was started (and maybe finished), or zero if
885 the load was too high and the child was put on the `waiting_jobs' chain. */
887 static int
888 start_waiting_job (c)
889 struct child *c;
891 /* If we can start a job remotely, we always want to, and don't care about
892 the local load average. We record that the job should be started
893 remotely in C->remote for start_job_command to test. */
895 c->remote = start_remote_job_p ();
897 /* If this job is to be started locally, and we are already running
898 some jobs, make this one wait if the load average is too high. */
899 if (!c->remote && job_slots_used > 0 && load_too_high ())
901 /* Put this child on the chain of children waiting
902 for the load average to go down. */
903 set_command_state (c->file, cs_running);
904 c->next = waiting_jobs;
905 waiting_jobs = c;
906 return 0;
909 /* Start the first command; reap_children will run later command lines. */
910 start_job_command (c);
912 switch (c->file->command_state)
914 case cs_running:
915 c->next = children;
916 if (debug_flag)
917 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
918 (unsigned long int) c,
919 c->pid, c->remote ? " (remote)" : "");
920 children = c;
921 /* One more job slot is in use. */
922 ++job_slots_used;
923 unblock_sigs ();
924 break;
926 case cs_not_started:
927 /* All the command lines turned out to be empty. */
928 c->file->update_status = 0;
929 /* FALLTHROUGH */
931 case cs_finished:
932 notice_finished_file (c->file);
933 free_child (c);
934 break;
936 default:
937 assert (c->file->command_state == cs_finished);
938 break;
941 return 1;
944 /* Create a `struct child' for FILE and start its commands running. */
946 void
947 new_job (file)
948 register struct file *file;
950 register struct commands *cmds = file->cmds;
951 register struct child *c;
952 char **lines;
953 register unsigned int i;
955 /* Let any previously decided-upon jobs that are waiting
956 for the load to go down start before this new one. */
957 start_waiting_jobs ();
959 /* Reap any children that might have finished recently. */
960 reap_children (0, 0);
962 /* Chop the commands up into lines if they aren't already. */
963 chop_commands (cmds);
965 if (job_slots != 0)
966 /* Wait for a job slot to be freed up. */
967 while (job_slots_used == job_slots)
968 reap_children (1, 0);
970 /* Expand the command lines and store the results in LINES. */
971 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
972 for (i = 0; i < cmds->ncommand_lines; ++i)
974 /* Collapse backslash-newline combinations that are inside variable
975 or function references. These are left alone by the parser so
976 that they will appear in the echoing of commands (where they look
977 nice); and collapsed by construct_command_argv when it tokenizes.
978 But letting them survive inside function invocations loses because
979 we don't want the functions to see them as part of the text. */
981 char *in, *out, *ref;
983 /* IN points to where in the line we are scanning.
984 OUT points to where in the line we are writing.
985 When we collapse a backslash-newline combination,
986 IN gets ahead out OUT. */
988 in = out = cmds->command_lines[i];
989 while ((ref = index (in, '$')) != 0)
991 ++ref; /* Move past the $. */
993 if (out != in)
994 /* Copy the text between the end of the last chunk
995 we processed (where IN points) and the new chunk
996 we are about to process (where REF points). */
997 bcopy (in, out, ref - in);
999 /* Move both pointers past the boring stuff. */
1000 out += ref - in;
1001 in = ref;
1003 if (*ref == '(' || *ref == '{')
1005 char openparen = *ref;
1006 char closeparen = openparen == '(' ? ')' : '}';
1007 int count;
1008 char *p;
1010 *out++ = *in++; /* Copy OPENPAREN. */
1011 /* IN now points past the opening paren or brace.
1012 Count parens or braces until it is matched. */
1013 count = 0;
1014 while (*in != '\0')
1016 if (*in == closeparen && --count < 0)
1017 break;
1018 else if (*in == '\\' && in[1] == '\n')
1020 /* We have found a backslash-newline inside a
1021 variable or function reference. Eat it and
1022 any following whitespace. */
1024 int quoted = 0;
1025 for (p = in - 1; p > ref && *p == '\\'; --p)
1026 quoted = !quoted;
1028 if (quoted)
1029 /* There were two or more backslashes, so this is
1030 not really a continuation line. We don't collapse
1031 the quoting backslashes here as is done in
1032 collapse_continuations, because the line will
1033 be collapsed again after expansion. */
1034 *out++ = *in++;
1035 else
1037 /* Skip the backslash, newline and
1038 any following whitespace. */
1039 in = next_token (in + 2);
1041 /* Discard any preceding whitespace that has
1042 already been written to the output. */
1043 while (out > ref && isblank (out[-1]))
1044 --out;
1046 /* Replace it all with a single space. */
1047 *out++ = ' ';
1050 else
1052 if (*in == openparen)
1053 ++count;
1055 *out++ = *in++;
1061 /* There are no more references in this line to worry about.
1062 Copy the remaining uninteresting text to the output. */
1063 if (out != in)
1064 strcpy (out, in);
1066 /* Finally, expand the line. */
1067 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1068 file);
1071 /* Start the command sequence, record it in a new
1072 `struct child', and add that to the chain. */
1074 c = (struct child *) xmalloc (sizeof (struct child));
1075 c->file = file;
1076 c->command_lines = lines;
1077 c->command_line = 0;
1078 c->command_ptr = 0;
1079 c->environment = 0;
1081 /* Fetch the first command line to be run. */
1082 job_next_command (c);
1084 /* The job is now primed. Start it running.
1085 (This will notice if there are in fact no commands.) */
1086 (void)start_waiting_job (c);
1088 if (job_slots == 1)
1089 /* Since there is only one job slot, make things run linearly.
1090 Wait for the child to die, setting the state to `cs_finished'. */
1091 while (file->command_state == cs_running)
1092 reap_children (1, 0);
1094 return;
1097 /* Move CHILD's pointers to the next command for it to execute.
1098 Returns nonzero if there is another command. */
1100 static int
1101 job_next_command (child)
1102 struct child *child;
1104 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1106 /* There are no more lines in the expansion of this line. */
1107 if (child->command_line == child->file->cmds->ncommand_lines)
1109 /* There are no more lines to be expanded. */
1110 child->command_ptr = 0;
1111 return 0;
1113 else
1114 /* Get the next line to run. */
1115 child->command_ptr = child->command_lines[child->command_line++];
1117 return 1;
1120 static int
1121 load_too_high ()
1123 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1124 return 1;
1125 #else
1126 double load;
1128 if (max_load_average < 0)
1129 return 0;
1131 make_access ();
1132 if (getloadavg (&load, 1) != 1)
1134 static int lossage = -1;
1135 /* Complain only once for the same error. */
1136 if (lossage == -1 || errno != lossage)
1138 if (errno == 0)
1139 /* An errno value of zero means getloadavg is just unsupported. */
1140 error ("cannot enforce load limits on this operating system");
1141 else
1142 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1144 lossage = errno;
1145 load = 0;
1147 user_access ();
1149 return load >= max_load_average;
1150 #endif
1153 /* Start jobs that are waiting for the load to be lower. */
1155 void
1156 start_waiting_jobs ()
1158 struct child *job;
1160 if (waiting_jobs == 0)
1161 return;
1165 /* Check for recently deceased descendants. */
1166 reap_children (0, 0);
1168 /* Take a job off the waiting list. */
1169 job = waiting_jobs;
1170 waiting_jobs = job->next;
1172 /* Try to start that job. We break out of the loop as soon
1173 as start_waiting_job puts one back on the waiting list. */
1175 while (start_waiting_job (job) && waiting_jobs != 0);
1177 return;
1180 #ifdef VMS
1181 #include <descrip.h>
1182 #include <clidef.h>
1184 /* This is called as an AST when a child process dies (it won't get
1185 interrupted by anything except a higher level AST).
1187 int vmsHandleChildTerm(struct child *child)
1189 int status;
1190 register struct child *lastc, *c;
1191 int child_failed;
1193 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1195 lib$free_ef(&child->efn);
1197 (void) sigblock (fatal_signal_mask);
1199 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1201 /* Search for a child matching the deceased one. */
1202 lastc = 0;
1203 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1204 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1205 #else
1206 c = child;
1207 #endif
1209 if (child_failed && !c->noerror && !ignore_errors_flag)
1211 /* The commands failed. Write an error message,
1212 delete non-precious targets, and abort. */
1213 child_error (c->file->name, c->cstatus, 0, 0, 0);
1214 c->file->update_status = 1;
1215 delete_child_targets (c);
1217 else
1219 if (child_failed)
1221 /* The commands failed, but we don't care. */
1222 child_error (c->file->name, c->cstatus, 0, 0, 1);
1223 child_failed = 0;
1226 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1227 /* If there are more commands to run, try to start them. */
1228 start_job (c);
1230 switch (c->file->command_state)
1232 case cs_running:
1233 /* Successfully started. */
1234 break;
1236 case cs_finished:
1237 if (c->file->update_status != 0) {
1238 /* We failed to start the commands. */
1239 delete_child_targets (c);
1241 break;
1243 default:
1244 error ("internal error: `%s' command_state \
1245 %d in child_handler", c->file->name);
1246 abort ();
1247 break;
1249 #endif /* RECURSIVEJOBS */
1252 /* Set the state flag to say the commands have finished. */
1253 c->file->command_state = cs_finished;
1254 notice_finished_file (c->file);
1256 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1257 /* Remove the child from the chain and free it. */
1258 if (lastc == 0)
1259 children = c->next;
1260 else
1261 lastc->next = c->next;
1262 free_child (c);
1263 #endif /* RECURSIVEJOBS */
1265 /* There is now another slot open. */
1266 if (job_slots_used > 0)
1267 --job_slots_used;
1269 /* If the job failed, and the -k flag was not given, die. */
1270 if (child_failed && !keep_going_flag)
1271 die (EXIT_FAILURE);
1273 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1275 return 1;
1278 /* VMS:
1279 Spawn a process executing the command in ARGV and return its pid. */
1281 #define MAXCMDLEN 200
1284 child_execute_job (argv, child)
1285 char *argv;
1286 struct child *child;
1288 int i;
1289 static struct dsc$descriptor_s cmddsc;
1290 #ifndef DONTWAITFORCHILD
1291 int spflags = 0;
1292 #else
1293 int spflags = CLI$M_NOWAIT;
1294 #endif
1295 int status;
1296 char cmd[4096],*p,*c;
1297 char comname[50];
1299 /* Remove backslashes */
1300 for (p = argv, c = cmd; *p; p++,c++)
1302 if (*p == '\\') p++;
1303 *c = *p;
1305 *c = *p;
1307 /* check for maximum dcl length and create *.com file if neccesary */
1309 comname[0] = '\0';
1311 if (strlen (cmd) > MAXCMDLEN)
1313 FILE *outfile;
1314 char tmp;
1316 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1317 (void) mktemp (comname);
1319 outfile = fopen (comname, "w");
1320 if (outfile == 0)
1321 pfatal_with_name (comname);
1323 fprintf (outfile, "$ ");
1324 c = cmd;
1326 while (c)
1328 p = strchr (c, ',');
1329 if ((p == NULL) || (p-c > MAXCMDLEN))
1330 p = strchr (c, ' ');
1331 if (p != NULL)
1333 p++;
1334 tmp = *p;
1335 *p = '\0';
1337 else
1338 tmp = '\0';
1339 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1340 if (p != NULL)
1341 *p = tmp;
1342 c = p;
1345 fclose (outfile);
1347 sprintf (cmd, "$ @%s", comname);
1349 if (debug_flag)
1350 printf ("Executing %s instead\n", cmd);
1353 cmddsc.dsc$w_length = strlen(cmd);
1354 cmddsc.dsc$a_pointer = cmd;
1355 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1356 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1358 child->efn = 0;
1359 while (child->efn < 32 || child->efn > 63)
1361 status = lib$get_ef(&child->efn);
1362 if (!(status & 1))
1363 return 0;
1366 sys$clref(child->efn);
1368 vms_jobsefnmask |= (1 << (child->efn - 32));
1370 #ifndef DONTWAITFORCHILD
1371 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1372 &child->efn,0,0);
1373 vmsHandleChildTerm(child);
1374 #else
1375 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1376 &child->efn,vmsHandleChildTerm,child);
1377 #endif
1379 if (!(status & 1))
1381 printf("Error spawning, %d\n",status);
1382 fflush(stdout);
1385 unlink (comname);
1387 return (status & 1);
1390 #else /* !VMS */
1392 #ifndef _AMIGA
1393 /* UNIX:
1394 Replace the current process with one executing the command in ARGV.
1395 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1396 the environment of the new program. This function does not return. */
1398 void
1399 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1400 int stdin_fd, stdout_fd;
1401 char **argv, **envp;
1403 if (stdin_fd != 0)
1404 (void) dup2 (stdin_fd, 0);
1405 if (stdout_fd != 1)
1406 (void) dup2 (stdout_fd, 1);
1407 if (stdin_fd != 0)
1408 (void) close (stdin_fd);
1409 if (stdout_fd != 1)
1410 (void) close (stdout_fd);
1412 /* Run the command. */
1413 exec_command (argv, envp);
1415 #endif /* !AMIGA */
1416 #endif /* !VMS */
1418 #ifndef _AMIGA
1419 /* Replace the current process with one running the command in ARGV,
1420 with environment ENVP. This function does not return. */
1422 void
1423 exec_command (argv, envp)
1424 char **argv, **envp;
1426 #ifdef VMS
1427 /* Run the program. */
1428 execve (argv[0], argv, envp);
1429 perror_with_name ("execve: ", argv[0]);
1430 _exit (EXIT_FAILURE);
1431 #else
1432 /* Be the user, permanently. */
1433 child_access ();
1435 /* Run the program. */
1436 environ = envp;
1437 execvp (argv[0], argv);
1439 switch (errno)
1441 case ENOENT:
1442 error ("%s: Command not found", argv[0]);
1443 break;
1444 case ENOEXEC:
1446 /* The file is not executable. Try it as a shell script. */
1447 extern char *getenv ();
1448 char *shell;
1449 char **new_argv;
1450 int argc;
1452 shell = getenv ("SHELL");
1453 if (shell == 0)
1454 shell = default_shell;
1456 argc = 1;
1457 while (argv[argc] != 0)
1458 ++argc;
1460 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1461 new_argv[0] = shell;
1462 new_argv[1] = argv[0];
1463 while (argc > 0)
1465 new_argv[1 + argc] = argv[argc];
1466 --argc;
1469 execvp (shell, new_argv);
1470 if (errno == ENOENT)
1471 error ("%s: Shell program not found", shell);
1472 else
1473 perror_with_name ("execvp: ", shell);
1474 break;
1477 default:
1478 perror_with_name ("execvp: ", argv[0]);
1479 break;
1482 _exit (127);
1483 #endif /* !VMS */
1485 #else /* On Amiga */
1486 void exec_command (argv)
1487 char **argv;
1489 MyExecute (argv);
1492 void clean_tmp (void)
1494 DeleteFile (amiga_bname);
1497 #endif /* An Amiga */
1499 #ifndef VMS
1500 /* Figure out the argument list necessary to run LINE as a command. Try to
1501 avoid using a shell. This routine handles only ' quoting, and " quoting
1502 when no backslash, $ or ` characters are seen in the quotes. Starting
1503 quotes may be escaped with a backslash. If any of the characters in
1504 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1505 is the first word of a line, the shell is used.
1507 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1508 If *RESTP is NULL, newlines will be ignored.
1510 SHELL is the shell to use, or nil to use the default shell.
1511 IFS is the value of $IFS, or nil (meaning the default). */
1513 static char **
1514 construct_command_argv_internal (line, restp, shell, ifs)
1515 char *line, **restp;
1516 char *shell, *ifs;
1518 #ifdef __MSDOS__
1519 static char sh_chars[] = "\"|<>";
1520 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1521 "copy", "ctty", "date", "del", "dir", "echo",
1522 "erase", "exit", "for", "goto", "if", "if", "md",
1523 "mkdir", "path", "pause", "prompt", "rem", "ren",
1524 "rename", "set", "shift", "time", "type",
1525 "ver", "verify", "vol", ":", 0 };
1526 #endif
1527 #ifdef _AMIGA
1528 static char sh_chars[] = "#;\"|<>()?*$`";
1529 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1530 "rename", "set", "setenv", "date", "makedir",
1531 "skip", "else", "endif", "path", "prompt",
1532 "unset", "unsetenv", "version",
1533 0 };
1534 #else
1535 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1536 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1537 "logout", "set", "umask", "wait", "while", "for",
1538 "case", "if", ":", ".", "break", "continue",
1539 "export", "read", "readonly", "shift", "times",
1540 "trap", "switch", 0 };
1541 #endif
1542 register int i;
1543 register char *p;
1544 register char *ap;
1545 char *end;
1546 int instring, word_has_equals, seen_nonequals;
1547 char **new_argv = 0;
1549 if (restp != NULL)
1550 *restp = NULL;
1552 /* Make sure not to bother processing an empty line. */
1553 while (isblank (*line))
1554 ++line;
1555 if (*line == '\0')
1556 return 0;
1558 /* See if it is safe to parse commands internally. */
1559 if (shell == 0)
1560 shell = default_shell;
1561 else if (strcmp (shell, default_shell))
1562 goto slow;
1564 if (ifs != 0)
1565 for (ap = ifs; *ap != '\0'; ++ap)
1566 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1567 goto slow;
1569 i = strlen (line) + 1;
1571 /* More than 1 arg per character is impossible. */
1572 new_argv = (char **) xmalloc (i * sizeof (char *));
1574 /* All the args can fit in a buffer as big as LINE is. */
1575 ap = new_argv[0] = (char *) xmalloc (i);
1576 end = ap + i;
1578 /* I is how many complete arguments have been found. */
1579 i = 0;
1580 instring = word_has_equals = seen_nonequals = 0;
1581 for (p = line; *p != '\0'; ++p)
1583 if (ap > end)
1584 abort ();
1586 if (instring)
1588 string_char:
1589 /* Inside a string, just copy any char except a closing quote
1590 or a backslash-newline combination. */
1591 if (*p == instring)
1592 instring = 0;
1593 else if (*p == '\\' && p[1] == '\n')
1594 goto swallow_escaped_newline;
1595 else if (*p == '\n' && restp != NULL)
1597 /* End of the command line. */
1598 *restp = p;
1599 goto end_of_line;
1601 /* Backslash, $, and ` are special inside double quotes.
1602 If we see any of those, punt. */
1603 else if (instring == '"' && index ("\\$`", *p) != 0)
1604 goto slow;
1605 else
1606 *ap++ = *p;
1608 else if (index (sh_chars, *p) != 0)
1609 /* Not inside a string, but it's a special char. */
1610 goto slow;
1611 else
1612 /* Not a special char. */
1613 switch (*p)
1615 case '=':
1616 /* Equals is a special character in leading words before the
1617 first word with no equals sign in it. This is not the case
1618 with sh -k, but we never get here when using nonstandard
1619 shell flags. */
1620 if (! seen_nonequals)
1621 goto slow;
1622 word_has_equals = 1;
1623 *ap++ = '=';
1624 break;
1626 case '\\':
1627 /* Backslash-newline combinations are eaten. */
1628 if (p[1] == '\n')
1630 swallow_escaped_newline:
1632 /* Eat the backslash, the newline, and following whitespace,
1633 replacing it all with a single space. */
1634 p += 2;
1636 /* If there is a tab after a backslash-newline,
1637 remove it from the source line which will be echoed,
1638 since it was most likely used to line
1639 up the continued line with the previous one. */
1640 if (*p == '\t')
1641 strcpy (p, p + 1);
1643 if (instring)
1644 goto string_char;
1645 else
1647 if (ap != new_argv[i])
1648 /* Treat this as a space, ending the arg.
1649 But if it's at the beginning of the arg, it should
1650 just get eaten, rather than becoming an empty arg. */
1651 goto end_of_arg;
1652 else
1653 p = next_token (p) - 1;
1656 else if (p[1] != '\0')
1657 /* Copy and skip the following char. */
1658 *ap++ = *++p;
1659 break;
1661 case '\'':
1662 case '"':
1663 instring = *p;
1664 break;
1666 case '\n':
1667 if (restp != NULL)
1669 /* End of the command line. */
1670 *restp = p;
1671 goto end_of_line;
1673 else
1674 /* Newlines are not special. */
1675 *ap++ = '\n';
1676 break;
1678 case ' ':
1679 case '\t':
1680 end_of_arg:
1681 /* We have the end of an argument.
1682 Terminate the text of the argument. */
1683 *ap++ = '\0';
1684 new_argv[++i] = ap;
1686 /* Update SEEN_NONEQUALS, which tells us if every word
1687 heretofore has contained an `='. */
1688 seen_nonequals |= ! word_has_equals;
1689 if (word_has_equals && ! seen_nonequals)
1690 /* An `=' in a word before the first
1691 word without one is magical. */
1692 goto slow;
1693 word_has_equals = 0; /* Prepare for the next word. */
1695 /* If this argument is the command name,
1696 see if it is a built-in shell command.
1697 If so, have the shell handle it. */
1698 if (i == 1)
1700 register int j;
1701 for (j = 0; sh_cmds[j] != 0; ++j)
1702 if (streq (sh_cmds[j], new_argv[0]))
1703 goto slow;
1706 /* Ignore multiple whitespace chars. */
1707 p = next_token (p);
1708 /* Next iteration should examine the first nonwhite char. */
1709 --p;
1710 break;
1712 default:
1713 *ap++ = *p;
1714 break;
1717 end_of_line:
1719 if (instring)
1720 /* Let the shell deal with an unterminated quote. */
1721 goto slow;
1723 /* Terminate the last argument and the argument list. */
1725 *ap = '\0';
1726 if (new_argv[i][0] != '\0')
1727 ++i;
1728 new_argv[i] = 0;
1730 if (i == 1)
1732 register int j;
1733 for (j = 0; sh_cmds[j] != 0; ++j)
1734 if (streq (sh_cmds[j], new_argv[0]))
1735 goto slow;
1738 if (new_argv[0] == 0)
1739 /* Line was empty. */
1740 return 0;
1741 else
1742 return new_argv;
1744 slow:;
1745 /* We must use the shell. */
1747 if (new_argv != 0)
1749 /* Free the old argument list we were working on. */
1750 free (new_argv[0]);
1751 free ((void *)new_argv);
1754 #ifdef __MSDOS__
1756 FILE *batch;
1757 dos_batch_file = 1;
1758 if (dos_bname == 0)
1760 dos_bname = tempnam (".", "mk");
1761 for (i = 0; dos_bname[i] != '\0'; ++i)
1762 if (dos_bname[i] == '/')
1763 dos_bname[i] = '\\';
1764 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1765 strcpy (dos_bename, dos_bname);
1766 strcat (dos_bname, ".bat");
1767 strcat (dos_bename, ".err");
1769 batch = fopen (dos_bename, "w"); /* Create a file. */
1770 if (batch != NULL)
1771 fclose (batch);
1772 batch = fopen (dos_bname, "w");
1773 fputs ("@echo off\n", batch);
1774 fputs (line, batch);
1775 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1776 fclose (batch);
1777 new_argv = (char **) xmalloc(2 * sizeof(char *));
1778 new_argv[0] = strdup (dos_bname);
1779 new_argv[1] = 0;
1781 #endif /* MSDOS. */
1782 #ifdef _AMIGA
1784 char *ptr;
1785 char *buffer;
1786 char *dptr;
1788 buffer = (char *)xmalloc (strlen (line)+1);
1790 ptr = line;
1791 for (dptr=buffer; *ptr; )
1793 if (*ptr == '\\' && ptr[1] == '\n')
1794 ptr += 2;
1795 else if (*ptr == '@') /* Kludge: multiline commands */
1797 ptr += 2;
1798 *dptr++ = '\n';
1800 else
1801 *dptr++ = *ptr++;
1803 *dptr = 0;
1805 new_argv = (char **) xmalloc(2 * sizeof(char *));
1806 new_argv[0] = buffer;
1807 new_argv[1] = 0;
1809 #else /* Not MSDOS or Amiga */
1811 /* SHELL may be a multi-word command. Construct a command line
1812 "SHELL -c LINE", with all special chars in LINE escaped.
1813 Then recurse, expanding this command line to get the final
1814 argument list. */
1816 unsigned int shell_len = strlen (shell);
1817 static char minus_c[] = " -c ";
1818 unsigned int line_len = strlen (line);
1820 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1821 + (line_len * 2) + 1);
1823 ap = new_line;
1824 bcopy (shell, ap, shell_len);
1825 ap += shell_len;
1826 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1827 ap += sizeof (minus_c) - 1;
1828 for (p = line; *p != '\0'; ++p)
1830 if (restp != NULL && *p == '\n')
1832 *restp = p;
1833 break;
1835 else if (*p == '\\' && p[1] == '\n')
1837 /* Eat the backslash, the newline, and following whitespace,
1838 replacing it all with a single space (which is escaped
1839 from the shell). */
1840 p += 2;
1842 /* If there is a tab after a backslash-newline,
1843 remove it from the source line which will be echoed,
1844 since it was most likely used to line
1845 up the continued line with the previous one. */
1846 if (*p == '\t')
1847 strcpy (p, p + 1);
1849 p = next_token (p);
1850 --p;
1851 *ap++ = '\\';
1852 *ap++ = ' ';
1853 continue;
1856 if (*p == '\\' || *p == '\'' || *p == '"'
1857 || isspace (*p)
1858 || index (sh_chars, *p) != 0)
1859 *ap++ = '\\';
1860 *ap++ = *p;
1862 *ap = '\0';
1864 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1865 (char *) 0, (char *) 0);
1867 #endif /* Not MSDOS nor Amiga. */
1869 return new_argv;
1872 /* Figure out the argument list necessary to run LINE as a command. Try to
1873 avoid using a shell. This routine handles only ' quoting, and " quoting
1874 when no backslash, $ or ` characters are seen in the quotes. Starting
1875 quotes may be escaped with a backslash. If any of the characters in
1876 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1877 is the first word of a line, the shell is used.
1879 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1880 If *RESTP is NULL, newlines will be ignored.
1882 FILE is the target whose commands these are. It is used for
1883 variable expansion for $(SHELL) and $(IFS). */
1885 char **
1886 construct_command_argv (line, restp, file)
1887 char *line, **restp;
1888 struct file *file;
1890 char *shell, *ifs;
1891 char **argv;
1894 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1895 int save = warn_undefined_variables_flag;
1896 warn_undefined_variables_flag = 0;
1898 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1899 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1901 warn_undefined_variables_flag = save;
1904 argv = construct_command_argv_internal (line, restp, shell, ifs);
1906 free (shell);
1907 free (ifs);
1909 return argv;
1911 #endif /* !VMS */
1913 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
1915 dup2 (old, new)
1916 int old, new;
1918 int fd;
1920 (void) close (new);
1921 fd = dup (old);
1922 if (fd != new)
1924 (void) close (fd);
1925 errno = EMFILE;
1926 return -1;
1929 return fd;
1931 #endif /* !HAPE_DUP2 && !_AMIGA */