FreeBSD-Date: 2005/04/01 10:53:43
[dragonfly.git] / usr.bin / make / job.c
CommitLineData
edf6dd37 1/*-
9a309bcc
MD
2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
984263bc
MD
4 * Copyright (c) 1988, 1989 by Adam de Boor
5 * Copyright (c) 1989 by Berkeley Softworks
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Adam de Boor.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
1de703da
MD
38 *
39 * @(#)job.c 8.2 (Berkeley) 3/19/94
1901cbd2 40 * $FreeBSD: src/usr.bin/make/job.c,v 1.75 2005/02/10 14:32:14 harti Exp $
df64c352 41 * $DragonFly: src/usr.bin/make/job.c,v 1.50 2005/04/07 00:44:18 okumoto Exp $
984263bc
MD
42 */
43
984263bc 44#ifndef OLD_JOKE
b83dbac0 45#define OLD_JOKE 0
984263bc
MD
46#endif /* OLD_JOKE */
47
48/*-
49 * job.c --
50 * handle the creation etc. of our child processes.
51 *
52 * Interface:
df64c352 53 * Job_Make Start the creation of the given target.
984263bc 54 *
df64c352
MO
55 * Job_CatchChildren
56 * Check for and handle the termination of any children.
57 * This must be called reasonably frequently to keep the
58 * whole make going at a decent clip, since job table
59 * entries aren't removed until their process is caught
60 * this way. Its single argument is TRUE if the function
61 * should block waiting for a child to terminate.
984263bc 62 *
df64c352
MO
63 * Job_CatchOutput Print any output our children have produced. Should
64 * also be called fairly frequently to keep the user
65 * informed of what's going on. If no output is waiting,
66 * it will block for a time given by the SEL_* constants,
67 * below, or until output is ready.
984263bc 68 *
df64c352
MO
69 * Job_Init Called to intialize this module. in addition, any
70 * commands attached to the .BEGIN target are executed
71 * before this function returns. Hence, the makefile must
72 * have been parsed before this function is called.
984263bc 73 *
df64c352 74 * Job_Full Return TRUE if the job table is filled.
984263bc 75 *
df64c352 76 * Job_Empty Return TRUE if the job table is completely empty.
984263bc 77 *
df64c352
MO
78 * Job_ParseShell Given the line following a .SHELL target, parse the
79 * line as a shell specification. Returns FAILURE if the
80 * spec was incorrect.
984263bc 81 *
df64c352
MO
82 * Job_Finish Perform any final processing which needs doing. This
83 * includes the execution of any commands which have
84 * been/were attached to the .END target. It should only
85 * be called when the job table is empty.
984263bc 86 *
df64c352
MO
87 * Job_AbortAll Abort all currently running jobs. It doesn't handle
88 * output or do anything for the jobs, just kills them.
89 * It should only be called in an emergency, as it were.
984263bc 90 *
df64c352
MO
91 * Job_CheckCommands
92 * Verify that the commands for a target are ok. Provide
93 * them if necessary and possible.
984263bc 94 *
df64c352 95 * Job_Touch Update a target without really updating it.
984263bc 96 *
df64c352 97 * Job_Wait Wait for all currently-running jobs to finish.
984263bc
MD
98 */
99
100#include <sys/types.h>
9863ce62 101#include <sys/select.h>
984263bc 102#include <sys/stat.h>
edf6dd37
MO
103#ifdef USE_KQUEUE
104#include <sys/event.h>
105#endif
984263bc 106#include <sys/wait.h>
9863ce62 107#include <ctype.h>
984263bc 108#include <errno.h>
ef1537e7 109#include <fcntl.h>
edf6dd37 110#include <string.h>
984263bc 111#include <signal.h>
9863ce62 112#include <stdlib.h>
d0f0ba15 113#include <unistd.h>
ef1537e7 114#include <utime.h>
9863ce62 115
9863ce62 116#include "arch.h"
b0ef9278 117#include "buf.h"
9863ce62 118#include "compat.h"
984263bc 119#include "dir.h"
9863ce62
MO
120#include "globals.h"
121#include "GNode.h"
984263bc 122#include "job.h"
9863ce62
MO
123#include "make.h"
124#include "parse.h"
984263bc 125#include "pathnames.h"
9863ce62
MO
126#include "str.h"
127#include "targ.h"
128#include "util.h"
129#include "var.h"
a34ec481
JS
130
131#define STATIC static
984263bc
MD
132
133/*
134 * error handling variables
135 */
df64c352
MO
136static int errors = 0; /* number of errors reported */
137static int aborting = 0; /* why is the make aborting? */
138#define ABORT_ERROR 1 /* Because of an error */
139#define ABORT_INTERRUPT 2 /* Because it was interrupted */
140#define ABORT_WAIT 3 /* Waiting for jobs to finish */
984263bc
MD
141
142/*
143 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
144 * is a char! So when we go above 127 we turn negative!
145 */
fbfaa208 146#define FILENO(a) ((unsigned)fileno(a))
984263bc
MD
147
148/*
149 * post-make command processing. The node postCommands is really just the
150 * .END target but we keep it around to avoid having to search for it
151 * all the time.
152 */
df64c352
MO
153static GNode *postCommands;
154
155/*
156 * The number of commands actually printed for a target. Should this
157 * number be 0, no shell will be executed.
158 */
159static int numCommands;
984263bc
MD
160
161/*
162 * Return values from JobStart.
163 */
df64c352
MO
164#define JOB_RUNNING 0 /* Job is running */
165#define JOB_ERROR 1 /* Error in starting the job */
166#define JOB_FINISHED 2 /* The job is already finished */
167#define JOB_STOPPED 3 /* The job is stopped */
984263bc
MD
168
169/*
170 * tfile is used to build temp file names to store shell commands to
fbfaa208 171 * execute.
984263bc 172 */
df64c352 173static char tfile[sizeof(TMPPAT)];
984263bc 174
984263bc
MD
175/*
176 * Descriptions for various shells.
177 */
899365c2 178static const DEF_SHELL_STRUCT(CShell, const) shells[] = {
df64c352
MO
179 /*
180 * CSH description. The csh can do echo control by playing
181 * with the setting of the 'echo' shell variable. Sadly,
182 * however, it is unable to do error control nicely.
183 */
184 {
185 "csh",
186 TRUE, "unset verbose", "set verbose", "unset verbose", 13,
187 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
188 "v", "e",
189 },
190 /*
191 * SH description. Echo control is also possible and, under
192 * sun UNIX anyway, one can even control error checking.
193 */
194 {
195 "sh",
196 TRUE, "set -", "set -v", "set -", 5,
197 TRUE, "set -e", "set +e",
984263bc 198#ifdef OLDBOURNESHELL
df64c352 199 FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
984263bc 200#endif
df64c352
MO
201 "v", "e",
202 },
203 /*
204 * KSH description. The Korn shell has a superset of
205 * the Bourne shell's functionality.
206 */
207 {
208 "ksh",
209 TRUE, "set -", "set -v", "set -", 5,
210 TRUE, "set -e", "set +e",
211 "v", "e",
212 },
984263bc 213};
984263bc 214
df64c352
MO
215/*
216 * This is the shell to which we pass all commands in the Makefile.
217 * It is set by the Job_ParseShell function.
218 */
219static Shell *commandShell = NULL;
220char *shellPath = NULL; /* full pathname of executable image */
221char *shellName = NULL; /* last component of shell */
984263bc 222
df64c352
MO
223int maxJobs; /* The most children we can run at once */
224STATIC int nJobs; /* The number of children currently running */
0a7e0b85
MO
225
226/* The structures that describe them */
df64c352 227STATIC Lst jobs = Lst_Initializer(jobs);
0a7e0b85 228
984263bc
MD
229STATIC Boolean jobFull; /* Flag to tell when the job table is full. It
230 * is set TRUE when (1) the total number of
a34ec481 231 * running jobs equals the maximum allowed */
218b5aa1
MD
232#ifdef USE_KQUEUE
233static int kqfd; /* File descriptor obtained by kqueue() */
234#else
984263bc
MD
235static fd_set outputs; /* Set of descriptors of pipes connected to
236 * the output channels of children */
237#endif
238
239STATIC GNode *lastNode; /* The node for which output was most recently
240 * produced. */
271e747f 241STATIC const char *targFmt; /* Format string to use to head output from a
984263bc
MD
242 * job when it's not the most-recent job heard
243 * from */
244
a34ec481
JS
245#define TARG_FMT "--- %s ---\n" /* Default format */
246#define MESSAGE(fp, gn) \
fbfaa208 247 fprintf(fp, targFmt, gn->name);
984263bc
MD
248
249/*
a34ec481
JS
250 * When JobStart attempts to run a job but isn't allowed to
251 * or when Job_CatchChildren detects a job that has
252 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
984263bc 253 * when the next job finishes.
0a7e0b85
MO
254 *
255 * Lst of Job structures describing jobs that were stopped due to
256 * concurrency limits or externally
984263bc 257 */
0a7e0b85 258STATIC Lst stoppedJobs = Lst_Initializer(stoppedJobs);
984263bc 259
aa582f64
MO
260STATIC int fifoFd; /* Fd of our job fifo */
261STATIC char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
262STATIC int fifoMaster;
984263bc 263
89a1b397
JS
264static sig_atomic_t interrupted;
265
266
984263bc
MD
267#if defined(USE_PGRP) && defined(SYSV)
268# define KILL(pid, sig) killpg(-(pid), (sig))
269#else
270# if defined(USE_PGRP)
271# define KILL(pid, sig) killpg((pid), (sig))
272# else
273# define KILL(pid, sig) kill((pid), (sig))
274# endif
275#endif
276
277/*
278 * Grmpf... There is no way to set bits of the wait structure
279 * anymore with the stupid W*() macros. I liked the union wait
280 * stuff much more. So, we devise our own macros... This is
281 * really ugly, use dramamine sparingly. You have been warned.
282 */
913800f5 283#define W_SETMASKED(st, val, fun) \
984263bc 284 { \
fbfaa208 285 int sh = (int)~0; \
984263bc
MD
286 int mask = fun(sh); \
287 \
288 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
289 continue; \
290 *(st) = (*(st) & ~mask) | ((val) << sh); \
291 }
292
913800f5
MD
293#define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
294#define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
984263bc 295
2d8a3be7 296static void JobPassSig(int);
9edd457e 297static int JobPrintCommand(void *, void *);
2d8a3be7 298static void JobClose(Job *);
2d8a3be7
EN
299static void JobFinish(Job *, int *);
300static void JobExec(Job *, char **);
2d8a3be7
EN
301static void JobMakeArgv(Job *, char **);
302static void JobRestart(Job *);
303static int JobStart(GNode *, int, Job *);
304static char *JobOutput(Job *, char *, char *, int);
305static void JobDoOutput(Job *, Boolean);
899365c2 306static Shell *JobMatchShell(const char *);
2d8a3be7
EN
307static void JobInterrupt(int, int);
308static void JobRestartJobs(void);
984263bc 309
df64c352 310/**
89a1b397 311 * JobCatchSignal
df64c352
MO
312 * Got a signal. Set global variables and hope that someone will
313 * handle it.
89a1b397
JS
314 */
315static void
316JobCatchSig(int signo)
317{
318
319 interrupted = signo;
320}
321
df64c352 322/**
984263bc 323 * JobCondPassSig --
3637a988 324 * Pass a signal to all jobs
984263bc
MD
325 *
326 * Side Effects:
327 * None, except the job may bite it.
984263bc 328 */
3637a988
MO
329static void
330JobCondPassSig(int signo)
984263bc 331{
3637a988
MO
332 LstNode *ln;
333 Job *job;
a34ec481 334
3637a988
MO
335 LST_FOREACH(ln, &jobs) {
336 job = Lst_Datum(ln);
337
338 DEBUGF(JOB, ("JobCondPassSig passing signal %d to child %d.\n",
339 signo, job->pid));
340 KILL(job->pid, signo);
341 }
984263bc
MD
342}
343
df64c352 344/**
984263bc 345 * JobPassSig --
a34ec481 346 * Pass a signal on to all local jobs if
984263bc
MD
347 * USE_PGRP is defined, then die ourselves.
348 *
984263bc
MD
349 * Side Effects:
350 * We die by the same signal.
984263bc
MD
351 */
352static void
84de9e23 353JobPassSig(int signo)
984263bc 354{
df64c352
MO
355 sigset_t nmask, omask;
356 struct sigaction act;
357
358 sigemptyset(&nmask);
359 sigaddset(&nmask, signo);
360 sigprocmask(SIG_SETMASK, &nmask, &omask);
361
362 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
363 JobCondPassSig(signo);
364
365 /*
366 * Deal with proper cleanup based on the signal received. We only run
367 * the .INTERRUPT target if the signal was in fact an interrupt.
368 * The other three termination signals are more of a "get out *now*"
369 * command.
370 */
371 if (signo == SIGINT) {
372 JobInterrupt(TRUE, signo);
373 } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
374 JobInterrupt(FALSE, signo);
375 }
376
377 /*
378 * Leave gracefully if SIGQUIT, rather than core dumping.
379 */
380 if (signo == SIGQUIT) {
381 signo = SIGINT;
382 }
383
384 /*
385 * Send ourselves the signal now we've given the message to everyone
386 * else. Note we block everything else possible while we're getting
387 * the signal. This ensures that all our jobs get continued when we
388 * wake up before we take any other signal.
389 * XXX this comment seems wrong.
390 */
391 act.sa_handler = SIG_DFL;
392 sigemptyset(&act.sa_mask);
393 act.sa_flags = 0;
394 sigaction(signo, &act, NULL);
395
396 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
397 ~0 & ~(1 << (signo - 1))));
398 signal(signo, SIG_DFL);
399
400 KILL(getpid(), signo);
401
402 signo = SIGCONT;
403 JobCondPassSig(signo);
404
405 sigprocmask(SIG_SETMASK, &omask, NULL);
406 sigprocmask(SIG_SETMASK, &omask, NULL);
407 act.sa_handler = JobPassSig;
408 sigaction(signo, &act, NULL);
984263bc
MD
409}
410
df64c352 411/**
984263bc
MD
412 * JobPrintCommand --
413 * Put out another command for the given job. If the command starts
414 * with an @ or a - we process it specially. In the former case,
415 * so long as the -s and -n flags weren't given to make, we stick
416 * a shell-specific echoOff command in the script. In the latter,
417 * we ignore errors for the entire job, unless the shell has error
418 * control.
419 * If the command is just "..." we take all future commands for this
420 * job to be commands to be executed once the entire graph has been
421 * made and return non-zero to signal that the end of the commands
422 * was reached. These commands are later attached to the postCommands
9a309bcc 423 * node and executed by Job_Finish when all things are done.
3637a988 424 * This function is called from JobStart via LST_FOREACH.
984263bc
MD
425 *
426 * Results:
427 * Always 0, unless the command was "..."
428 *
429 * Side Effects:
430 * If the command begins with a '-' and the shell has no error control,
431 * the JOB_IGNERR flag is set in the job descriptor.
432 * If the command is "..." and we're not ignoring such things,
433 * tailCmds is set to the successor node of the cmd.
434 * numCommands is incremented if the command is actually printed.
984263bc
MD
435 */
436static int
84de9e23 437JobPrintCommand(void *cmdp, void *jobp)
984263bc 438{
df64c352 439 Boolean noSpecials; /* true if we shouldn't worry about
271e747f
MO
440 * inserting special commands into
441 * the input stream. */
df64c352 442 Boolean shutUp = FALSE; /* true if we put a no echo command
271e747f 443 * into the command file */
df64c352 444 Boolean errOff = FALSE; /* true if we turned error checking
271e747f
MO
445 * off before printing the command
446 * and need to turn it back on */
df64c352
MO
447 const char *cmdTemplate;/* Template to use when printing the command */
448 char *cmdStart; /* Start of expanded command */
449 LstNode *cmdNode; /* Node for replacing the command */
450 char *cmd = cmdp;
451 Job *job = jobp;
452
453 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
454
455 if (strcmp(cmd, "...") == 0) {
456 job->node->type |= OP_SAVE_CMDS;
457 if ((job->flags & JOB_IGNDOTS) == 0) {
458 job->tailCmds =
459 Lst_Succ(Lst_Member(&job->node->commands, cmd));
460 return (1);
461 }
462 return (0);
984263bc 463 }
984263bc 464
df64c352
MO
465#define DBPRINTF(fmt, arg) \
466 DEBUGF(JOB, (fmt, arg)); \
467 fprintf(job->cmdFILE, fmt, arg); \
468 fflush(job->cmdFILE);
984263bc 469
df64c352 470 numCommands += 1;
984263bc 471
df64c352
MO
472 /*
473 * For debugging, we replace each command with the result of expanding
474 * the variables in the command.
475 */
476 cmdNode = Lst_Member(&job->node->commands, cmd);
68061244 477
df64c352
MO
478 cmd = Buf_Peel(Var_Subst(NULL, cmd, job->node, FALSE));
479 cmdStart = cmd;
68061244 480
df64c352 481 Lst_Replace(cmdNode, cmdStart);
984263bc 482
df64c352 483 cmdTemplate = "%s\n";
984263bc 484
df64c352
MO
485 /*
486 * Check for leading @', -' or +'s to control echoing, error checking,
487 * and execution on -n.
488 */
489 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
490 switch (*cmd) {
40763d81 491
df64c352
MO
492 case '@':
493 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
494 break;
40763d81 495
df64c352
MO
496 case '-':
497 errOff = TRUE;
498 break;
40763d81 499
df64c352
MO
500 case '+':
501 if (noSpecials) {
502 /*
503 * We're not actually exececuting anything...
504 * but this one needs to be - use compat mode
505 * just for it.
506 */
507 Compat_RunCommand(cmdp, job->node);
508 return (0);
509 }
510 break;
511 }
512 cmd++;
984263bc 513 }
984263bc 514
df64c352
MO
515 while (isspace((unsigned char)*cmd))
516 cmd++;
984263bc 517
df64c352
MO
518 if (shutUp) {
519 if (!(job->flags & JOB_SILENT) && !noSpecials &&
984263bc
MD
520 commandShell->hasEchoCtl) {
521 DBPRINTF("%s\n", commandShell->echoOff);
984263bc 522 } else {
df64c352 523 shutUp = FALSE;
984263bc 524 }
df64c352
MO
525 }
526
527 if (errOff) {
528 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
529 if (commandShell->hasErrCtl) {
530 /*
531 * We don't want the error-control commands
532 * showing up either, so we turn off echoing
533 * while executing them. We could put another
534 * field in the shell structure to tell
535 * JobDoOutput to look for this string too,
536 * but why make it any more complex than
537 * it already is?
538 */
539 if (!(job->flags & JOB_SILENT) && !shutUp &&
540 commandShell->hasEchoCtl) {
541 DBPRINTF("%s\n", commandShell->echoOff);
542 DBPRINTF("%s\n", commandShell->ignErr);
543 DBPRINTF("%s\n", commandShell->echoOn);
544 } else {
545 DBPRINTF("%s\n", commandShell->ignErr);
546 }
547 } else if (commandShell->ignErr &&
548 (*commandShell->ignErr != '\0')) {
549 /*
550 * The shell has no error control, so we need to
551 * be weird to get it to ignore any errors from
552 * the command. If echoing is turned on, we turn
553 * it off and use the errCheck template to echo
554 * the command. Leave echoing off so the user
555 * doesn't see the weirdness we go through to
556 * ignore errors. Set cmdTemplate to use the
557 * weirdness instead of the simple "%s\n"
558 * template.
559 */
560 if (!(job->flags & JOB_SILENT) && !shutUp &&
561 commandShell->hasEchoCtl) {
562 DBPRINTF("%s\n", commandShell->echoOff);
563 DBPRINTF(commandShell->errCheck, cmd);
564 shutUp = TRUE;
565 }
566 cmdTemplate = commandShell->ignErr;
567 /*
568 * The error ignoration (hee hee) is already
569 * taken care of by the ignErr template, so
570 * pretend error checking is still on.
571 */
572 errOff = FALSE;
573 } else {
574 errOff = FALSE;
575 }
576 } else {
577 errOff = FALSE;
578 }
579 }
580
581 DBPRINTF(cmdTemplate, cmd);
582
583 if (errOff) {
984263bc 584 /*
df64c352
MO
585 * If echoing is already off, there's no point in issuing the
586 * echoOff command. Otherwise we issue it and pretend it was on
587 * for the whole command...
984263bc 588 */
df64c352 589 if (!shutUp && !(job->flags & JOB_SILENT) &&
984263bc
MD
590 commandShell->hasEchoCtl) {
591 DBPRINTF("%s\n", commandShell->echoOff);
984263bc
MD
592 shutUp = TRUE;
593 }
df64c352 594 DBPRINTF("%s\n", commandShell->errCheck);
984263bc 595 }
df64c352
MO
596 if (shutUp) {
597 DBPRINTF("%s\n", commandShell->echoOn);
598 }
599 return (0);
984263bc
MD
600}
601
df64c352 602/**
984263bc
MD
603 * JobClose --
604 * Called to close both input and output pipes when a job is finished.
605 *
984263bc
MD
606 * Side Effects:
607 * The file descriptors associated with the job are closed.
984263bc
MD
608 */
609static void
84de9e23 610JobClose(Job *job)
984263bc 611{
fbfaa208 612
df64c352 613 if (usePipes) {
a34ec481 614#if !defined(USE_KQUEUE)
df64c352 615 FD_CLR(job->inPipe, &outputs);
984263bc 616#endif
df64c352
MO
617 if (job->outPipe != job->inPipe) {
618 close(job->outPipe);
619 }
620 JobDoOutput(job, TRUE);
621 close(job->inPipe);
622 } else {
623 close(job->outFd);
624 JobDoOutput(job, TRUE);
625 }
984263bc
MD
626}
627
df64c352 628/**
984263bc
MD
629 * JobFinish --
630 * Do final processing for the given job including updating
631 * parents and starting new jobs as available/necessary. Note
632 * that we pay no attention to the JOB_IGNERR flag here.
633 * This is because when we're called because of a noexecute flag
634 * or something, jstat.w_status is 0 and when called from
635 * Job_CatchChildren, the status is zeroed if it s/b ignored.
636 *
984263bc
MD
637 * Side Effects:
638 * Some nodes may be put on the toBeMade queue.
639 * Final commands for the job are placed on postCommands.
640 *
641 * If we got an error and are aborting (aborting == ABORT_ERROR) and
642 * the job list is now empty, we are done for the day.
643 * If we recognized an error (errors !=0), we set the aborting flag
644 * to ABORT_ERROR so no more jobs will be started.
984263bc 645 */
984263bc 646static void
84de9e23 647JobFinish(Job *job, int *status)
984263bc 648{
df64c352
MO
649 Boolean done;
650 LstNode *ln;
984263bc 651
df64c352
MO
652 if ((WIFEXITED(*status) &&
653 (((WEXITSTATUS(*status) != 0) && !(job->flags & JOB_IGNERR)))) ||
654 (WIFSIGNALED(*status) && (WTERMSIG(*status) != SIGCONT))) {
655 /*
656 * If it exited non-zero and either we're doing things our
657 * way or we're not ignoring errors, the job is finished.
658 * Similarly, if the shell died because of a signal
659 * the job is also finished. In these cases, finish out the
660 * job's output before printing the exit status...
661 */
662 JobClose(job);
663 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
664 fclose(job->cmdFILE);
665 }
666 done = TRUE;
667
668 } else if (WIFEXITED(*status)) {
669 /*
670 * Deal with ignored errors in -B mode. We need to print a
671 * message telling of the ignored error as well as setting
672 * status.w_status to 0 so the next command gets run. To do
673 * this, we set done to be TRUE if in -B mode and the job
674 * exited non-zero.
675 */
676 done = WEXITSTATUS(*status) != 0;
677
678 /*
679 * Old comment said: "Note we don't want to close down any of
680 * the streams until we know we're at the end." But we do.
681 * Otherwise when are we going to print the rest of the stuff?
682 */
683 JobClose(job);
984263bc 684 } else {
df64c352
MO
685 /*
686 * No need to close things down or anything.
687 */
688 done = FALSE;
984263bc
MD
689 }
690
df64c352
MO
691 if (done || WIFSTOPPED(*status) ||
692 (WIFSIGNALED(*status) && (WTERMSIG(*status) == SIGCONT)) ||
693 DEBUG(JOB)) {
694 FILE *out;
695
696 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
697 /*
698 * If output is going to a file and this job is ignoring
699 * errors, arrange to have the exit status sent to the
700 * output file as well.
701 */
702 out = fdopen(job->outFd, "w");
703 if (out == NULL)
704 Punt("Cannot fdopen");
705 } else {
706 out = stdout;
984263bc 707 }
984263bc 708
df64c352
MO
709 if (WIFEXITED(*status)) {
710 DEBUGF(JOB, ("Process %d exited.\n", job->pid));
711 if (WEXITSTATUS(*status) != 0) {
712 if (usePipes && job->node != lastNode) {
713 MESSAGE(out, job->node);
714 lastNode = job->node;
715 }
716 fprintf(out, "*** Error code %d%s\n",
717 WEXITSTATUS(*status),
718 (job->flags & JOB_IGNERR) ?
719 "(ignored)" : "");
720
721 if (job->flags & JOB_IGNERR) {
722 *status = 0;
723 }
724 } else if (DEBUG(JOB)) {
725 if (usePipes && job->node != lastNode) {
726 MESSAGE(out, job->node);
727 lastNode = job->node;
728 }
729 fprintf(out, "*** Completed successfully\n");
730 }
731
732 } else if (WIFSTOPPED(*status)) {
733 DEBUGF(JOB, ("Process %d stopped.\n", job->pid));
734 if (usePipes && job->node != lastNode) {
735 MESSAGE(out, job->node);
736 lastNode = job->node;
737 }
738 fprintf(out, "*** Stopped -- signal %d\n",
739 WSTOPSIG(*status));
740 job->flags |= JOB_RESUME;
741 Lst_AtEnd(&stoppedJobs, job);
742 fflush(out);
743 return;
744
745 } else if (WTERMSIG(*status) == SIGCONT) {
746 /*
747 * If the beastie has continued, shift the Job from
748 * the stopped list to the running one (or re-stop it
749 * if concurrency is exceeded) and go and get another
750 * child.
751 */
752 if (job->flags & (JOB_RESUME|JOB_RESTART)) {
753 if (usePipes && job->node != lastNode) {
754 MESSAGE(out, job->node);
755 lastNode = job->node;
756 }
757 fprintf(out, "*** Continued\n");
758 }
759 if (!(job->flags & JOB_CONTINUING)) {
760 DEBUGF(JOB, ("Warning: process %d was not "
761 "continuing.\n", job->pid));
984263bc 762#ifdef notdef
df64c352
MO
763 /*
764 * We don't really want to restart a job from
765 * scratch just because it continued, especially
766 * not without killing the continuing process!
767 * That's why this is ifdef'ed out.
768 * FD - 9/17/90
769 */
770 JobRestart(job);
984263bc 771#endif
df64c352
MO
772 }
773 job->flags &= ~JOB_CONTINUING;
774 Lst_AtEnd(&jobs, job);
775 nJobs += 1;
776 DEBUGF(JOB, ("Process %d is continuing locally.\n",
777 job->pid));
778 if (nJobs == maxJobs) {
779 jobFull = TRUE;
780 DEBUGF(JOB, ("Job queue is full.\n"));
781 }
782 fflush(out);
783 return;
784
785 } else {
786 if (usePipes && job->node != lastNode) {
787 MESSAGE(out, job->node);
788 lastNode = job->node;
789 }
790 fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
791 }
792
793 fflush(out);
794 }
795
984263bc 796 /*
df64c352
MO
797 * Now handle the -B-mode stuff. If the beast still isn't finished,
798 * try and restart the job on the next command. If JobStart says it's
799 * ok, it's ok. If there's an error, this puppy is done.
984263bc 800 */
df64c352
MO
801 if (compatMake && WIFEXITED(*status) &&
802 Lst_Succ(job->node->compat_command) != NULL) {
803 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
804 case JOB_RUNNING:
805 done = FALSE;
806 break;
807 case JOB_ERROR:
808 done = TRUE;
809 W_SETEXITSTATUS(status, 1);
810 break;
811 case JOB_FINISHED:
812 /*
813 * If we got back a JOB_FINISHED code, JobStart has
814 * already called Make_Update and freed the job
815 * descriptor. We set done to false here to avoid fake
816 * cycles and double frees. JobStart needs to do the
817 * update so we can proceed up the graph when given
818 * the -n flag..
819 */
820 done = FALSE;
821 break;
822 default:
823 break;
824 }
825 } else {
826 done = TRUE;
984263bc 827 }
14ba7c54 828
df64c352
MO
829 if (done && (aborting != ABORT_ERROR) &&
830 (aborting != ABORT_INTERRUPT) && (*status == 0)) {
831 /*
832 * As long as we aren't aborting and the job didn't return a
833 * non-zero status that we shouldn't ignore, we call
834 * Make_Update to update the parents. In addition, any saved
835 * commands for the node are placed on the .END target.
836 */
837 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
838 Lst_AtEnd(&postCommands->commands,
839 Buf_Peel(Var_Subst(NULL, Lst_Datum(ln),
840 job->node, FALSE)));
841 }
984263bc 842
df64c352
MO
843 job->node->made = MADE;
844 Make_Update(job->node);
845 free(job);
984263bc 846
df64c352
MO
847 } else if (*status != 0) {
848 errors += 1;
849 free(job);
850 }
851
852 JobRestartJobs();
984263bc 853
984263bc 854 /*
df64c352 855 * Set aborting if any error.
984263bc 856 */
df64c352
MO
857 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
858 /*
859 * If we found any errors in this batch of children and the -k
860 * flag wasn't given, we set the aborting flag so no more jobs
861 * get started.
862 */
863 aborting = ABORT_ERROR;
864 }
865
866 if ((aborting == ABORT_ERROR) && Job_Empty()) {
867 /*
868 * If we are aborting and the job table is now empty, we finish.
869 */
870 Finish(errors);
871 }
984263bc
MD
872}
873
df64c352
MO
874/**
875 * Job_Touch
984263bc 876 * Touch the given target. Called by JobStart when the -t flag was
84de9e23 877 * given. Prints messages unless told to be silent.
984263bc 878 *
984263bc
MD
879 * Side Effects:
880 * The data modification of the file is changed. In addition, if the
881 * file did not exist, it is created.
984263bc
MD
882 */
883void
84de9e23 884Job_Touch(GNode *gn, Boolean silent)
984263bc 885{
df64c352
MO
886 int streamID; /* ID of stream opened to do the touch */
887 struct utimbuf times; /* Times for utime() call */
984263bc 888
df64c352
MO
889 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
890 /*
891 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
892 * targets and, as such, shouldn't really be created.
893 */
894 return;
895 }
984263bc 896
df64c352
MO
897 if (!silent) {
898 fprintf(stdout, "touch %s\n", gn->name);
899 fflush(stdout);
900 }
984263bc 901
df64c352
MO
902 if (noExecute) {
903 return;
904 }
984263bc 905
df64c352
MO
906 if (gn->type & OP_ARCHV) {
907 Arch_Touch(gn);
908 } else if (gn->type & OP_LIB) {
909 Arch_TouchLib(gn);
910 } else {
911 char *file = gn->path ? gn->path : gn->name;
912
913 times.actime = times.modtime = now;
914 if (utime(file, &times) < 0) {
915 streamID = open(file, O_RDWR | O_CREAT, 0666);
916
917 if (streamID >= 0) {
918 char c;
919
920 /*
921 * Read and write a byte to the file to change
922 * the modification time, then close the file.
923 */
924 if (read(streamID, &c, 1) == 1) {
925 lseek(streamID, (off_t)0, SEEK_SET);
926 write(streamID, &c, 1);
927 }
928
929 close(streamID);
930 } else {
931 fprintf(stdout, "*** couldn't touch %s: %s",
932 file, strerror(errno));
933 fflush(stdout);
934 }
984263bc 935 }
984263bc 936 }
984263bc
MD
937}
938
df64c352
MO
939/**
940 * Job_CheckCommands
984263bc
MD
941 * Make sure the given node has all the commands it needs.
942 *
943 * Results:
944 * TRUE if the commands list is/was ok.
945 *
946 * Side Effects:
947 * The node will have commands from the .DEFAULT rule added to it
948 * if it needs them.
984263bc
MD
949 */
950Boolean
84de9e23 951Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
984263bc 952{
fbfaa208 953
df64c352
MO
954 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
955 (gn->type & OP_LIB) == 0) {
956 /*
957 * No commands. Look for .DEFAULT rule from which we might infer
958 * commands.
959 */
960 if ((DEFAULT != NULL) && !Lst_IsEmpty(&DEFAULT->commands)) {
961 char *p1;
962 /*
963 * Make only looks for a .DEFAULT if the node was
964 * never the target of an operator, so that's what we
965 * do too. If a .DEFAULT was given, we substitute its
966 * commands for gn's commands and set the IMPSRC
967 * variable to be the target's name The DEFAULT node
968 * acts like a transformation rule, in that gn also
969 * inherits any attributes or sources attached to
970 * .DEFAULT itself.
971 */
972 Make_HandleUse(DEFAULT, gn);
973 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
974 free(p1);
975
976 } else if (Dir_MTime(gn) == 0) {
977 /*
978 * The node wasn't the target of an operator we have
979 * no .DEFAULT rule to go on and the target doesn't
980 * already exist. There's nothing more we can do for
981 * this branch. If the -k flag wasn't given, we stop
982 * in our tracks, otherwise we just don't update
983 * this node's parents so they never get examined.
984 */
985 static const char msg[] =
986 "make: don't know how to make";
987
988 if (gn->type & OP_OPTIONAL) {
989 fprintf(stdout, "%s %s(ignored)\n",
990 msg, gn->name);
991 fflush(stdout);
992 } else if (keepgoing) {
993 fprintf(stdout, "%s %s(continuing)\n",
994 msg, gn->name);
995 fflush(stdout);
996 return (FALSE);
997 } else {
984263bc 998#if OLD_JOKE
df64c352
MO
999 if (strcmp(gn->name,"love") == 0)
1000 (*abortProc)("Not war.");
1001 else
984263bc 1002#endif
df64c352
MO
1003 (*abortProc)("%s %s. Stop",
1004 msg, gn->name);
1005 return (FALSE);
1006 }
1007 }
984263bc 1008 }
df64c352 1009 return (TRUE);
984263bc 1010}
984263bc 1011
df64c352
MO
1012/**
1013 * JobExec
984263bc
MD
1014 * Execute the shell for the given job. Called from JobStart and
1015 * JobRestart.
1016 *
984263bc
MD
1017 * Side Effects:
1018 * A shell is executed, outputs is altered and the Job structure added
1019 * to the job table.
984263bc
MD
1020 */
1021static void
84de9e23 1022JobExec(Job *job, char **argv)
984263bc 1023{
df64c352 1024 int cpid; /* ID of new child */
984263bc 1025
df64c352
MO
1026 if (DEBUG(JOB)) {
1027 int i;
1028
1029 DEBUGF(JOB, ("Running %s\n", job->node->name));
1030 DEBUGF(JOB, ("\tCommand: "));
1031 for (i = 0; argv[i] != NULL; i++) {
1032 DEBUGF(JOB, ("%s ", argv[i]));
1033 }
1034 DEBUGF(JOB, ("\n"));
984263bc 1035 }
df64c352 1036
984263bc 1037 /*
df64c352
MO
1038 * Some jobs produce no output and it's disconcerting to have
1039 * no feedback of their running (since they produce no output, the
1040 * banner with their name in it never appears). This is an attempt to
1041 * provide that feedback, even if nothing follows it.
984263bc 1042 */
df64c352
MO
1043 if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1044 !(job->flags & JOB_SILENT)) {
1045 MESSAGE(stdout, job->node);
1046 lastNode = job->node;
1047 }
1048
1049 if ((cpid = vfork()) == -1) {
1050 Punt("Cannot fork");
1051
1052 } else if (cpid == 0) {
1053 if (fifoFd >= 0)
1054 close(fifoFd);
1055
1056 /*
1057 * Must duplicate the input stream down to the child's input and
1058 * reset it to the beginning (again). Since the stream was
1059 * marked close-on-exec, we must clear that bit in the new
1060 * input.
1061 */
1062 if (dup2(FILENO(job->cmdFILE), 0) == -1)
1063 Punt("Cannot dup2: %s", strerror(errno));
1064 fcntl(0, F_SETFD, 0);
1065 lseek(0, (off_t)0, SEEK_SET);
1066
1067 if (usePipes) {
1068 /*
1069 * Set up the child's output to be routed through the
1070 * pipe we've created for it.
1071 */
1072 if (dup2(job->outPipe, 1) == -1)
1073 Punt("Cannot dup2: %s", strerror(errno));
1074 } else {
1075 /*
1076 * We're capturing output in a file, so we duplicate the
1077 * descriptor to the temporary file into the standard
1078 * output.
1079 */
1080 if (dup2(job->outFd, 1) == -1)
1081 Punt("Cannot dup2: %s", strerror(errno));
1082 }
1083 /*
1084 * The output channels are marked close on exec. This bit was
1085 * duplicated by the dup2 (on some systems), so we have to clear
1086 * it before routing the shell's error output to the same place
1087 * as its standard output.
1088 */
1089 fcntl(1, F_SETFD, 0);
1090 if (dup2(1, 2) == -1)
1091 Punt("Cannot dup2: %s", strerror(errno));
984263bc
MD
1092
1093#ifdef USE_PGRP
df64c352
MO
1094 /*
1095 * We want to switch the child into a different process family
1096 * so we can kill it and all its descendants in one fell swoop,
1097 * by killing its process family, but not commit suicide.
1098 */
984263bc 1099# if defined(SYSV)
df64c352 1100 setsid();
984263bc 1101# else
df64c352 1102 setpgid(0, getpid());
984263bc
MD
1103# endif
1104#endif /* USE_PGRP */
1105
df64c352 1106 execv(shellPath, argv);
984263bc 1107
df64c352
MO
1108 write(STDERR_FILENO, "Could not execute shell\n",
1109 sizeof("Could not execute shell"));
1110 _exit(1);
984263bc 1111
df64c352
MO
1112 } else {
1113 job->pid = cpid;
1114
1115 if (usePipes && (job->flags & JOB_FIRST)) {
1116 /*
1117 * The first time a job is run for a node, we set the
1118 * current position in the buffer to the beginning and
1119 * mark another stream to watch in the outputs mask.
1120 */
218b5aa1 1121#ifdef USE_KQUEUE
df64c352 1122 struct kevent kev[2];
218b5aa1 1123#endif
df64c352 1124 job->curPos = 0;
984263bc 1125
a34ec481 1126#if defined(USE_KQUEUE)
df64c352
MO
1127 EV_SET(&kev[0], job->inPipe, EVFILT_READ,
1128 EV_ADD, 0, 0, job);
1129 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1130 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1131 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1132 /*
1133 * kevent() will fail if the job is already
1134 * finished
1135 */
1136 if (errno != EINTR && errno != EBADF &&
1137 errno != ESRCH)
1138 Punt("kevent: %s", strerror(errno));
1139 }
984263bc 1140#else
df64c352 1141 FD_SET(job->inPipe, &outputs);
a34ec481 1142#endif /* USE_KQUEUE */
df64c352 1143 }
984263bc 1144
df64c352
MO
1145 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1146 fclose(job->cmdFILE);
1147 job->cmdFILE = NULL;
1148 }
984263bc 1149 }
984263bc 1150
df64c352
MO
1151 /*
1152 * Now the job is actually running, add it to the table.
1153 */
1154 nJobs += 1;
1155 Lst_AtEnd(&jobs, job);
1156 if (nJobs == maxJobs) {
1157 jobFull = TRUE;
1158 }
984263bc
MD
1159}
1160
df64c352
MO
1161/**
1162 * JobMakeArgv
984263bc 1163 * Create the argv needed to execute the shell for a given job.
984263bc
MD
1164 */
1165static void
84de9e23 1166JobMakeArgv(Job *job, char **argv)
984263bc 1167{
df64c352
MO
1168 int argc;
1169 static char args[10]; /* For merged arguments */
984263bc 1170
df64c352
MO
1171 argv[0] = shellName;
1172 argc = 1;
984263bc 1173
df64c352
MO
1174 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1175 (commandShell->echo && (*commandShell->echo != '-'))) {
1176 /*
1177 * At least one of the flags doesn't have a minus before it, so
1178 * merge them together. Have to do this because the *(&(@*#*&#$#
1179 * Bourne shell thinks its second argument is a file to source.
1180 * Grrrr. Note the ten-character limitation on the combined
1181 * arguments.
1182 */
1183 sprintf(args, "-%s%s", ((job->flags & JOB_IGNERR) ? "" :
1184 (commandShell->exit ? commandShell->exit : "")),
1185 ((job->flags & JOB_SILENT) ? "" :
1186 (commandShell->echo ? commandShell->echo : "")));
1187
1188 if (args[1]) {
1189 argv[argc] = args;
1190 argc++;
1191 }
1192 } else {
1193 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1194 argv[argc] = commandShell->exit;
1195 argc++;
1196 }
1197 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1198 argv[argc] = commandShell->echo;
1199 argc++;
1200 }
1201 }
1202 argv[argc] = NULL;
984263bc
MD
1203}
1204
df64c352
MO
1205/**
1206 * JobRestart
984263bc
MD
1207 * Restart a job that stopped for some reason.
1208 *
984263bc
MD
1209 * Side Effects:
1210 * jobFull will be set if the job couldn't be run.
984263bc
MD
1211 */
1212static void
84de9e23 1213JobRestart(Job *job)
984263bc 1214{
984263bc 1215
df64c352 1216 if (job->flags & JOB_RESTART) {
984263bc 1217 /*
df64c352
MO
1218 * Set up the control arguments to the shell. This is based on
1219 * the flags set earlier for this job. If the JOB_IGNERR flag
1220 * is clear, the 'exit' flag of the commandShell is used to
1221 * cause it to exit upon receiving an error. If the JOB_SILENT
1222 * flag is clear, the 'echo' flag of the commandShell is used
1223 * to get it to start echoing as soon as it starts
1224 * processing commands.
984263bc 1225 */
df64c352
MO
1226 char *argv[4];
1227
1228 JobMakeArgv(job, argv);
1229
1230 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1231 if (((nJobs >= maxJobs) && !(job->flags & JOB_SPECIAL))) {
1232 /*
1233 * Can't be exported and not allowed to run locally --
1234 * put it back on the hold queue and mark the table full
1235 */
1236 DEBUGF(JOB, ("holding\n"));
1237 Lst_AtFront(&stoppedJobs, (void *)job);
1238 jobFull = TRUE;
1239 DEBUGF(JOB, ("Job queue is full.\n"));
1240 return;
1241 } else {
1242 /*
1243 * Job may be run locally.
1244 */
1245 DEBUGF(JOB, ("running locally\n"));
1246 }
1247 JobExec(job, argv);
984263bc 1248
984263bc 1249 } else {
df64c352
MO
1250 /*
1251 * The job has stopped and needs to be restarted.
1252 * Why it stopped, we don't know...
1253 */
1254 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1255 if (((nJobs < maxJobs) || ((job->flags & JOB_SPECIAL) &&
1256 (maxJobs == 0))) && (nJobs != maxJobs)) {
1257 /*
1258 * If we haven't reached the concurrency limit already
1259 * (or the job must be run and maxJobs is 0), it's ok
1260 * to resume it.
1261 */
1262 Boolean error;
1263 int status;
1264
1265 error = (KILL(job->pid, SIGCONT) != 0);
1266
1267 if (!error) {
1268 /*
1269 * Make sure the user knows we've continued
1270 * the beast and actually put the thing in the
1271 * job table.
1272 */
1273 job->flags |= JOB_CONTINUING;
1274 status = 0;
1275 W_SETTERMSIG(&status, SIGCONT);
1276 JobFinish(job, &status);
1277
1278 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1279 DEBUGF(JOB, ("done\n"));
1280 } else {
1281 Error("couldn't resume %s: %s",
1282 job->node->name, strerror(errno));
1283 status = 0;
1284 W_SETEXITSTATUS(&status, 1);
1285 JobFinish(job, &status);
1286 }
1287 } else {
1288 /*
1289 * Job cannot be restarted. Mark the table as full and
1290 * place the job back on the list of stopped jobs.
1291 */
1292 DEBUGF(JOB, ("table full\n"));
1293 Lst_AtFront(&stoppedJobs, (void *)job);
1294 jobFull = TRUE;
1295 DEBUGF(JOB, ("Job queue is full.\n"));
1296 }
1297 }
984263bc
MD
1298}
1299
df64c352
MO
1300/**
1301 * JobStart
984263bc
MD
1302 * Start a target-creation process going for the target described
1303 * by the graph node gn.
1304 *
1305 * Results:
1306 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1307 * if there isn't actually anything left to do for the job and
1308 * JOB_RUNNING if the job has been started.
1309 *
1310 * Side Effects:
1311 * A new Job node is created and added to the list of running
1312 * jobs. PMake is forked and a child shell created.
984263bc
MD
1313 */
1314static int
84de9e23 1315JobStart(GNode *gn, int flags, Job *previous)
984263bc 1316{
df64c352
MO
1317 Job *job; /* new job descriptor */
1318 char *argv[4]; /* Argument vector to shell */
1319 Boolean cmdsOK; /* true if the nodes commands were all right */
1320 Boolean noExec; /* Set true if we decide not to run the job */
1321 int tfd; /* File descriptor for temp file */
1322 LstNode *ln;
1323
1324 if (interrupted) {
1325 JobPassSig(interrupted);
1326 return (JOB_ERROR);
1327 }
1328 if (previous != NULL) {
1329 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1330 job = previous;
1331 } else {
1332 job = emalloc(sizeof(Job));
1333 flags |= JOB_FIRST;
1334 }
1335
1336 job->node = gn;
1337 job->tailCmds = NULL;
1338
984263bc 1339 /*
df64c352
MO
1340 * Set the initial value of the flags for this job based on the global
1341 * ones and the node's attributes... Any flags supplied by the caller
1342 * are also added to the field.
984263bc 1343 */
df64c352
MO
1344 job->flags = 0;
1345 if (Targ_Ignore(gn)) {
1346 job->flags |= JOB_IGNERR;
984263bc 1347 }
df64c352
MO
1348 if (Targ_Silent(gn)) {
1349 job->flags |= JOB_SILENT;
984263bc 1350 }
df64c352
MO
1351 job->flags |= flags;
1352
984263bc 1353 /*
df64c352
MO
1354 * Check the commands now so any attributes from .DEFAULT have a chance
1355 * to migrate to the node.
984263bc 1356 */
df64c352
MO
1357 if (!compatMake && job->flags & JOB_FIRST) {
1358 cmdsOK = Job_CheckCommands(gn, Error);
1359 } else {
1360 cmdsOK = TRUE;
1361 }
984263bc
MD
1362
1363 /*
df64c352
MO
1364 * If the -n flag wasn't given, we open up OUR (not the child's)
1365 * temporary file to stuff commands in it. The thing is rd/wr so we
1366 * don't need to reopen it to feed it to the shell. If the -n flag
1367 * *was* given, we just set the file to be stdout. Cute, huh?
984263bc 1368 */
df64c352
MO
1369 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1370 /*
1371 * We're serious here, but if the commands were bogus, we're
1372 * also dead...
1373 */
1374 if (!cmdsOK) {
1375 DieHorribly();
1376 }
513bf0db 1377
df64c352
MO
1378 strcpy(tfile, TMPPAT);
1379 if ((tfd = mkstemp(tfile)) == -1)
1380 Punt("Cannot create temp file: %s", strerror(errno));
1381 job->cmdFILE = fdopen(tfd, "w+");
1382 eunlink(tfile);
1383 if (job->cmdFILE == NULL) {
1384 close(tfd);
1385 Punt("Could not open %s", tfile);
1386 }
1387 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
513bf0db 1388 /*
df64c352
MO
1389 * Send the commands to the command file, flush all its
1390 * buffers then rewind and remove the thing.
513bf0db 1391 */
df64c352
MO
1392 noExec = FALSE;
1393
1394 /*
1395 * Used to be backwards; replace when start doing multiple
1396 * commands per shell.
1397 */
1398 if (compatMake) {
1399 /*
1400 * Be compatible: If this is the first time for this
1401 * node, verify its commands are ok and open the
1402 * commands list for sequential access by later
1403 * invocations of JobStart. Once that is done, we take
1404 * the next command off the list and print it to the
1405 * command file. If the command was an ellipsis, note
1406 * that there's nothing more to execute.
1407 */
1408 if (job->flags & JOB_FIRST)
1409 gn->compat_command = Lst_First(&gn->commands);
1410 else
1411 gn->compat_command =
1412 Lst_Succ(gn->compat_command);
1413
1414 if (gn->compat_command == NULL ||
1415 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1416 noExec = TRUE;
1417
1418 if (noExec && !(job->flags & JOB_FIRST)) {
1419 /*
1420 * If we're not going to execute anything, the
1421 * job is done and we need to close down the
1422 * various file descriptors we've opened for
1423 * output, then call JobDoOutput to catch the
1424 * final characters or send the file to the
1425 * screen... Note that the i/o streams are only
1426 * open if this isn't the first job. Note also
1427 * that this could not be done in
1428 * Job_CatchChildren b/c it wasn't clear if
1429 * there were more commands to execute or not...
1430 */
1431 JobClose(job);
1432 }
1433 } else {
1434 /*
1435 * We can do all the commands at once. hooray for sanity
1436 */
1437 numCommands = 0;
1438 LST_FOREACH(ln, &gn->commands) {
1439 if (JobPrintCommand(Lst_Datum(ln), job))
1440 break;
1441 }
1442
1443 /*
1444 * If we didn't print out any commands to the shell
1445 * script, there's not much point in executing the
1446 * shell, is there?
1447 */
1448 if (numCommands == 0) {
1449 noExec = TRUE;
1450 }
1451 }
1452
1453 } else if (noExecute) {
1454 /*
1455 * Not executing anything -- just print all the commands to
1456 * stdout in one fell swoop. This will still set up
1457 * job->tailCmds correctly.
1458 */
1459 if (lastNode != gn) {
1460 MESSAGE(stdout, gn);
1461 lastNode = gn;
1462 }
1463 job->cmdFILE = stdout;
1464
1465 /*
1466 * Only print the commands if they're ok, but don't die if
1467 * they're not -- just let the user know they're bad and keep
1468 * going. It doesn't do any harm in this case and may do
1469 * some good.
1470 */
1471 if (cmdsOK) {
1472 LST_FOREACH(ln, &gn->commands) {
1473 if (JobPrintCommand(Lst_Datum(ln), job))
1474 break;
1475 }
1476 }
1477 /*
1478 * Don't execute the shell, thank you.
1479 */
984263bc 1480 noExec = TRUE;
df64c352 1481
984263bc 1482 } else {
df64c352
MO
1483 /*
1484 * Just touch the target and note that no shell should be
1485 * executed. Set cmdFILE to stdout to make life easier. Check
1486 * the commands, too, but don't die if they're no good -- it
1487 * does no harm to keep working up the graph.
1488 */
1489 job->cmdFILE = stdout;
1490 Job_Touch(gn, job->flags & JOB_SILENT);
1491 noExec = TRUE;
984263bc
MD
1492 }
1493
1494 /*
df64c352 1495 * If we're not supposed to execute a shell, don't.
984263bc 1496 */
df64c352
MO
1497 if (noExec) {
1498 /*
1499 * Unlink and close the command file if we opened one
1500 */
1501 if (job->cmdFILE != stdout) {
1502 if (job->cmdFILE != NULL)
1503 fclose(job->cmdFILE);
1504 } else {
1505 fflush(stdout);
1506 }
1507
1508 /*
1509 * We only want to work our way up the graph if we aren't here
1510 * because the commands for the job were no good.
1511 */
1512 if (cmdsOK) {
1513 if (aborting == 0) {
1514 for (ln = job->tailCmds; ln != NULL;
1515 ln = LST_NEXT(ln)) {
1516 Lst_AtEnd(&postCommands->commands,
1517 Buf_Peel(Var_Subst(NULL,
1518 Lst_Datum(ln), job->node, FALSE)));
1519 }
1520 job->node->made = MADE;
1521 Make_Update(job->node);
1522 }
1523 free(job);
1524 return(JOB_FINISHED);
1525 } else {
1526 free(job);
1527 return(JOB_ERROR);
984263bc 1528 }
984263bc 1529 } else {
df64c352 1530 fflush(job->cmdFILE);
984263bc 1531 }
984263bc 1532
984263bc 1533 /*
df64c352
MO
1534 * Set up the control arguments to the shell. This is based on the flags
1535 * set earlier for this job.
984263bc 1536 */
df64c352 1537 JobMakeArgv(job, argv);
984263bc 1538
df64c352
MO
1539 /*
1540 * If we're using pipes to catch output, create the pipe by which we'll
1541 * get the shell's output. If we're using files, print out that we're
1542 * starting a job and then set up its temporary-file name.
1543 */
1544 if (!compatMake || (job->flags & JOB_FIRST)) {
1545 if (usePipes) {
1546 int fd[2];
1547
1548 if (pipe(fd) == -1)
1549 Punt("Cannot create pipe: %s", strerror(errno));
1550 job->inPipe = fd[0];
1551 job->outPipe = fd[1];
1552 fcntl(job->inPipe, F_SETFD, 1);
1553 fcntl(job->outPipe, F_SETFD, 1);
1554 } else {
1555 fprintf(stdout, "Remaking `%s'\n", gn->name);
1556 fflush(stdout);
1557 strcpy(job->outFile, TMPPAT);
1558 if ((job->outFd = mkstemp(job->outFile)) == -1)
1559 Punt("cannot create temp file: %s",
1560 strerror(errno));
1561 fcntl(job->outFd, F_SETFD, 1);
984263bc 1562 }
df64c352
MO
1563 }
1564
1565 if ((nJobs >= maxJobs) && !(job->flags & JOB_SPECIAL) && (maxJobs != 0)) {
984263bc 1566 /*
df64c352
MO
1567 * We've hit the limit of concurrency, so put the job on hold
1568 * until some other job finishes. Note that the special jobs
1569 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1570 * limit has been reached (e.g. when maxJobs == 0).
984263bc 1571 */
df64c352
MO
1572 jobFull = TRUE;
1573
1574 DEBUGF(JOB, ("Can only run job locally.\n"));
1575 job->flags |= JOB_RESTART;
1576 Lst_AtEnd(&stoppedJobs, job);
1577 } else {
1578 if (nJobs >= maxJobs) {
1579 /*
1580 * If we're running this job locally as a special case
1581 * (see above), at least say the table is full.
1582 */
1583 jobFull = TRUE;
1584 DEBUGF(JOB, ("Local job queue is full.\n"));
984263bc 1585 }
df64c352
MO
1586 JobExec(job, argv);
1587 }
1588 return (JOB_RUNNING);
1589}
1590
1591static char *
1592JobOutput(Job *job, char *cp, char *endp, int msg)
1593{
1594 char *ecp;
1595
1596 if (commandShell->noPrint) {
4faecc47 1597 ecp = strstr(cp, commandShell->noPrint);
df64c352
MO
1598 while (ecp != NULL) {
1599 if (cp != ecp) {
1600 *ecp = '\0';
1601 if (msg && job->node != lastNode) {
1602 MESSAGE(stdout, job->node);
1603 lastNode = job->node;
1604 }
1605 /*
1606 * The only way there wouldn't be a newline
1607 * after this line is if it were the last in
1608 * the buffer. However, since the non-printable
1609 * comes after it, there must be a newline, so
1610 * we don't print one.
1611 */
1612 fprintf(stdout, "%s", cp);
1613 fflush(stdout);
1614 }
1615 cp = ecp + commandShell->noPLen;
1616 if (cp != endp) {
1617 /*
1618 * Still more to print, look again after
1619 * skipping the whitespace following the
1620 * non-printable command....
1621 */
1622 cp++;
1623 while (*cp == ' ' || *cp == '\t' ||
1624 *cp == '\n') {
1625 cp++;
1626 }
1627 ecp = strstr(cp, commandShell->noPrint);
1628 } else {
1629 return (cp);
1630 }
1631 }
984263bc 1632 }
df64c352 1633 return (cp);
984263bc
MD
1634}
1635
df64c352
MO
1636/**
1637 * JobDoOutput
984263bc
MD
1638 * This function is called at different times depending on
1639 * whether the user has specified that output is to be collected
1640 * via pipes or temporary files. In the former case, we are called
1641 * whenever there is something to read on the pipe. We collect more
1642 * output from the given job and store it in the job's outBuf. If
1643 * this makes up a line, we print it tagged by the job's identifier,
1644 * as necessary.
1645 * If output has been collected in a temporary file, we open the
1646 * file and read it line by line, transfering it to our own
1647 * output channel until the file is empty. At which point we
1648 * remove the temporary file.
1649 * In both cases, however, we keep our figurative eye out for the
1650 * 'noPrint' line for the shell from which the output came. If
1651 * we recognize a line, we don't print it. If the command is not
1652 * alone on the line (the character after it is not \0 or \n), we
1653 * do print whatever follows it.
1654 *
984263bc
MD
1655 * Side Effects:
1656 * curPos may be shifted as may the contents of outBuf.
984263bc
MD
1657 */
1658STATIC void
84de9e23 1659JobDoOutput(Job *job, Boolean finish)
984263bc 1660{
df64c352
MO
1661 Boolean gotNL = FALSE; /* true if got a newline */
1662 Boolean fbuf; /* true if our buffer filled up */
1663 int nr; /* number of bytes read */
1664 int i; /* auxiliary index into outBuf */
1665 int max; /* limit for i (end of current data) */
1666 int nRead; /* (Temporary) number of bytes read */
1667 FILE *oFILE; /* Stream pointer to shell's output file */
1668 char inLine[132];
984263bc 1669
df64c352 1670 if (usePipes) {
984263bc 1671 /*
df64c352 1672 * Read as many bytes as will fit in the buffer.
984263bc 1673 */
df64c352
MO
1674 end_loop:
1675 gotNL = FALSE;
1676 fbuf = FALSE;
984263bc 1677
df64c352
MO
1678 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1679 JOB_BUFSIZE - job->curPos);
984263bc 1680 /*
df64c352
MO
1681 * Check for interrupt here too, because the above read may
1682 * block when the child process is stopped. In this case the
1683 * interrupt will unblock it (we don't use SA_RESTART).
984263bc 1684 */
df64c352
MO
1685 if (interrupted)
1686 JobPassSig(interrupted);
1687
1688 if (nRead < 0) {
1689 DEBUGF(JOB, ("JobDoOutput(piperead)"));
1690 nr = 0;
1691 } else {
1692 nr = nRead;
1693 }
984263bc
MD
1694
1695 /*
df64c352
MO
1696 * If we hit the end-of-file (the job is dead), we must flush
1697 * its remaining output, so pretend we read a newline if
1698 * there's any output remaining in the buffer.
1699 * Also clear the 'finish' flag so we stop looping.
984263bc 1700 */
df64c352
MO
1701 if ((nr == 0) && (job->curPos != 0)) {
1702 job->outBuf[job->curPos] = '\n';
1703 nr = 1;
1704 finish = FALSE;
1705 } else if (nr == 0) {
1706 finish = FALSE;
984263bc 1707 }
984263bc 1708
984263bc 1709 /*
df64c352
MO
1710 * Look for the last newline in the bytes we just got. If there
1711 * is one, break out of the loop with 'i' as its index and
1712 * gotNL set TRUE.
1713 */
1714 max = job->curPos + nr;
1715 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1716 if (job->outBuf[i] == '\n') {
1717 gotNL = TRUE;
1718 break;
1719 } else if (job->outBuf[i] == '\0') {
1720 /*
1721 * Why?
1722 */
1723 job->outBuf[i] = ' ';
1724 }
1725 }
1726
1727 if (!gotNL) {
1728 job->curPos += nr;
1729 if (job->curPos == JOB_BUFSIZE) {
1730 /*
1731 * If we've run out of buffer space, we have
1732 * no choice but to print the stuff. sigh.
1733 */
1734 fbuf = TRUE;
1735 i = job->curPos;
1736 }
1737 }
1738 if (gotNL || fbuf) {
1739 /*
1740 * Need to send the output to the screen. Null terminate
1741 * it first, overwriting the newline character if there
1742 * was one. So long as the line isn't one we should
1743 * filter (according to the shell description), we print
1744 * the line, preceded by a target banner if this target
1745 * isn't the same as the one for which we last printed
1746 * something. The rest of the data in the buffer are
1747 * then shifted down to the start of the buffer and
1748 * curPos is set accordingly.
1749 */
1750 job->outBuf[i] = '\0';
1751 if (i >= job->curPos) {
1752 char *cp;
1753
1754 cp = JobOutput(job, job->outBuf,
1755 &job->outBuf[i], FALSE);
1756
1757 /*
1758 * There's still more in that buffer. This time,
1759 * though, we know there's no newline at the
1760 * end, so we add one of our own free will.
1761 */
1762 if (*cp != '\0') {
1763 if (job->node != lastNode) {
1764 MESSAGE(stdout, job->node);
1765 lastNode = job->node;
1766 }
1767 fprintf(stdout, "%s%s", cp,
1768 gotNL ? "\n" : "");
1769 fflush(stdout);
1770 }
1771 }
1772 if (i < max - 1) {
1773 /* shift the remaining characters down */
1774 memcpy(job->outBuf, &job->outBuf[i + 1],
1775 max - (i + 1));
1776 job->curPos = max - (i + 1);
1777
1778 } else {
1779 /*
1780 * We have written everything out, so we just
1781 * start over from the start of the buffer.
1782 * No copying. No nothing.
1783 */
1784 job->curPos = 0;
1785 }
1786 }
1787 if (finish) {
1788 /*
1789 * If the finish flag is true, we must loop until we hit
1790 * end-of-file on the pipe. This is guaranteed to happen
1791 * eventually since the other end of the pipe is now
1792 * closed (we closed it explicitly and the child has
1793 * exited). When we do get an EOF, finish will be set
1794 * FALSE and we'll fall through and out.
1795 */
1796 goto end_loop;
984263bc 1797 }
984263bc 1798
df64c352 1799 } else {
984263bc 1800 /*
df64c352
MO
1801 * We've been called to retrieve the output of the job from the
1802 * temporary file where it's been squirreled away. This consists
1803 * of opening the file, reading the output line by line, being
1804 * sure not to print the noPrint line for the shell we used,
1805 * then close and remove the temporary file. Very simple.
1806 *
1807 * Change to read in blocks and do FindSubString type things
1808 * as for pipes? That would allow for "@echo -n..."
984263bc 1809 */
df64c352
MO
1810 oFILE = fopen(job->outFile, "r");
1811 if (oFILE != NULL) {
1812 fprintf(stdout, "Results of making %s:\n",
1813 job->node->name);
1814 fflush(stdout);
1815
1816 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
1817 char *cp, *endp, *oendp;
1818
1819 cp = inLine;
1820 oendp = endp = inLine + strlen(inLine);
1821 if (endp[-1] == '\n') {
1822 *--endp = '\0';
1823 }
1824 cp = JobOutput(job, inLine, endp, FALSE);
1825
1826 /*
1827 * There's still more in that buffer. This time,
1828 * though, we know there's no newline at the
1829 * end, so we add one of our own free will.
1830 */
1831 fprintf(stdout, "%s", cp);
1832 fflush(stdout);
1833 if (endp != oendp) {
1834 fprintf(stdout, "\n");
1835 fflush(stdout);
1836 }
1837 }
1838 fclose(oFILE);
1839 eunlink(job->outFile);
984263bc 1840 }
984263bc 1841 }
984263bc
MD
1842}
1843
df64c352
MO
1844/**
1845 * Job_CatchChildren
984263bc
MD
1846 * Handle the exit of a child. Called from Make_Make.
1847 *
984263bc
MD
1848 * Side Effects:
1849 * The job descriptor is removed from the list of children.
1850 *
1851 * Notes:
1852 * We do waits, blocking or not, according to the wisdom of our
1853 * caller, until there are no more children to report. For each
1854 * job, call JobFinish to finish things off. This will take care of
1855 * putting jobs on the stoppedJobs queue.
984263bc
MD
1856 */
1857void
84de9e23 1858Job_CatchChildren(Boolean block)
984263bc 1859{
df64c352
MO
1860 int pid; /* pid of dead child */
1861 Job *job; /* job descriptor for dead child */
1862 LstNode *jnode; /* list element for finding job */
1863 int status; /* Exit/termination status */
1864
1865 /*
1866 * Don't even bother if we know there's no one around.
1867 */
1868 if (nJobs == 0) {
1869 return;
1870 }
1871
1872 for (;;) {
1873 pid = waitpid((pid_t)-1, &status,
1874 (block ? 0 : WNOHANG) | WUNTRACED);
1875 if (pid <= 0)
0515f7ac 1876 break;
df64c352
MO
1877
1878 DEBUGF(JOB, ("Process %d exited or stopped.\n", pid));
1879
1880 LST_FOREACH(jnode, &jobs) {
1881 if (((const Job *)Lst_Datum(jnode))->pid == pid)
1882 break;
0515f7ac 1883 }
df64c352 1884
9edd457e 1885 if (jnode == NULL) {
df64c352
MO
1886 if (WIFSIGNALED(status) &&
1887 (WTERMSIG(status) == SIGCONT)) {
1888 LST_FOREACH(jnode, &stoppedJobs) {
1889 if (((const Job *)Lst_Datum(jnode))->pid == pid)
1890 break;
1891 }
1892 if (jnode == NULL) {
1893 Error("Resumed child (%d) not in table",
1894 pid);
1895 continue;
1896 }
1897 job = Lst_Datum(jnode);
1898 Lst_Remove(&stoppedJobs, jnode);
1899 } else {
1900 Error("Child (%d) not in table?", pid);
1901 continue;
1902 }
1903 } else {
1904 job = Lst_Datum(jnode);
1905 Lst_Remove(&jobs, jnode);
1906 nJobs -= 1;
1907 if (fifoFd >= 0 && maxJobs > 1) {
1908 write(fifoFd, "+", 1);
1909 maxJobs--;
1910 if (nJobs >= maxJobs)
1911 jobFull = TRUE;
1912 else
1913 jobFull = FALSE;
1914 } else {
1915 DEBUGF(JOB, ("Job queue is no longer full.\n"));
1916 jobFull = FALSE;
1917 }
984263bc 1918 }
df64c352
MO
1919
1920 JobFinish(job, &status);
1921 }
1922 if (interrupted)
1923 JobPassSig(interrupted);
984263bc
MD
1924}
1925
df64c352
MO
1926/**
1927 * Job_CatchOutput
984263bc
MD
1928 * Catch the output from our children, if we're using
1929 * pipes do so. Otherwise just block time until we get a
fbfaa208 1930 * signal(most likely a SIGCHLD) since there's no point in
984263bc
MD
1931 * just spinning when there's nothing to do and the reaping
1932 * of a child can wait for a while.
1933 *
984263bc
MD
1934 * Side Effects:
1935 * Output is read from pipes if we're piping.
1936 * -----------------------------------------------------------------------
1937 */
1938void
b24361c9
MO
1939#ifdef USE_KQUEUE
1940Job_CatchOutput(int flag __unused)
1941#else
aa582f64 1942Job_CatchOutput(int flag)
b24361c9 1943#endif
984263bc 1944{
df64c352 1945 int nfds;
218b5aa1
MD
1946#ifdef USE_KQUEUE
1947#define KEV_SIZE 4
df64c352
MO
1948 struct kevent kev[KEV_SIZE];
1949 int i;
218b5aa1 1950#else
df64c352
MO
1951 struct timeval timeout;
1952 fd_set readfds;
1953 LstNode *ln;
1954 Job *job;
218b5aa1 1955#endif
984263bc 1956
df64c352 1957 fflush(stdout);
984263bc 1958
df64c352 1959 if (usePipes) {
218b5aa1 1960#ifdef USE_KQUEUE
df64c352
MO
1961 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
1962 if (errno != EINTR)
1963 Punt("kevent: %s", strerror(errno));
1964 if (interrupted)
1965 JobPassSig(interrupted);
1966 } else {
1967 for (i = 0; i < nfds; i++) {
1968 if (kev[i].flags & EV_ERROR) {
1969 warnc(kev[i].data, "kevent");
1970 continue;
1971 }
1972 switch (kev[i].filter) {
1973 case EVFILT_READ:
1974 JobDoOutput(kev[i].udata, FALSE);
1975 break;
1976 case EVFILT_PROC:
1977 /*
1978 * Just wake up and let
1979 * Job_CatchChildren() collect the
1980 * terminated job.
1981 */
1982 break;
1983 }
1984 }
218b5aa1 1985 }
218b5aa1 1986#else
df64c352
MO
1987 readfds = outputs;
1988 timeout.tv_sec = SEL_SEC;
1989 timeout.tv_usec = SEL_USEC;
1990 if (flag && jobFull && fifoFd >= 0)
1991 FD_SET(fifoFd, &readfds);
1992
1993 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
1994 (fd_set *)NULL, &timeout);
1995 if (nfds <= 0) {
1996 if (interrupted)
1997 JobPassSig(interrupted);
1998 return;
1999 }
2000 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2001 if (--nfds <= 0)
2002 return;
2003 }
2004 for (ln = Lst_First(&jobs); nfds != 0 && ln != NULL;
2005 ln = Lst_Succ(ln)){
2006 job = Lst_Datum(ln);
2007 if (FD_ISSET(job->inPipe, &readfds)) {
2008 JobDoOutput(job, FALSE);
2009 nfds -= 1;
2010 }
2011 }
218b5aa1 2012#endif /* !USE_KQUEUE */
df64c352 2013 }
984263bc
MD
2014}
2015
df64c352
MO
2016/**
2017 * Job_Make
984263bc
MD
2018 * Start the creation of a target. Basically a front-end for
2019 * JobStart used by the Make module.
2020 *
984263bc
MD
2021 * Side Effects:
2022 * Another job is started.
984263bc
MD
2023 */
2024void
84de9e23 2025Job_Make(GNode *gn)
984263bc 2026{
fbfaa208 2027
df64c352 2028 JobStart(gn, 0, NULL);
984263bc
MD
2029}
2030
df64c352
MO
2031/**
2032 * JobCopyShell
2033 * Make a new copy of the shell structure including a copy of the strings
2034 * in it. This also defaults some fields in case they are NULL.
899365c2 2035 *
df64c352
MO
2036 * Returns:
2037 * The function returns a pointer to the new shell structure.
899365c2
MO
2038 */
2039static Shell *
2040JobCopyShell(const Shell *osh)
2041{
2042 Shell *nsh;
2043
2044 nsh = emalloc(sizeof(*nsh));
2045 nsh->name = estrdup(osh->name);
2046
2047 if (osh->echoOff != NULL)
2048 nsh->echoOff = estrdup(osh->echoOff);
2049 else
2050 nsh->echoOff = NULL;
2051 if (osh->echoOn != NULL)
2052 nsh->echoOn = estrdup(osh->echoOn);
2053 else
2054 nsh->echoOn = NULL;
2055 nsh->hasEchoCtl = osh->hasEchoCtl;
2056
2057 if (osh->noPrint != NULL)
2058 nsh->noPrint = estrdup(osh->noPrint);
2059 else
2060 nsh->noPrint = NULL;
2061 nsh->noPLen = osh->noPLen;
2062
2063 nsh->hasErrCtl = osh->hasErrCtl;
2064 if (osh->errCheck == NULL)
2065 nsh->errCheck = estrdup("");
2066 else
2067 nsh->errCheck = estrdup(osh->errCheck);
2068 if (osh->ignErr == NULL)
2069 nsh->ignErr = estrdup("%s");
2070 else
2071 nsh->ignErr = estrdup(osh->ignErr);
2072
2073 if (osh->echo == NULL)
2074 nsh->echo = estrdup("");
2075 else
2076 nsh->echo = estrdup(osh->echo);
2077
2078 if (osh->exit == NULL)
2079 nsh->exit = estrdup("");
2080 else
2081 nsh->exit = estrdup(osh->exit);
2082
2083 return (nsh);
2084}
2085
df64c352
MO
2086/**
2087 * JobFreeShell
2088 * Free a shell structure and all associated strings.
899365c2
MO
2089 */
2090static void
2091JobFreeShell(Shell *sh)
2092{
2093
2094 if (sh != NULL) {
2095 free(sh->name);
2096 free(sh->echoOff);
2097 free(sh->echoOn);
2098 free(sh->noPrint);
2099 free(sh->errCheck);
2100 free(sh->ignErr);
2101 free(sh->echo);
2102 free(sh->exit);
2103 free(sh);
2104 }
2105}
2106
2107void
2108Shell_Init(void)
2109{
2110
df64c352
MO
2111 if (commandShell == NULL)
2112 commandShell = JobMatchShell(shells[DEFSHELL].name);
899365c2 2113
df64c352
MO
2114 if (shellPath == NULL) {
2115 /*
2116 * The user didn't specify a shell to use, so we are using the
2117 * default one... Both the absolute path and the last component
2118 * must be set. The last component is taken from the 'name'
2119 * field of the default shell description pointed-to by
2120 * commandShell. All default shells are located in
2121 * PATH_DEFSHELLDIR.
2122 */
2123 shellName = commandShell->name;
2124 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2125 STR_ADDSLASH);
2126 }
899365c2
MO
2127}
2128
df64c352
MO
2129/**
2130 * Job_Init
a34ec481 2131 * Initialize the process module, given a maximum number of jobs.
984263bc 2132 *
984263bc
MD
2133 * Side Effects:
2134 * lists and counters are initialized
984263bc
MD
2135 */
2136void
a34ec481 2137Job_Init(int maxproc)
984263bc 2138{
df64c352
MO
2139 GNode *begin; /* node for commands to do at the very start */
2140 const char *env;
2141 struct sigaction sa;
984263bc 2142
df64c352
MO
2143 fifoFd = -1;
2144 env = getenv("MAKE_JOBS_FIFO");
aa582f64 2145
df64c352
MO
2146 if (env == NULL && maxproc > 1) {
2147 /*
2148 * We did not find the environment variable so we are the
2149 * leader. Create the fifo, open it, write one char per
2150 * allowed job into the pipe.
2151 */
2152 mktemp(fifoName);
2153 if (!mkfifo(fifoName, 0600)) {
2154 fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2155 if (fifoFd >= 0) {
2156 fifoMaster = 1;
2157 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2158 env = fifoName;
2159 setenv("MAKE_JOBS_FIFO", env, 1);
2160 while (maxproc-- > 0) {
2161 write(fifoFd, "+", 1);
2162 }
2163 /* The master make does not get a magic token */
2164 jobFull = TRUE;
2165 maxJobs = 0;
2166 } else {
2167 unlink(fifoName);
2168 env = NULL;
2169 }
aa582f64 2170 }
df64c352
MO
2171
2172 } else if (env != NULL) {
2173 /*
2174 * We had the environment variable so we are a slave.
2175 * Open fifo and give ourselves a magic token which represents
2176 * the token our parent make has grabbed to start his make
2177 * process. Otherwise the sub-makes would gobble up tokens and
2178 * the proper number of tokens to specify to -j would depend
2179 * on the depth of the tree and the order of execution.
2180 */
2181 fifoFd = open(env, O_RDWR, 0);
2182 if (fifoFd >= 0) {
2183 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2184 maxJobs = 1;
2185 jobFull = FALSE;
2186 }
2187 }
2188 if (fifoFd <= 0) {
2189 maxJobs = maxproc;
2190 jobFull = FALSE;
2191 } else {
2192 }
2193 nJobs = 0;
2194
2195 aborting = 0;
2196 errors = 0;
2197
2198 lastNode = NULL;
2199
2200 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2201 /*
2202 * If only one job can run at a time, there's no need for a
2203 * banner, no is there?
2204 */
2205 targFmt = "";
2206 } else {
2207 targFmt = TARG_FMT;
aa582f64 2208 }
984263bc 2209
df64c352 2210 Shell_Init();
984263bc 2211
df64c352
MO
2212 /*
2213 * Catch the four signals that POSIX specifies if they aren't ignored.
2214 * JobCatchSignal will just set global variables and hope someone
2215 * else is going to handle the interrupt.
2216 */
2217 sa.sa_handler = JobCatchSig;
2218 sigemptyset(&sa.sa_mask);
2219 sa.sa_flags = 0;
984263bc 2220
df64c352
MO
2221 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2222 sigaction(SIGINT, &sa, NULL);
2223 }
2224 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2225 sigaction(SIGHUP, &sa, NULL);
2226 }
2227 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2228 sigaction(SIGQUIT, &sa, NULL);
2229 }
2230 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2231 sigaction(SIGTERM, &sa, NULL);
2232 }
984263bc 2233 /*
df64c352
MO
2234 * There are additional signals that need to be caught and passed if
2235 * either the export system wants to be told directly of signals or if
2236 * we're giving each job its own process group (since then it won't get
2237 * signals from the terminal driver as we own the terminal)
984263bc 2238 */
a34ec481 2239#if defined(USE_PGRP)
df64c352
MO
2240 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2241 sigaction(SIGTSTP, &sa, NULL);
2242 }
2243 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2244 sigaction(SIGTTOU, &sa, NULL);
2245 }
2246 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2247 sigaction(SIGTTIN, &sa, NULL);
2248 }
2249 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2250 sigaction(SIGWINCH, &sa, NULL);
2251 }
984263bc
MD
2252#endif
2253
218b5aa1 2254#ifdef USE_KQUEUE
df64c352
MO
2255 if ((kqfd = kqueue()) == -1) {
2256 Punt("kqueue: %s", strerror(errno));
2257 }
218b5aa1
MD
2258#endif
2259
df64c352 2260 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
984263bc 2261
df64c352
MO
2262 if (begin != NULL) {
2263 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2264 while (nJobs) {
2265 Job_CatchOutput(0);
2266 Job_CatchChildren(!usePipes);
2267 }
984263bc 2268 }
df64c352 2269 postCommands = Targ_FindNode(".END", TARG_CREATE);
984263bc
MD
2270}
2271
df64c352
MO
2272/**
2273 * Job_Full
984263bc
MD
2274 * See if the job table is full. It is considered full if it is OR
2275 * if we are in the process of aborting OR if we have
2276 * reached/exceeded our local quota. This prevents any more jobs
2277 * from starting up.
2278 *
2279 * Results:
2280 * TRUE if the job table is full, FALSE otherwise
984263bc
MD
2281 */
2282Boolean
84de9e23 2283Job_Full(void)
984263bc 2284{
df64c352
MO
2285 char c;
2286 int i;
2287
2288 if (aborting)
2289 return (aborting);
2290 if (fifoFd >= 0 && jobFull) {
2291 i = read(fifoFd, &c, 1);
2292 if (i > 0) {
2293 maxJobs++;
2294 jobFull = FALSE;
2295 }
2296 }
2297 return (jobFull);
984263bc
MD
2298}
2299
df64c352
MO
2300/**
2301 * Job_Empty
984263bc
MD
2302 * See if the job table is empty. Because the local concurrency may
2303 * be set to 0, it is possible for the job table to become empty,
2304 * while the list of stoppedJobs remains non-empty. In such a case,
2305 * we want to restart as many jobs as we can.
2306 *
2307 * Results:
2308 * TRUE if it is. FALSE if it ain't.
984263bc
MD
2309 */
2310Boolean
84de9e23 2311Job_Empty(void)
984263bc 2312{
df64c352
MO
2313 if (nJobs == 0) {
2314 if (!Lst_IsEmpty(&stoppedJobs) && !aborting) {
2315 /*
2316 * The job table is obviously not full if it has no
2317 * jobs in it...Try and restart the stopped jobs.
2318 */
2319 jobFull = FALSE;
2320 JobRestartJobs();
2321 return (FALSE);
2322 } else {
2323 return (TRUE);
2324 }
984263bc 2325 } else {
df64c352 2326 return (FALSE);
984263bc 2327 }
984263bc
MD
2328}
2329
df64c352
MO
2330/**
2331 * JobMatchShell
984263bc
MD
2332 * Find a matching shell in 'shells' given its final component.
2333 *
2334 * Results:
a4063c43 2335 * A pointer to a freshly allocated Shell structure with a copy
899365c2
MO
2336 * of the static structure or NULL if no shell with the given name
2337 * is found.
984263bc
MD
2338 */
2339static Shell *
899365c2 2340JobMatchShell(const char *name)
984263bc 2341{
df64c352
MO
2342 const struct CShell *sh; /* Pointer into shells table */
2343 struct Shell *nsh;
2344
2345 for (sh = shells; sh < shells + __arysize(shells); sh++)
2346 if (strcmp(sh->name, name) == 0)
2347 break;
2348
2349 if (sh == shells + __arysize(shells))
2350 return (NULL);
2351
2352 /* make a copy */
2353 nsh = emalloc(sizeof(*nsh));
2354
2355 nsh->name = estrdup(sh->name);
2356 nsh->echoOff = estrdup(sh->echoOff);
2357 nsh->echoOn = estrdup(sh->echoOn);
2358 nsh->hasEchoCtl = sh->hasEchoCtl;
2359 nsh->noPrint = estrdup(sh->noPrint);
2360 nsh->noPLen = sh->noPLen;
2361 nsh->hasErrCtl = sh->hasErrCtl;
2362 nsh->errCheck = estrdup(sh->errCheck);
2363 nsh->ignErr = estrdup(sh->ignErr);
2364 nsh->echo = estrdup(sh->echo);
2365 nsh->exit = estrdup(sh->exit);
2366
2367 return (nsh);
984263bc
MD
2368}
2369
df64c352
MO
2370/**
2371 * Job_ParseShell
984263bc
MD
2372 * Parse a shell specification and set up commandShell, shellPath
2373 * and shellName appropriately.
2374 *
2375 * Results:
2376 * FAILURE if the specification was incorrect.
2377 *
2378 * Side Effects:
2379 * commandShell points to a Shell structure (either predefined or
2380 * created from the shell spec), shellPath is the full path of the
2381 * shell described by commandShell, while shellName is just the
2382 * final component of shellPath.
2383 *
2384 * Notes:
2385 * A shell specification consists of a .SHELL target, with dependency
2386 * operator, followed by a series of blank-separated words. Double
2387 * quotes can be used to use blanks in words. A backslash escapes
2388 * anything (most notably a double-quote and a space) and
2389 * provides the functionality it does in C. Each word consists of
2390 * keyword and value separated by an equal sign. There should be no
2391 * unnecessary spaces in the word. The keywords are as follows:
2392 * name Name of shell.
2393 * path Location of shell. Overrides "name" if given
2394 * quiet Command to turn off echoing.
2395 * echo Command to turn echoing on
2396 * filter Result of turning off echoing that shouldn't be
2397 * printed.
2398 * echoFlag Flag to turn echoing on at the start
2399 * errFlag Flag to turn error checking on at the start
2400 * hasErrCtl True if shell has error checking control
2401 * check Command to turn on error checking if hasErrCtl
2402 * is TRUE or template of command to echo a command
2403 * for which error checking is off if hasErrCtl is
2404 * FALSE.
2405 * ignore Command to turn off error checking if hasErrCtl
2406 * is TRUE or template of command to execute a
2407 * command so as to ignore any errors it returns if
2408 * hasErrCtl is FALSE.
984263bc
MD
2409 */
2410ReturnStatus
84de9e23 2411Job_ParseShell(char *line)
984263bc 2412{
df64c352
MO
2413 char **words;
2414 int wordCount;
2415 char **argv;
2416 int argc;
2417 char *path;
2418 Shell newShell;
2419 Shell *sh;
2420 Boolean fullSpec = FALSE;
2421
2422 while (isspace((unsigned char)*line)) {
2423 line++;
2424 }
2425 words = brk_string(line, &wordCount, TRUE);
2426
2427 memset(&newShell, 0, sizeof(newShell));
2428
984263bc 2429 /*
df64c352 2430 * Parse the specification by keyword
984263bc 2431 */
df64c352
MO
2432 for (path = NULL, argc = wordCount - 1, argv = words + 1; argc != 0;
2433 argc--, argv++) {
2434 if (strncmp(*argv, "path=", 5) == 0) {
2435 path = &argv[0][5];
2436 } else if (strncmp(*argv, "name=", 5) == 0) {
2437 newShell.name = &argv[0][5];
2438 } else {
2439 if (strncmp(*argv, "quiet=", 6) == 0) {
2440 newShell.echoOff = &argv[0][6];
2441 } else if (strncmp(*argv, "echo=", 5) == 0) {
2442 newShell.echoOn = &argv[0][5];
2443 } else if (strncmp(*argv, "filter=", 7) == 0) {
2444 newShell.noPrint = &argv[0][7];
2445 newShell.noPLen = strlen(newShell.noPrint);
2446 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2447 newShell.echo = &argv[0][9];
2448 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2449 newShell.exit = &argv[0][8];
2450 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2451 char c = argv[0][10];
2452 newShell.hasErrCtl = !((c != 'Y') &&
2453 (c != 'y') && (c != 'T') && (c != 't'));
2454 } else if (strncmp(*argv, "check=", 6) == 0) {
2455 newShell.errCheck = &argv[0][6];
2456 } else if (strncmp(*argv, "ignore=", 7) == 0) {
2457 newShell.ignErr = &argv[0][7];
2458 } else {
2459 Parse_Error(PARSE_FATAL,
2460 "Unknown keyword \"%s\"", *argv);
2461 return (FAILURE);
2462 }
2463 fullSpec = TRUE;
2464 }
899365c2
MO
2465 }
2466
984263bc 2467 /*
df64c352 2468 * Some checks (could be more)
984263bc 2469 */
df64c352
MO
2470 if (fullSpec) {
2471 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2472 Parse_Error(PARSE_FATAL, "Shell must have either both "
2473 "echoOff and echoOn or none of them");
2474
2475 if (newShell.echoOn != NULL && newShell.echoOff)
2476 newShell.hasEchoCtl = TRUE;
2477 }
2478
2479 if (path == NULL) {
2480 /*
2481 * If no path was given, the user wants one of the pre-defined
2482 * shells, yes? So we find the one s/he wants with the help of
2483 * JobMatchShell and set things up the right way. shellPath
2484 * will be set up by Job_Init.
2485 */
2486 if (newShell.name == NULL) {
2487 Parse_Error(PARSE_FATAL,
2488 "Neither path nor name specified");
2489 return (FAILURE);
2490 }
2491 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2492 Parse_Error(PARSE_FATAL, "%s: no matching shell",
2493 newShell.name);
2494 return (FAILURE);
2495 }
2496
984263bc 2497 } else {
df64c352
MO
2498 /*
2499 * The user provided a path. If s/he gave nothing else
2500 * (fullSpec is FALSE), try and find a matching shell in the
2501 * ones we know of. Else we just take the specification at its
2502 * word and copy it to a new location. In either case, we need
2503 * to record the path the user gave for the shell.
2504 */
2505 free(shellPath);
2506 shellPath = estrdup(path);
2507 if (newShell.name == NULL) {
2508 /* get the base name as the name */
2509 path = strrchr(path, '/');
2510 if (path == NULL) {
2511 path = shellPath;
2512 } else {
2513 path += 1;
2514 }
2515 newShell.name = path;
2516 }
2517
2518 if (!fullSpec) {
2519 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2520 Parse_Error(PARSE_FATAL,
2521 "%s: no matching shell", newShell.name);
2522 return (FAILURE);
2523 }
2524 } else {
2525 sh = JobCopyShell(&newShell);
2526 }
984263bc 2527 }
984263bc 2528
df64c352
MO
2529 /* set the new shell */
2530 JobFreeShell(commandShell);
2531 commandShell = sh;
984263bc 2532
df64c352 2533 shellName = commandShell->name;
899365c2 2534
df64c352 2535 return (SUCCESS);
984263bc
MD
2536}
2537
df64c352
MO
2538/**
2539 * JobInterrupt
984263bc
MD
2540 * Handle the receipt of an interrupt.
2541 *
984263bc
MD
2542 * Side Effects:
2543 * All children are killed. Another job will be started if the
2544 * .INTERRUPT target was given.
984263bc
MD
2545 */
2546static void
84de9e23 2547JobInterrupt(int runINTERRUPT, int signo)
984263bc 2548{
df64c352
MO
2549 LstNode *ln; /* element in job table */
2550 Job *job; /* job descriptor in that element */
2551 GNode *interrupt; /* the node describing the .INTERRUPT target */
984263bc 2552
df64c352 2553 aborting = ABORT_INTERRUPT;
984263bc 2554
df64c352
MO
2555 for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Succ(ln)) {
2556 job = Lst_Datum(ln);
984263bc 2557
df64c352
MO
2558 if (!Targ_Precious(job->node)) {
2559 char *file = (job->node->path == NULL ?
2560 job->node->name : job->node->path);
2561
2562 if (!noExecute && eunlink(file) != -1) {
2563 Error("*** %s removed", file);
2564 }
2565 }
2566 if (job->pid) {
2567 DEBUGF(JOB, ("JobInterrupt passing signal to child "
2568 "%d.\n", job->pid));
2569 KILL(job->pid, signo);
2570 }
984263bc 2571 }
984263bc 2572
df64c352
MO
2573 if (runINTERRUPT && !touchFlag) {
2574 /*
2575 * clear the interrupted flag because we would get an
2576 * infinite loop otherwise.
2577 */
2578 interrupted = 0;
89a1b397 2579
df64c352
MO
2580 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2581 if (interrupt != NULL) {
2582 ignoreErrors = FALSE;
984263bc 2583
df64c352
MO
2584 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2585 while (nJobs) {
2586 Job_CatchOutput(0);
2587 Job_CatchChildren(!usePipes);
2588 }
2589 }
984263bc 2590 }
984263bc
MD
2591}
2592
df64c352
MO
2593/**
2594 * Job_Finish
984263bc
MD
2595 * Do final processing such as the running of the commands
2596 * attached to the .END target.
2597 *
2598 * Results:
2599 * Number of errors reported.
984263bc
MD
2600 */
2601int
84de9e23 2602Job_Finish(void)
984263bc 2603{
fbfaa208 2604
df64c352
MO
2605 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2606 if (errors) {
2607 Error("Errors reported so .END ignored");
2608 } else {
2609 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
984263bc 2610
df64c352
MO
2611 while (nJobs) {
2612 Job_CatchOutput(0);
2613 Job_CatchChildren(!usePipes);
2614 }
2615 }
984263bc 2616 }
df64c352
MO
2617 if (fifoFd >= 0) {
2618 close(fifoFd);
2619 fifoFd = -1;
2620 if (fifoMaster)
2621 unlink(fifoName);
2622 }
2623 return (errors);
984263bc
MD
2624}
2625
df64c352
MO
2626/**
2627 * Job_Wait
984263bc
MD
2628 * Waits for all running jobs to finish and returns. Sets 'aborting'
2629 * to ABORT_WAIT to prevent other jobs from starting.
2630 *
984263bc
MD
2631 * Side Effects:
2632 * Currently running jobs finish.
984263bc
MD
2633 */
2634void
84de9e23 2635Job_Wait(void)
984263bc 2636{
fbfaa208 2637
df64c352
MO
2638 aborting = ABORT_WAIT;
2639 while (nJobs != 0) {
2640 Job_CatchOutput(0);
2641 Job_CatchChildren(!usePipes);
2642 }
2643 aborting = 0;
984263bc
MD
2644}
2645
df64c352
MO
2646/**
2647 * Job_AbortAll
984263bc
MD
2648 * Abort all currently running jobs without handling output or anything.
2649 * This function is to be called only in the event of a major
2650 * error. Most definitely NOT to be called from JobInterrupt.
2651 *
984263bc
MD
2652 * Side Effects:
2653 * All children are killed, not just the firstborn
984263bc
MD
2654 */
2655void
84de9e23 2656Job_AbortAll(void)
984263bc 2657{
df64c352
MO
2658 LstNode *ln; /* element in job table */
2659 Job *job; /* the job descriptor in that element */
2660 int foo;
984263bc 2661
df64c352 2662 aborting = ABORT_ERROR;
984263bc 2663
df64c352
MO
2664 if (nJobs) {
2665 for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Succ(ln)) {
2666 job = Lst_Datum(ln);
2667
2668 /*
2669 * kill the child process with increasingly drastic
2670 * signals to make darn sure it's dead.
2671 */
2672 KILL(job->pid, SIGINT);
2673 KILL(job->pid, SIGKILL);
2674 }
2675 }
2676
2677 /*
2678 * Catch as many children as want to report in at first, then give up
2679 */
2680 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2681 continue;
984263bc
MD
2682}
2683
df64c352
MO
2684/**
2685 * JobRestartJobs
984263bc
MD
2686 * Tries to restart stopped jobs if there are slots available.
2687 * Note that this tries to restart them regardless of pending errors.
2688 * It's not good to leave stopped jobs lying around!
2689 *
984263bc
MD
2690 * Side Effects:
2691 * Resumes(and possibly migrates) jobs.
984263bc
MD
2692 */
2693static void
84de9e23 2694JobRestartJobs(void)
984263bc 2695{
df64c352
MO
2696 while (!jobFull && !Lst_IsEmpty(&stoppedJobs)) {
2697 DEBUGF(JOB, ("Job queue is not full. "
2698 "Restarting a stopped job.\n"));
2699 JobRestart(Lst_DeQueue(&stoppedJobs));
2700 }
984263bc 2701}