xref: /netbsd-src/usr.bin/make/job.c (revision 9fbd88883c38d0c0fbfcbe66d76fe6b0fab3f9de)
1 /*	$NetBSD: job.c,v 1.55 2001/10/16 18:06:29 sjg Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5  * Copyright (c) 1988, 1989 by Adam de Boor
6  * Copyright (c) 1989 by Berkeley Softworks
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Adam de Boor.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #ifdef MAKE_BOOTSTRAP
42 static char rcsid[] = "$NetBSD: job.c,v 1.55 2001/10/16 18:06:29 sjg Exp $";
43 #else
44 #include <sys/cdefs.h>
45 #ifndef lint
46 #if 0
47 static char sccsid[] = "@(#)job.c	8.2 (Berkeley) 3/19/94";
48 #else
49 __RCSID("$NetBSD: job.c,v 1.55 2001/10/16 18:06:29 sjg Exp $");
50 #endif
51 #endif /* not lint */
52 #endif
53 
54 /*-
55  * job.c --
56  *	handle the creation etc. of our child processes.
57  *
58  * Interface:
59  *	Job_Make  	    	Start the creation of the given target.
60  *
61  *	Job_CatchChildren   	Check for and handle the termination of any
62  *	    	  	    	children. This must be called reasonably
63  *	    	  	    	frequently to keep the whole make going at
64  *	    	  	    	a decent clip, since job table entries aren't
65  *	    	  	    	removed until their process is caught this way.
66  *	    	  	    	Its single argument is TRUE if the function
67  *	    	  	    	should block waiting for a child to terminate.
68  *
69  *	Job_CatchOutput	    	Print any output our children have produced.
70  *	    	  	    	Should also be called fairly frequently to
71  *	    	  	    	keep the user informed of what's going on.
72  *	    	  	    	If no output is waiting, it will block for
73  *	    	  	    	a time given by the SEL_* constants, below,
74  *	    	  	    	or until output is ready.
75  *
76  *	Job_Init  	    	Called to intialize this module. in addition,
77  *	    	  	    	any commands attached to the .BEGIN target
78  *	    	  	    	are executed before this function returns.
79  *	    	  	    	Hence, the makefile must have been parsed
80  *	    	  	    	before this function is called.
81  *
82  *	Job_End  	    	Cleanup any memory used.
83  *
84  *	Job_Empty 	    	Return TRUE if the job table is completely
85  *	    	  	    	empty.
86  *
87  *	Job_ParseShell	    	Given the line following a .SHELL target, parse
88  *	    	  	    	the line as a shell specification. Returns
89  *	    	  	    	FAILURE if the spec was incorrect.
90  *
91  *	Job_Finish	    	Perform any final processing which needs doing.
92  *	    	  	    	This includes the execution of any commands
93  *	    	  	    	which have been/were attached to the .END
94  *	    	  	    	target. It should only be called when the
95  *	    	  	    	job table is empty.
96  *
97  *	Job_AbortAll	    	Abort all currently running jobs. It doesn't
98  *	    	  	    	handle output or do anything for the jobs,
99  *	    	  	    	just kills them. It should only be called in
100  *	    	  	    	an emergency, as it were.
101  *
102  *	Job_CheckCommands   	Verify that the commands for a target are
103  *	    	  	    	ok. Provide them if necessary and possible.
104  *
105  *	Job_Touch 	    	Update a target without really updating it.
106  *
107  *	Job_Wait  	    	Wait for all currently-running jobs to finish.
108  */
109 
110 #include <sys/types.h>
111 #include <sys/stat.h>
112 #include <sys/file.h>
113 #include <sys/time.h>
114 #include <sys/wait.h>
115 #include <fcntl.h>
116 #include <errno.h>
117 #include <utime.h>
118 #include <stdio.h>
119 #include <string.h>
120 #include <signal.h>
121 #ifndef RMT_WILL_WATCH
122 #ifndef USE_SELECT
123 #include <poll.h>
124 #endif
125 #endif
126 #include "make.h"
127 #include "hash.h"
128 #include "dir.h"
129 #include "job.h"
130 #include "pathnames.h"
131 #include "trace.h"
132 #ifdef REMOTE
133 #include "rmt.h"
134 # define STATIC
135 #else
136 # define STATIC static
137 #endif
138 
139 /*
140  * error handling variables
141  */
142 static int     	errors = 0;	    /* number of errors reported */
143 static int    	aborting = 0;	    /* why is the make aborting? */
144 #define ABORT_ERROR	1   	    /* Because of an error */
145 #define ABORT_INTERRUPT	2   	    /* Because it was interrupted */
146 #define ABORT_WAIT	3   	    /* Waiting for jobs to finish */
147 
148 /*
149  * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
150  * is a char! So when we go above 127 we turn negative!
151  */
152 #define FILENO(a) ((unsigned) fileno(a))
153 
154 /*
155  * post-make command processing. The node postCommands is really just the
156  * .END target but we keep it around to avoid having to search for it
157  * all the time.
158  */
159 static GNode   	  *postCommands;    /* node containing commands to execute when
160 				     * everything else is done */
161 static int     	  numCommands; 	    /* The number of commands actually printed
162 				     * for a target. Should this number be
163 				     * 0, no shell will be executed. */
164 
165 /*
166  * Return values from JobStart.
167  */
168 #define JOB_RUNNING	0   	/* Job is running */
169 #define JOB_ERROR 	1   	/* Error in starting the job */
170 #define JOB_FINISHED	2   	/* The job is already finished */
171 #define JOB_STOPPED	3   	/* The job is stopped */
172 
173 
174 
175 /*
176  * Descriptions for various shells.
177  */
178 static Shell    shells[] = {
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", 10,
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",
198 #ifdef OLDBOURNESHELL
199     FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
200 #endif
201 #ifdef __NetBSD__
202     "vq",
203 #else
204     "v",
205 #endif
206     "e",
207 },
208     /*
209      * UNKNOWN.
210      */
211 {
212     (char *) 0,
213     FALSE, (char *) 0, (char *) 0, (char *) 0, 0,
214     FALSE, (char *) 0, (char *) 0,
215     (char *) 0, (char *) 0,
216 }
217 };
218 static Shell 	*commandShell = &shells[DEFSHELL];/* this is the shell to
219 						   * which we pass all
220 						   * commands in the Makefile.
221 						   * It is set by the
222 						   * Job_ParseShell function */
223 static char   	*shellPath = NULL,		  /* full pathname of
224 						   * executable image */
225                	*shellName = NULL,	      	  /* last component of shell */
226 		*shellArgv = NULL;		  /* Custom shell args */
227 
228 
229 static int  	maxJobs;    	/* The most children we can run at once */
230 static int  	maxLocal;    	/* The most local ones we can have */
231 STATIC int     	nJobs;	    	/* The number of children currently running */
232 STATIC int	nLocal;    	/* The number of local children */
233 STATIC Lst     	jobs;		/* The structures that describe them */
234 static Boolean	wantToken;	/* we want a token */
235 
236 /*
237  * Set of descriptors of pipes connected to
238  * the output channels of children
239  */
240 #ifndef RMT_WILL_WATCH
241 #ifdef USE_SELECT
242 static fd_set  	outputs;
243 #else
244 static struct pollfd *fds = NULL;
245 static Job **jobfds = NULL;
246 static int nfds = 0;
247 static int maxfds = 0;
248 static void watchfd __P((Job *));
249 static void clearfd __P((Job *));
250 static int readyfd __P((Job *));
251 #define JBSTART 256
252 #define JBFACTOR 2
253 #endif
254 #endif
255 
256 STATIC GNode   	*lastNode;	/* The node for which output was most recently
257 				 * produced. */
258 STATIC char    	*targFmt;   	/* Format string to use to head output from a
259 				 * job when it's not the most-recent job heard
260 				 * from */
261 static Job tokenWaitJob;	/* token wait pseudo-job */
262 int	job_pipe[2] = { -1, -1 }; /* job server pipes. */
263 
264 #ifdef REMOTE
265 # define TARG_FMT  "--- %s at %s ---\n" /* Default format */
266 # define MESSAGE(fp, gn) \
267 	(void) fprintf(fp, targFmt, gn->name, gn->rem.hname)
268 #else
269 # define TARG_FMT  "--- %s ---\n" /* Default format */
270 # define MESSAGE(fp, gn) \
271 	(void) fprintf(fp, targFmt, gn->name)
272 #endif
273 
274 /*
275  * When JobStart attempts to run a job remotely but can't, and isn't allowed
276  * to run the job locally, or when Job_CatchChildren detects a job that has
277  * been migrated home, the job is placed on the stoppedJobs queue to be run
278  * when the next job finishes.
279  */
280 STATIC Lst	stoppedJobs;	/* Lst of Job structures describing
281 				 * jobs that were stopped due to concurrency
282 				 * limits or migration home */
283 
284 
285 #if defined(USE_PGRP) && defined(SYSV)
286 # define KILL(pid, sig)		kill(-(pid), (sig))
287 #else
288 # if defined(USE_PGRP)
289 #  define KILL(pid, sig)	killpg((pid), (sig))
290 # else
291 #  define KILL(pid, sig)	kill((pid), (sig))
292 # endif
293 #endif
294 
295 /*
296  * Grmpf... There is no way to set bits of the wait structure
297  * anymore with the stupid W*() macros. I liked the union wait
298  * stuff much more. So, we devise our own macros... This is
299  * really ugly, use dramamine sparingly. You have been warned.
300  */
301 #ifndef W_STOPCODE
302 #define W_STOPCODE(sig) (((sig) << 8) | 0177)
303 #endif
304 #ifndef W_EXITCODE
305 #define W_EXITCODE(ret, sig) ((ret << 8) | (sig))
306 #endif
307 
308 static int JobCondPassSig __P((ClientData, ClientData));
309 static void JobPassSig __P((int));
310 static void JobIgnoreSig __P((int));
311 #ifdef USE_PGRP
312 static void JobContinueSig __P((int));
313 #endif
314 static int JobCmpPid __P((ClientData, ClientData));
315 static int JobPrintCommand __P((ClientData, ClientData));
316 static int JobSaveCommand __P((ClientData, ClientData));
317 static void JobClose __P((Job *));
318 #ifdef REMOTE
319 static int JobCmpRmtID __P((Job *, int));
320 # ifdef RMT_WILL_WATCH
321 static void JobLocalInput __P((int, Job *));
322 # endif
323 #else
324 static void JobFinish __P((Job *, int *));
325 static void JobExec __P((Job *, char **));
326 #endif
327 static void JobMakeArgv __P((Job *, char **));
328 static void JobRestart __P((Job *));
329 static int JobStart __P((GNode *, int, Job *));
330 static char *JobOutput __P((Job *, char *, char *, int));
331 static void JobDoOutput __P((Job *, Boolean));
332 static Shell *JobMatchShell __P((char *));
333 static void JobInterrupt __P((int, int));
334 static void JobRestartJobs __P((void));
335 static void JobTokenAdd __P((void));
336 
337 /*-
338  *-----------------------------------------------------------------------
339  * JobCondPassSig --
340  *	Pass a signal to a job if the job is remote or if USE_PGRP
341  *	is defined.
342  *
343  * Results:
344  *	=== 0
345  *
346  * Side Effects:
347  *	None, except the job may bite it.
348  *
349  *-----------------------------------------------------------------------
350  */
351 static int
352 JobCondPassSig(jobp, signop)
353     ClientData	    	jobp;	    /* Job to biff */
354     ClientData	    	signop;	    /* Signal to send it */
355 {
356     Job	*job = (Job *) jobp;
357     int	signo = *(int *) signop;
358 #ifdef RMT_WANTS_SIGNALS
359     if (job->flags & JOB_REMOTE) {
360 	(void) Rmt_Signal(job, signo);
361     } else {
362 	KILL(job->pid, signo);
363     }
364 #else
365     /*
366      * Assume that sending the signal to job->pid will signal any remote
367      * job as well.
368      */
369     if (DEBUG(JOB)) {
370 	(void) fprintf(stdout,
371 		       "JobCondPassSig passing signal %d to child %d.\n",
372 		       signo, job->pid);
373 	(void) fflush(stdout);
374     }
375     KILL(job->pid, signo);
376 #endif
377     return 0;
378 }
379 
380 /*-
381  *-----------------------------------------------------------------------
382  * JobIgnoreSig --
383  *	No-op signal handler so we wake up from poll.
384  *
385  * Results:
386  *	None.
387  *
388  * Side Effects:
389  *	None.
390  *
391  *-----------------------------------------------------------------------
392  */
393 static void
394 JobIgnoreSig(signo)
395     int	    signo;	/* The signal number we've received */
396 {
397 	/*
398 	 * Do nothing.  The mere fact that we've been called will cause
399 	 * poll/select in Job_CatchOutput() to return early.
400 	 */
401 }
402 
403 
404 #ifdef USE_PGRP
405 /*-
406  *-----------------------------------------------------------------------
407  * JobContinueSig --
408  *	Resume all stopped jobs.
409  *
410  * Results:
411  *	None.
412  *
413  * Side Effects:
414  *	Jobs start running again.
415  *
416  *-----------------------------------------------------------------------
417  */
418 static void
419 JobContinueSig(signo)
420     int	    signo;	/* The signal number we've received */
421 {
422     if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
423 	(void) signal(SIGTSTP, JobPassSig);
424     }
425     JobRestartJobs();
426 }
427 #endif
428 
429 /*-
430  *-----------------------------------------------------------------------
431  * JobPassSig --
432  *	Pass a signal on to all remote jobs and to all local jobs if
433  *	USE_PGRP is defined, then die ourselves.
434  *
435  * Results:
436  *	None.
437  *
438  * Side Effects:
439  *	We die by the same signal.
440  *
441  *-----------------------------------------------------------------------
442  */
443 static void
444 JobPassSig(signo)
445     int	    signo;	/* The signal number we've received */
446 {
447     sigset_t nmask, omask;
448     struct sigaction act;
449     int sigcont;
450 
451     if (DEBUG(JOB)) {
452 	(void) fprintf(stdout, "JobPassSig(%d) called.\n", signo);
453 	(void) fflush(stdout);
454     }
455     Lst_ForEach(jobs, JobCondPassSig, (ClientData) &signo);
456 
457     /*
458      * Deal with proper cleanup based on the signal received. We only run
459      * the .INTERRUPT target if the signal was in fact an interrupt. The other
460      * three termination signals are more of a "get out *now*" command.
461      */
462     if (signo == SIGINT) {
463 	JobInterrupt(TRUE, signo);
464     } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
465 	JobInterrupt(FALSE, signo);
466     }
467 
468     /*
469      * Leave gracefully if SIGQUIT, rather than core dumping.
470      */
471     if (signo == SIGQUIT) {
472 	Finish(0);
473     }
474 
475     if (signo == SIGTSTP) {
476 	Job_CatchChildren(FALSE);
477     }
478     /*
479      * Send ourselves the signal now we've given the message to everyone else.
480      * Note we block everything else possible while we're getting the signal.
481      * This ensures that all our jobs get continued when we wake up before
482      * we take any other signal.
483      */
484     sigfillset(&nmask);
485     sigprocmask(SIG_SETMASK, &nmask, &omask);
486     act.sa_handler = SIG_DFL;
487     sigemptyset(&act.sa_mask);
488     act.sa_flags = 0;
489     sigaction(signo, &act, NULL);
490 
491     if (DEBUG(JOB)) {
492 	(void) fprintf(stdout,
493 		       "JobPassSig passing signal %d to self.\n", signo);
494 	(void) fflush(stdout);
495     }
496 
497     (void) kill(getpid(), signo);
498     if (signo != SIGTSTP) {
499 	sigcont = SIGCONT;
500 	Lst_ForEach(jobs, JobCondPassSig, (ClientData) &sigcont);
501     }
502 
503     (void) sigprocmask(SIG_SETMASK, &omask, NULL);
504     sigprocmask(SIG_SETMASK, &omask, NULL);
505     if (signo != SIGCONT && signo != SIGTSTP) {
506 	act.sa_handler = JobPassSig;
507 	sigaction(sigcont, &act, NULL);
508     }
509 }
510 
511 /*-
512  *-----------------------------------------------------------------------
513  * JobCmpPid  --
514  *	Compare the pid of the job with the given pid and return 0 if they
515  *	are equal. This function is called from Job_CatchChildren via
516  *	Lst_Find to find the job descriptor of the finished job.
517  *
518  * Results:
519  *	0 if the pid's match
520  *
521  * Side Effects:
522  *	None
523  *-----------------------------------------------------------------------
524  */
525 static int
526 JobCmpPid(job, pid)
527     ClientData        job;	/* job to examine */
528     ClientData        pid;	/* process id desired */
529 {
530     return *(int *) pid - ((Job *) job)->pid;
531 }
532 
533 #ifdef REMOTE
534 /*-
535  *-----------------------------------------------------------------------
536  * JobCmpRmtID  --
537  *	Compare the rmtID of the job with the given rmtID and return 0 if they
538  *	are equal.
539  *
540  * Results:
541  *	0 if the rmtID's match
542  *
543  * Side Effects:
544  *	None.
545  *-----------------------------------------------------------------------
546  */
547 static int
548 JobCmpRmtID(job, rmtID)
549     ClientData      job;	/* job to examine */
550     ClientData      rmtID;	/* remote id desired */
551 {
552     return(*(int *) rmtID - *(int *) job->rmtID);
553 }
554 #endif
555 
556 /*-
557  *-----------------------------------------------------------------------
558  * JobPrintCommand  --
559  *	Put out another command for the given job. If the command starts
560  *	with an @ or a - we process it specially. In the former case,
561  *	so long as the -s and -n flags weren't given to make, we stick
562  *	a shell-specific echoOff command in the script. In the latter,
563  *	we ignore errors for the entire job, unless the shell has error
564  *	control.
565  *	If the command is just "..." we take all future commands for this
566  *	job to be commands to be executed once the entire graph has been
567  *	made and return non-zero to signal that the end of the commands
568  *	was reached. These commands are later attached to the postCommands
569  *	node and executed by Job_End when all things are done.
570  *	This function is called from JobStart via Lst_ForEach.
571  *
572  * Results:
573  *	Always 0, unless the command was "..."
574  *
575  * Side Effects:
576  *	If the command begins with a '-' and the shell has no error control,
577  *	the JOB_IGNERR flag is set in the job descriptor.
578  *	If the command is "..." and we're not ignoring such things,
579  *	tailCmds is set to the successor node of the cmd.
580  *	numCommands is incremented if the command is actually printed.
581  *-----------------------------------------------------------------------
582  */
583 static int
584 JobPrintCommand(cmdp, jobp)
585     ClientData    cmdp;	    	    /* command string to print */
586     ClientData    jobp;	    	    /* job for which to print it */
587 {
588     Boolean	  noSpecials;	    /* true if we shouldn't worry about
589 				     * inserting special commands into
590 				     * the input stream. */
591     Boolean       shutUp = FALSE;   /* true if we put a no echo command
592 				     * into the command file */
593     Boolean	  errOff = FALSE;   /* true if we turned error checking
594 				     * off before printing the command
595 				     * and need to turn it back on */
596     char       	  *cmdTemplate;	    /* Template to use when printing the
597 				     * command */
598     char    	  *cmdStart;	    /* Start of expanded command */
599     LstNode 	  cmdNode;  	    /* Node for replacing the command */
600     char     	  *cmd = (char *) cmdp;
601     Job           *job = (Job *) jobp;
602     char	*cp;
603 
604     noSpecials = NoExecute(job->node);
605 
606     if (strcmp(cmd, "...") == 0) {
607 	job->node->type |= OP_SAVE_CMDS;
608 	if ((job->flags & JOB_IGNDOTS) == 0) {
609 	    job->tailCmds = Lst_Succ(Lst_Member(job->node->commands,
610 						(ClientData)cmd));
611 	    return 1;
612 	}
613 	return 0;
614     }
615 
616 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) {	\
617 	(void) fprintf(stdout, fmt, arg); 	\
618 	(void) fflush(stdout); 			\
619     }						\
620    (void) fprintf(job->cmdFILE, fmt, arg);	\
621    (void) fflush(job->cmdFILE);
622 
623     numCommands += 1;
624 
625     /*
626      * For debugging, we replace each command with the result of expanding
627      * the variables in the command.
628      */
629     cmdNode = Lst_Member(job->node->commands, (ClientData)cmd);
630     cmdStart = cmd = Var_Subst(NULL, cmd, job->node, FALSE);
631     Lst_Replace(cmdNode, (ClientData)cmdStart);
632 
633     cmdTemplate = "%s\n";
634 
635     /*
636      * Check for leading @' and -'s to control echoing and error checking.
637      */
638     while (*cmd == '@' || *cmd == '-') {
639 	if (*cmd == '@') {
640 	    shutUp = TRUE;
641 	} else {
642 	    errOff = TRUE;
643 	}
644 	cmd++;
645     }
646 
647     while (isspace((unsigned char) *cmd))
648 	cmd++;
649 
650     if (shutUp) {
651 	if (!(job->flags & JOB_SILENT) && !noSpecials &&
652 	    commandShell->hasEchoCtl) {
653 		DBPRINTF("%s\n", commandShell->echoOff);
654 	} else {
655 	    shutUp = FALSE;
656 	}
657     }
658 
659     if (errOff) {
660 	if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
661 	    if (commandShell->hasErrCtl) {
662 		/*
663 		 * we don't want the error-control commands showing
664 		 * up either, so we turn off echoing while executing
665 		 * them. We could put another field in the shell
666 		 * structure to tell JobDoOutput to look for this
667 		 * string too, but why make it any more complex than
668 		 * it already is?
669 		 */
670 		if (!(job->flags & JOB_SILENT) && !shutUp &&
671 		    commandShell->hasEchoCtl) {
672 			DBPRINTF("%s\n", commandShell->echoOff);
673 			DBPRINTF("%s\n", commandShell->ignErr);
674 			DBPRINTF("%s\n", commandShell->echoOn);
675 		} else {
676 		    DBPRINTF("%s\n", commandShell->ignErr);
677 		}
678 	    } else if (commandShell->ignErr &&
679 		      (*commandShell->ignErr != '\0'))
680 	    {
681 		/*
682 		 * The shell has no error control, so we need to be
683 		 * weird to get it to ignore any errors from the command.
684 		 * If echoing is turned on, we turn it off and use the
685 		 * errCheck template to echo the command. Leave echoing
686 		 * off so the user doesn't see the weirdness we go through
687 		 * to ignore errors. Set cmdTemplate to use the weirdness
688 		 * instead of the simple "%s\n" template.
689 		 */
690 		if (!(job->flags & JOB_SILENT) && !shutUp &&
691 		    commandShell->hasEchoCtl) {
692 			DBPRINTF("%s\n", commandShell->echoOff);
693 			DBPRINTF(commandShell->errCheck, cmd);
694 			shutUp = TRUE;
695 		}
696 		cmdTemplate = commandShell->ignErr;
697 		/*
698 		 * The error ignoration (hee hee) is already taken care
699 		 * of by the ignErr template, so pretend error checking
700 		 * is still on.
701 		 */
702 		errOff = FALSE;
703 	    } else {
704 		errOff = FALSE;
705 	    }
706 	} else {
707 	    errOff = FALSE;
708 	}
709     }
710 
711     if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
712 	(job->flags & JOB_TRACED) == 0) {
713 	    DBPRINTF("set -%s\n", "x");
714 	    job->flags |= JOB_TRACED;
715     }
716 
717     if ((cp = Check_Cwd_Cmd(cmd)) != NULL) {
718 	    DBPRINTF("test -d %s && ", cp);
719 	    DBPRINTF("cd %s; ", cp);
720     }
721     DBPRINTF(cmdTemplate, cmd);
722     free(cmdStart);
723 
724     if (errOff) {
725 	/*
726 	 * If echoing is already off, there's no point in issuing the
727 	 * echoOff command. Otherwise we issue it and pretend it was on
728 	 * for the whole command...
729 	 */
730 	if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
731 	    DBPRINTF("%s\n", commandShell->echoOff);
732 	    shutUp = TRUE;
733 	}
734 	DBPRINTF("%s\n", commandShell->errCheck);
735     }
736     if (shutUp) {
737 	DBPRINTF("%s\n", commandShell->echoOn);
738     }
739     return 0;
740 }
741 
742 /*-
743  *-----------------------------------------------------------------------
744  * JobSaveCommand --
745  *	Save a command to be executed when everything else is done.
746  *	Callback function for JobFinish...
747  *
748  * Results:
749  *	Always returns 0
750  *
751  * Side Effects:
752  *	The command is tacked onto the end of postCommands's commands list.
753  *
754  *-----------------------------------------------------------------------
755  */
756 static int
757 JobSaveCommand(cmd, gn)
758     ClientData   cmd;
759     ClientData   gn;
760 {
761     cmd = (ClientData) Var_Subst(NULL, (char *) cmd, (GNode *) gn, FALSE);
762     (void) Lst_AtEnd(postCommands->commands, cmd);
763     return(0);
764 }
765 
766 
767 /*-
768  *-----------------------------------------------------------------------
769  * JobClose --
770  *	Called to close both input and output pipes when a job is finished.
771  *
772  * Results:
773  *	Nada
774  *
775  * Side Effects:
776  *	The file descriptors associated with the job are closed.
777  *
778  *-----------------------------------------------------------------------
779  */
780 static void
781 JobClose(job)
782     Job *job;
783 {
784     if (usePipes && (job->flags & JOB_FIRST)) {
785 #ifdef RMT_WILL_WATCH
786 	Rmt_Ignore(job->inPipe);
787 #else
788 #ifdef USE_SELECT
789 	FD_CLR(job->inPipe, &outputs);
790 #else
791 	clearfd(job);
792 #endif
793 #endif
794 	if (job->outPipe != job->inPipe) {
795 	   (void) close(job->outPipe);
796 	}
797 	JobDoOutput(job, TRUE);
798 	(void) close(job->inPipe);
799     } else {
800 	(void) close(job->outFd);
801 	JobDoOutput(job, TRUE);
802     }
803 }
804 
805 /*-
806  *-----------------------------------------------------------------------
807  * JobFinish  --
808  *	Do final processing for the given job including updating
809  *	parents and starting new jobs as available/necessary. Note
810  *	that we pay no attention to the JOB_IGNERR flag here.
811  *	This is because when we're called because of a noexecute flag
812  *	or something, jstat.w_status is 0 and when called from
813  *	Job_CatchChildren, the status is zeroed if it s/b ignored.
814  *
815  * Results:
816  *	None
817  *
818  * Side Effects:
819  *	Some nodes may be put on the toBeMade queue.
820  *	Final commands for the job are placed on postCommands.
821  *
822  *	If we got an error and are aborting (aborting == ABORT_ERROR) and
823  *	the job list is now empty, we are done for the day.
824  *	If we recognized an error (errors !=0), we set the aborting flag
825  *	to ABORT_ERROR so no more jobs will be started.
826  *-----------------------------------------------------------------------
827  */
828 /*ARGSUSED*/
829 static void
830 JobFinish(job, status)
831     Job         *job;	      	  /* job to finish */
832     int	  	*status;     	  /* sub-why job went away */
833 {
834     Boolean 	 done;
835 
836     if ((WIFEXITED(*status) &&
837 	 (((WEXITSTATUS(*status) != 0) && !(job->flags & JOB_IGNERR)))) ||
838 	WIFSIGNALED(*status))
839     {
840 	/*
841 	 * If it exited non-zero and either we're doing things our
842 	 * way or we're not ignoring errors, the job is finished.
843 	 * Similarly, if the shell died because of a signal
844 	 * the job is also finished. In these
845 	 * cases, finish out the job's output before printing the exit
846 	 * status...
847 	 */
848 #ifdef REMOTE
849 	KILL(job->pid, SIGCONT);
850 #endif
851 	JobClose(job);
852 	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
853 	   (void) fclose(job->cmdFILE);
854 	   job->cmdFILE = NULL;
855 	}
856 	done = TRUE;
857 #ifdef REMOTE
858 	if (job->flags & JOB_REMOTE)
859 	    Rmt_Done(job->rmtID, job->node);
860 #endif
861     } else if (WIFEXITED(*status)) {
862 	/*
863 	 * Deal with ignored errors in -B mode. We need to print a message
864 	 * telling of the ignored error as well as setting status.w_status
865 	 * to 0 so the next command gets run. To do this, we set done to be
866 	 * TRUE if in -B mode and the job exited non-zero.
867 	 */
868 	done = WEXITSTATUS(*status) != 0;
869 	/*
870 	 * Old comment said: "Note we don't
871 	 * want to close down any of the streams until we know we're at the
872 	 * end."
873 	 * But we do. Otherwise when are we going to print the rest of the
874 	 * stuff?
875 	 */
876 	JobClose(job);
877 #ifdef REMOTE
878 	if (job->flags & JOB_REMOTE)
879 	    Rmt_Done(job->rmtID, job->node);
880 #endif /* REMOTE */
881     } else {
882 	/*
883 	 * No need to close things down or anything.
884 	 */
885 	done = FALSE;
886     }
887 
888     if (done ||
889 	WIFSTOPPED(*status) ||
890 	(WIFSIGNALED(*status) && (WTERMSIG(*status) == SIGCONT)))
891     {
892 	FILE	  *out;
893 
894 	if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
895 	    /*
896 	     * If output is going to a file and this job is ignoring
897 	     * errors, arrange to have the exit status sent to the
898 	     * output file as well.
899 	     */
900 	    out = fdopen(job->outFd, "w");
901 	    if (out == NULL)
902 		Punt("Cannot fdopen");
903 	} else {
904 	    out = stdout;
905 	}
906 
907 	if (WIFEXITED(*status)) {
908 	    if (DEBUG(JOB)) {
909 		(void) fprintf(stdout, "Process %d exited.\n", job->pid);
910 		(void) fflush(stdout);
911 	    }
912 	    if (WEXITSTATUS(*status) != 0) {
913 		if (usePipes && job->node != lastNode) {
914 		    MESSAGE(out, job->node);
915 		    lastNode = job->node;
916 		}
917 		(void) fprintf(out, "*** Error code %d%s\n",
918 			       WEXITSTATUS(*status),
919 			       (job->flags & JOB_IGNERR) ? "(ignored)" : "");
920 
921 		if (job->flags & JOB_IGNERR) {
922 		    *status = 0;
923 		}
924 	    } else if (DEBUG(JOB)) {
925 		if (usePipes && job->node != lastNode) {
926 		    MESSAGE(out, job->node);
927 		    lastNode = job->node;
928 		}
929 		(void) fprintf(out, "*** Completed successfully\n");
930 	    }
931 	} else if (WIFSTOPPED(*status) && WSTOPSIG(*status) != SIGCONT) {
932 	    if (DEBUG(JOB)) {
933 		(void) fprintf(stdout, "Process %d stopped.\n", job->pid);
934 		(void) fflush(stdout);
935 	    }
936 	    if (usePipes && job->node != lastNode) {
937 		MESSAGE(out, job->node);
938 		lastNode = job->node;
939 	    }
940 	    if (!(job->flags & JOB_REMIGRATE)) {
941 		switch (WSTOPSIG(*status)) {
942 		case SIGTSTP:
943 		    (void) fprintf(out, "*** Suspended\n");
944 		    break;
945 		case SIGSTOP:
946 		    (void) fprintf(out, "*** Stopped\n");
947 		    break;
948 		default:
949 		    (void) fprintf(out, "*** Stopped -- signal %d\n",
950 			WSTOPSIG(*status));
951 		}
952 	    }
953 	    job->flags |= JOB_RESUME;
954 	    (void)Lst_AtEnd(stoppedJobs, (ClientData)job);
955 #ifdef REMOTE
956 	    if (job->flags & JOB_REMIGRATE)
957 		JobRestart(job);
958 #endif
959 	    (void) fflush(out);
960 	    return;
961 	} else if (WIFSTOPPED(*status) &&  WSTOPSIG(*status) == SIGCONT) {
962 	    /*
963 	     * If the beastie has continued, shift the Job from the stopped
964 	     * list to the running one (or re-stop it if concurrency is
965 	     * exceeded) and go and get another child.
966 	     */
967 	    if (job->flags & (JOB_RESUME|JOB_REMIGRATE|JOB_RESTART)) {
968 		if (usePipes && job->node != lastNode) {
969 		    MESSAGE(out, job->node);
970 		    lastNode = job->node;
971 		}
972 		(void) fprintf(out, "*** Continued\n");
973 	    }
974 	    if (!(job->flags & JOB_CONTINUING)) {
975 		if (DEBUG(JOB)) {
976 		    (void) fprintf(stdout,
977 				   "Warning: process %d was not continuing.\n",
978 				   job->pid);
979 		    (void) fflush(stdout);
980 		}
981 #ifdef notdef
982 		/*
983 		 * We don't really want to restart a job from scratch just
984 		 * because it continued, especially not without killing the
985 		 * continuing process!  That's why this is ifdef'ed out.
986 		 * FD - 9/17/90
987 		 */
988 		JobRestart(job);
989 #endif
990 	    }
991 	    job->flags &= ~JOB_CONTINUING;
992  	    Lst_AtEnd(jobs, (ClientData)job);
993 	    nJobs += 1;
994 	    if (!(job->flags & JOB_REMOTE)) {
995 		if (DEBUG(JOB)) {
996 		    (void) fprintf(stdout,
997 				   "Process %d is continuing locally.\n",
998 				   job->pid);
999 		    (void) fflush(stdout);
1000   		}
1001 		nLocal += 1;
1002 	    }
1003 	    (void) fflush(out);
1004   	    return;
1005 	} else {
1006 	    if (usePipes && job->node != lastNode) {
1007 		MESSAGE(out, job->node);
1008 		lastNode = job->node;
1009 	    }
1010 	    (void) fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
1011 	}
1012 
1013 	(void) fflush(out);
1014     }
1015 
1016     /*
1017      * Now handle the -B-mode stuff. If the beast still isn't finished,
1018      * try and restart the job on the next command. If JobStart says it's
1019      * ok, it's ok. If there's an error, this puppy is done.
1020      */
1021     if (compatMake && (WIFEXITED(*status) &&
1022 	!Lst_IsAtEnd(job->node->commands))) {
1023 	switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1024 	case JOB_RUNNING:
1025 	    done = FALSE;
1026 	    break;
1027 	case JOB_ERROR:
1028 	    done = TRUE;
1029 	    *status = W_EXITCODE(1, 0);
1030 	    break;
1031 	case JOB_FINISHED:
1032 	    /*
1033 	     * If we got back a JOB_FINISHED code, JobStart has already
1034 	     * called Make_Update and freed the job descriptor. We set
1035 	     * done to false here to avoid fake cycles and double frees.
1036 	     * JobStart needs to do the update so we can proceed up the
1037 	     * graph when given the -n flag..
1038 	     */
1039 	    done = FALSE;
1040 	    break;
1041 	}
1042     } else {
1043 	done = TRUE;
1044     }
1045 
1046     if (done) {
1047 	Trace_Log(JOBEND, job);
1048 	if (!compatMake && !(job->flags & JOB_SPECIAL)) {
1049 	    if ((*status != 0) ||
1050 	        (aborting == ABORT_ERROR) ||
1051 	        (aborting == ABORT_INTERRUPT))
1052 		Job_TokenReturn();
1053 	}
1054 
1055     }
1056 
1057     if (done &&
1058 	(aborting != ABORT_ERROR) &&
1059 	(aborting != ABORT_INTERRUPT) &&
1060 	(*status == 0))
1061     {
1062 	/*
1063 	 * As long as we aren't aborting and the job didn't return a non-zero
1064 	 * status that we shouldn't ignore, we call Make_Update to update
1065 	 * the parents. In addition, any saved commands for the node are placed
1066 	 * on the .END target.
1067 	 */
1068 	if (job->tailCmds != NILLNODE) {
1069 	    Lst_ForEachFrom(job->node->commands, job->tailCmds,
1070 			     JobSaveCommand,
1071 			    (ClientData)job->node);
1072 	}
1073 	job->node->made = MADE;
1074 	if (!(job->flags & JOB_SPECIAL))
1075 	    Job_TokenReturn();
1076 	Make_Update(job->node);
1077 	free((Address)job);
1078     } else if (*status != 0) {
1079 	errors += 1;
1080 	free((Address)job);
1081     }
1082     JobRestartJobs();
1083 
1084     /*
1085      * Set aborting if any error.
1086      */
1087     if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
1088 	/*
1089 	 * If we found any errors in this batch of children and the -k flag
1090 	 * wasn't given, we set the aborting flag so no more jobs get
1091 	 * started.
1092 	 */
1093 	aborting = ABORT_ERROR;
1094     }
1095 
1096     if ((aborting == ABORT_ERROR) && Job_Empty()) {
1097 	/*
1098 	 * If we are aborting and the job table is now empty, we finish.
1099 	 */
1100 	Finish(errors);
1101     }
1102 }
1103 
1104 /*-
1105  *-----------------------------------------------------------------------
1106  * Job_Touch --
1107  *	Touch the given target. Called by JobStart when the -t flag was
1108  *	given
1109  *
1110  * Results:
1111  *	None
1112  *
1113  * Side Effects:
1114  *	The data modification of the file is changed. In addition, if the
1115  *	file did not exist, it is created.
1116  *-----------------------------------------------------------------------
1117  */
1118 void
1119 Job_Touch(gn, silent)
1120     GNode         *gn;	      	/* the node of the file to touch */
1121     Boolean 	  silent;   	/* TRUE if should not print messages */
1122 {
1123     int		  streamID;   	/* ID of stream opened to do the touch */
1124     struct utimbuf times;	/* Times for utime() call */
1125 
1126     if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|OP_PHONY)) {
1127 	/*
1128 	 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1129 	 * and, as such, shouldn't really be created.
1130 	 */
1131 	return;
1132     }
1133 
1134     if (!silent || NoExecute(gn)) {
1135 	(void) fprintf(stdout, "touch %s\n", gn->name);
1136 	(void) fflush(stdout);
1137     }
1138 
1139     if (NoExecute(gn)) {
1140 	return;
1141     }
1142 
1143     if (gn->type & OP_ARCHV) {
1144 	Arch_Touch(gn);
1145     } else if (gn->type & OP_LIB) {
1146 	Arch_TouchLib(gn);
1147     } else {
1148 	char	*file = gn->path ? gn->path : gn->name;
1149 
1150 	times.actime = times.modtime = now;
1151 	if (utime(file, &times) < 0){
1152 	    streamID = open(file, O_RDWR | O_CREAT, 0666);
1153 
1154 	    if (streamID >= 0) {
1155 		char	c;
1156 
1157 		/*
1158 		 * Read and write a byte to the file to change the
1159 		 * modification time, then close the file.
1160 		 */
1161 		if (read(streamID, &c, 1) == 1) {
1162 		    (void) lseek(streamID, (off_t)0, SEEK_SET);
1163 		    (void) write(streamID, &c, 1);
1164 		}
1165 
1166 		(void) close(streamID);
1167 	    } else {
1168 		(void) fprintf(stdout, "*** couldn't touch %s: %s",
1169 			       file, strerror(errno));
1170 		(void) fflush(stdout);
1171 	    }
1172 	}
1173     }
1174 }
1175 
1176 /*-
1177  *-----------------------------------------------------------------------
1178  * Job_CheckCommands --
1179  *	Make sure the given node has all the commands it needs.
1180  *
1181  * Results:
1182  *	TRUE if the commands list is/was ok.
1183  *
1184  * Side Effects:
1185  *	The node will have commands from the .DEFAULT rule added to it
1186  *	if it needs them.
1187  *-----------------------------------------------------------------------
1188  */
1189 Boolean
1190 Job_CheckCommands(gn, abortProc)
1191     GNode          *gn;	    	    /* The target whose commands need
1192 				     * verifying */
1193     void    	 (*abortProc) __P((char *, ...));
1194 			/* Function to abort with message */
1195 {
1196     if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1197 	(gn->type & OP_LIB) == 0) {
1198 	/*
1199 	 * No commands. Look for .DEFAULT rule from which we might infer
1200 	 * commands
1201 	 */
1202 	if ((DEFAULT != NILGNODE) && !Lst_IsEmpty(DEFAULT->commands)) {
1203 	    char *p1;
1204 	    /*
1205 	     * Make only looks for a .DEFAULT if the node was never the
1206 	     * target of an operator, so that's what we do too. If
1207 	     * a .DEFAULT was given, we substitute its commands for gn's
1208 	     * commands and set the IMPSRC variable to be the target's name
1209 	     * The DEFAULT node acts like a transformation rule, in that
1210 	     * gn also inherits any attributes or sources attached to
1211 	     * .DEFAULT itself.
1212 	     */
1213 	    Make_HandleUse(DEFAULT, gn);
1214 	    Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn, 0);
1215 	    if (p1)
1216 		free(p1);
1217 	} else if (Dir_MTime(gn) == 0) {
1218 	    /*
1219 	     * The node wasn't the target of an operator we have no .DEFAULT
1220 	     * rule to go on and the target doesn't already exist. There's
1221 	     * nothing more we can do for this branch. If the -k flag wasn't
1222 	     * given, we stop in our tracks, otherwise we just don't update
1223 	     * this node's parents so they never get examined.
1224 	     */
1225 	    static const char msg[] = ": don't know how to make";
1226 
1227 	    if (gn->type & OP_OPTIONAL) {
1228 		(void) fprintf(stdout, "%s%s %s(ignored)\n", progname,
1229 		    msg, gn->name);
1230 		(void) fflush(stdout);
1231 	    } else if (keepgoing) {
1232 		(void) fprintf(stdout, "%s%s %s(continuing)\n", progname,
1233 		    msg, gn->name);
1234 		(void) fflush(stdout);
1235   		return FALSE;
1236 	    } else {
1237 		(*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
1238 		return FALSE;
1239 	    }
1240 	}
1241     }
1242     return TRUE;
1243 }
1244 #ifdef RMT_WILL_WATCH
1245 /*-
1246  *-----------------------------------------------------------------------
1247  * JobLocalInput --
1248  *	Handle a pipe becoming readable. Callback function for Rmt_Watch
1249  *
1250  * Results:
1251  *	None
1252  *
1253  * Side Effects:
1254  *	JobDoOutput is called.
1255  *
1256  *-----------------------------------------------------------------------
1257  */
1258 /*ARGSUSED*/
1259 static void
1260 JobLocalInput(stream, job)
1261     int	    stream; 	/* Stream that's ready (ignored) */
1262     Job	    *job;   	/* Job to which the stream belongs */
1263 {
1264     JobDoOutput(job, FALSE);
1265 }
1266 #endif /* RMT_WILL_WATCH */
1267 
1268 /*-
1269  *-----------------------------------------------------------------------
1270  * JobExec --
1271  *	Execute the shell for the given job. Called from JobStart and
1272  *	JobRestart.
1273  *
1274  * Results:
1275  *	None.
1276  *
1277  * Side Effects:
1278  *	A shell is executed, outputs is altered and the Job structure added
1279  *	to the job table.
1280  *
1281  *-----------------------------------------------------------------------
1282  */
1283 static void
1284 JobExec(job, argv)
1285     Job	    	  *job; 	/* Job to execute */
1286     char    	  **argv;
1287 {
1288     int	    	  cpid;	    	/* ID of new child */
1289 
1290     job->flags &= ~JOB_TRACED;
1291 
1292     if (DEBUG(JOB)) {
1293 	int 	  i;
1294 
1295 	(void) fprintf(stdout, "Running %s %sly\n", job->node->name,
1296 		       job->flags&JOB_REMOTE?"remote":"local");
1297 	(void) fprintf(stdout, "\tCommand: ");
1298 	for (i = 0; argv[i] != NULL; i++) {
1299 	    (void) fprintf(stdout, "%s ", argv[i]);
1300 	}
1301  	(void) fprintf(stdout, "\n");
1302  	(void) fflush(stdout);
1303     }
1304 
1305     /*
1306      * Some jobs produce no output and it's disconcerting to have
1307      * no feedback of their running (since they produce no output, the
1308      * banner with their name in it never appears). This is an attempt to
1309      * provide that feedback, even if nothing follows it.
1310      */
1311     if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1312 	!(job->flags & JOB_SILENT)) {
1313 	MESSAGE(stdout, job->node);
1314 	lastNode = job->node;
1315     }
1316 
1317 #ifdef RMT_NO_EXEC
1318     if (job->flags & JOB_REMOTE) {
1319 	goto jobExecFinish;
1320     }
1321 #endif /* RMT_NO_EXEC */
1322 
1323     if ((cpid = vfork()) == -1) {
1324 	Punt("Cannot vfork: %s", strerror(errno));
1325     } else if (cpid == 0) {
1326 
1327 	/*
1328 	 * Must duplicate the input stream down to the child's input and
1329 	 * reset it to the beginning (again). Since the stream was marked
1330 	 * close-on-exec, we must clear that bit in the new input.
1331 	 */
1332 	if (dup2(FILENO(job->cmdFILE), 0) == -1)
1333 	    Punt("Cannot dup2: %s", strerror(errno));
1334 	(void) fcntl(0, F_SETFD, 0);
1335 	(void) lseek(0, (off_t)0, SEEK_SET);
1336 
1337 	if (job->node->type & OP_MAKE) {
1338 		/*
1339 		 * Pass job token pipe to submakes.
1340 		 */
1341 		fcntl(job_pipe[0], F_SETFD, 0);
1342 		fcntl(job_pipe[1], F_SETFD, 0);
1343 	}
1344 
1345 	if (usePipes) {
1346 	    /*
1347 	     * Set up the child's output to be routed through the pipe
1348 	     * we've created for it.
1349 	     */
1350 	    if (dup2(job->outPipe, 1) == -1)
1351 		Punt("Cannot dup2: %s", strerror(errno));
1352 	} else {
1353 	    /*
1354 	     * We're capturing output in a file, so we duplicate the
1355 	     * descriptor to the temporary file into the standard
1356 	     * output.
1357 	     */
1358 	    if (dup2(job->outFd, 1) == -1)
1359 		Punt("Cannot dup2: %s", strerror(errno));
1360 	}
1361 	/*
1362 	 * The output channels are marked close on exec. This bit was
1363 	 * duplicated by the dup2 (on some systems), so we have to clear
1364 	 * it before routing the shell's error output to the same place as
1365 	 * its standard output.
1366 	 */
1367 	(void) fcntl(1, F_SETFD, 0);
1368 	if (dup2(1, 2) == -1)
1369 	    Punt("Cannot dup2: %s", strerror(errno));
1370 
1371 #ifdef USE_PGRP
1372 	/*
1373 	 * We want to switch the child into a different process family so
1374 	 * we can kill it and all its descendants in one fell swoop,
1375 	 * by killing its process family, but not commit suicide.
1376 	 */
1377 # if defined(SYSV)
1378 	(void) setsid();
1379 # else
1380 	(void) setpgid(0, getpid());
1381 # endif
1382 #endif /* USE_PGRP */
1383 
1384 #ifdef REMOTE
1385 	if (job->flags & JOB_REMOTE) {
1386 	    Rmt_Exec(shellPath, argv, FALSE);
1387 	} else
1388 #endif /* REMOTE */
1389 	{
1390 	   (void) execv(shellPath, argv);
1391 	   execError(shellPath);
1392 	}
1393 	_exit(1);
1394     } else {
1395 #ifdef REMOTE
1396 	sigset_t nmask, omask;
1397 	sigemptyset(&nmask);
1398 	sigaddset(&nmask, SIGCHLD);
1399 	sigprocmask(SIG_BLOCK, &nmask, &omask);
1400 #endif
1401 	job->pid = cpid;
1402 
1403 	Trace_Log(JOBSTART, job);
1404 
1405 	if (usePipes && (job->flags & JOB_FIRST)) {
1406 	    /*
1407 	     * The first time a job is run for a node, we set the current
1408 	     * position in the buffer to the beginning and mark another
1409 	     * stream to watch in the outputs mask
1410 	     */
1411 	    job->curPos = 0;
1412 
1413 #ifdef RMT_WILL_WATCH
1414 	    Rmt_Watch(job->inPipe, JobLocalInput, job);
1415 #else
1416 #ifdef USE_SELECT
1417 	    FD_SET(job->inPipe, &outputs);
1418 #else
1419 	    watchfd(job);
1420 #endif
1421 #endif /* RMT_WILL_WATCH */
1422 	}
1423 
1424 	if (job->flags & JOB_REMOTE) {
1425 #ifndef REMOTE
1426 	    job->rmtID = 0;
1427 #else
1428 	    job->rmtID = Rmt_LastID(job->pid);
1429 #endif /* REMOTE */
1430 	} else {
1431 	    nLocal += 1;
1432 	    /*
1433 	     * XXX: Used to not happen if REMOTE. Why?
1434 	     */
1435 	    if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1436 		(void) fclose(job->cmdFILE);
1437 		job->cmdFILE = NULL;
1438 	    }
1439 	}
1440 #ifdef REMOTE
1441 	sigprocmask(SIG_SETMASK, &omask, NULL);
1442 #endif
1443     }
1444 
1445 #ifdef RMT_NO_EXEC
1446 jobExecFinish:
1447 #endif
1448     /*
1449      * Now the job is actually running, add it to the table.
1450      */
1451     nJobs += 1;
1452     (void) Lst_AtEnd(jobs, (ClientData)job);
1453 }
1454 
1455 /*-
1456  *-----------------------------------------------------------------------
1457  * JobMakeArgv --
1458  *	Create the argv needed to execute the shell for a given job.
1459  *
1460  *
1461  * Results:
1462  *
1463  * Side Effects:
1464  *
1465  *-----------------------------------------------------------------------
1466  */
1467 static void
1468 JobMakeArgv(job, argv)
1469     Job	    	  *job;
1470     char	  **argv;
1471 {
1472     int	    	  argc;
1473     static char	  args[10]; 	/* For merged arguments */
1474 
1475     argv[0] = shellName;
1476     argc = 1;
1477 
1478     if ((commandShell->exit && (*commandShell->exit != '-')) ||
1479 	(commandShell->echo && (*commandShell->echo != '-')))
1480     {
1481 	/*
1482 	 * At least one of the flags doesn't have a minus before it, so
1483 	 * merge them together. Have to do this because the *(&(@*#*&#$#
1484 	 * Bourne shell thinks its second argument is a file to source.
1485 	 * Grrrr. Note the ten-character limitation on the combined arguments.
1486 	 */
1487 	(void)snprintf(args, sizeof(args), "-%s%s",
1488 		      ((job->flags & JOB_IGNERR) ? "" :
1489 		       (commandShell->exit ? commandShell->exit : "")),
1490 		      ((job->flags & JOB_SILENT) ? "" :
1491 		       (commandShell->echo ? commandShell->echo : "")));
1492 
1493 	if (args[1]) {
1494 	    argv[argc] = args;
1495 	    argc++;
1496 	}
1497     } else {
1498 	if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1499 	    argv[argc] = commandShell->exit;
1500 	    argc++;
1501 	}
1502 	if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1503 	    argv[argc] = commandShell->echo;
1504 	    argc++;
1505 	}
1506     }
1507     argv[argc] = NULL;
1508 }
1509 
1510 /*-
1511  *-----------------------------------------------------------------------
1512  * JobRestart --
1513  *	Restart a job that stopped for some reason.
1514  *
1515  * Results:
1516  *	None.
1517  *
1518  *-----------------------------------------------------------------------
1519  */
1520 static void
1521 JobRestart(job)
1522     Job 	  *job;    	/* Job to restart */
1523 {
1524 #ifdef REMOTE
1525     int host;
1526 #endif
1527 
1528     if (job->flags & JOB_REMIGRATE) {
1529 	if (
1530 #ifdef REMOTE
1531 	    verboseRemigrates ||
1532 #endif
1533 	    DEBUG(JOB)) {
1534 	   (void) fprintf(stdout, "*** remigrating %x(%s)\n",
1535 			   job->pid, job->node->name);
1536 	   (void) fflush(stdout);
1537 	}
1538 
1539 #ifdef REMOTE
1540 	if (!Rmt_ReExport(job->pid, job->node, &host)) {
1541 	    if (verboseRemigrates || DEBUG(JOB)) {
1542 		(void) fprintf(stdout, "*** couldn't migrate...\n");
1543 		(void) fflush(stdout);
1544 	    }
1545 #endif
1546 	    if (nLocal != maxLocal) {
1547 		/*
1548 		 * Job cannot be remigrated, but there's room on the local
1549 		 * machine, so resume the job and note that another
1550 		 * local job has started.
1551 		 */
1552 		if (
1553 #ifdef REMOTE
1554 		    verboseRemigrates ||
1555 #endif
1556 		    DEBUG(JOB)) {
1557 		    (void) fprintf(stdout, "*** resuming on local machine\n");
1558 		    (void) fflush(stdout);
1559 		}
1560 		KILL(job->pid, SIGCONT);
1561 		nLocal +=1;
1562 #ifdef REMOTE
1563 		job->flags &= ~(JOB_REMIGRATE|JOB_RESUME|JOB_REMOTE);
1564 		job->flags |= JOB_CONTINUING;
1565 #else
1566 		job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1567 #endif
1568 	} else {
1569 		/*
1570 		 * Job cannot be restarted. Mark the table as full and
1571 		 * place the job back on the list of stopped jobs.
1572 		 */
1573 		if (
1574 #ifdef REMOTE
1575 		    verboseRemigrates ||
1576 #endif
1577 		    DEBUG(JOB)) {
1578 		   (void) fprintf(stdout, "*** holding\n");
1579 		   (void) fflush(stdout);
1580   		}
1581 		(void)Lst_AtFront(stoppedJobs, (ClientData)job);
1582 		return;
1583 	    }
1584 #ifdef REMOTE
1585 	} else {
1586 	    /*
1587 	     * Clear out the remigrate and resume flags. Set the continuing
1588 	     * flag so we know later on that the process isn't exiting just
1589 	     * because of a signal.
1590 	     */
1591 	    job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1592 	    job->flags |= JOB_CONTINUING;
1593 	    job->rmtID = host;
1594 	}
1595 #endif
1596 
1597 	(void)Lst_AtEnd(jobs, (ClientData)job);
1598 	nJobs += 1;
1599     } else if (job->flags & JOB_RESTART) {
1600 	/*
1601 	 * Set up the control arguments to the shell. This is based on the
1602 	 * flags set earlier for this job. If the JOB_IGNERR flag is clear,
1603 	 * the 'exit' flag of the commandShell is used to cause it to exit
1604 	 * upon receiving an error. If the JOB_SILENT flag is clear, the
1605 	 * 'echo' flag of the commandShell is used to get it to start echoing
1606 	 * as soon as it starts processing commands.
1607 	 */
1608 	char	  *argv[10];
1609 
1610 	JobMakeArgv(job, argv);
1611 
1612 	if (DEBUG(JOB)) {
1613 	    (void) fprintf(stdout, "Restarting %s...", job->node->name);
1614 	    (void) fflush(stdout);
1615 	}
1616 #ifdef REMOTE
1617 	if ((job->node->type&OP_NOEXPORT) ||
1618  	    (nLocal < maxLocal && runLocalFirst)
1619 # ifdef RMT_NO_EXEC
1620 	    || !Rmt_Export(shellPath, argv, job)
1621 # else
1622 	    || !Rmt_Begin(shellPath, argv, job->node)
1623 # endif
1624 #endif
1625 	{
1626 	    if (((nLocal >= maxLocal) && !(job->flags & JOB_SPECIAL))) {
1627 		/*
1628 		 * Can't be exported and not allowed to run locally -- put it
1629 		 * back on the hold queue and mark the table full
1630 		 */
1631 		if (DEBUG(JOB)) {
1632 		    (void) fprintf(stdout, "holding\n");
1633 		    (void) fflush(stdout);
1634 		}
1635 		(void)Lst_AtFront(stoppedJobs, (ClientData)job);
1636 		return;
1637 	    } else {
1638 		/*
1639 		 * Job may be run locally.
1640 		 */
1641 		if (DEBUG(JOB)) {
1642 		    (void) fprintf(stdout, "running locally\n");
1643 		    (void) fflush(stdout);
1644 		}
1645 		job->flags &= ~JOB_REMOTE;
1646 	    }
1647 	}
1648 #ifdef REMOTE
1649 	else {
1650 	    /*
1651 	     * Can be exported. Hooray!
1652 	     */
1653 	    if (DEBUG(JOB)) {
1654 		(void) fprintf(stdout, "exporting\n");
1655 		(void) fflush(stdout);
1656 	    }
1657 	    job->flags |= JOB_REMOTE;
1658 	}
1659 #endif
1660 	JobExec(job, argv);
1661     } else {
1662 	/*
1663 	 * The job has stopped and needs to be restarted. Why it stopped,
1664 	 * we don't know...
1665 	 */
1666 	if (DEBUG(JOB)) {
1667 	   (void) fprintf(stdout, "Resuming %s...", job->node->name);
1668 	   (void) fflush(stdout);
1669 	}
1670 	if (((job->flags & JOB_REMOTE) ||
1671 	    (nLocal < maxLocal) ||
1672 #ifdef REMOTE
1673 	    (((job->flags & JOB_SPECIAL) &&
1674 	      (job->node->type & OP_NOEXPORT)) &&
1675 	     (maxLocal == 0))) &&
1676 #else
1677 	    ((job->flags & JOB_SPECIAL) &&
1678 	     (maxLocal == 0))) &&
1679 #endif
1680 	   (nJobs != maxJobs))
1681 	{
1682 	    /*
1683 	     * If the job is remote, it's ok to resume it as long as the
1684 	     * maximum concurrency won't be exceeded. If it's local and
1685 	     * we haven't reached the local concurrency limit already (or the
1686 	     * job must be run locally and maxLocal is 0), it's also ok to
1687 	     * resume it.
1688 	     */
1689 	    Boolean error;
1690 	    int status;
1691 
1692 #ifdef RMT_WANTS_SIGNALS
1693 	    if (job->flags & JOB_REMOTE) {
1694 		error = !Rmt_Signal(job, SIGCONT);
1695 	    } else
1696 #endif	/* RMT_WANTS_SIGNALS */
1697 		error = (KILL(job->pid, SIGCONT) != 0);
1698 
1699 	    if (!error) {
1700 		/*
1701 		 * Make sure the user knows we've continued the beast and
1702 		 * actually put the thing in the job table.
1703 		 */
1704 		job->flags |= JOB_CONTINUING;
1705 		status = W_STOPCODE(SIGCONT);
1706 		JobFinish(job, &status);
1707 
1708 		job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1709 		if (DEBUG(JOB)) {
1710 		   (void) fprintf(stdout, "done\n");
1711 		   (void) fflush(stdout);
1712 		}
1713 	    } else {
1714 		Error("couldn't resume %s: %s",
1715 		    job->node->name, strerror(errno));
1716 		status = W_EXITCODE(1, 0);
1717 		JobFinish(job, &status);
1718 	    }
1719 	} else {
1720 	    /*
1721 	     * Job cannot be restarted. Mark the table as full and
1722 	     * place the job back on the list of stopped jobs.
1723 	     */
1724 	    if (DEBUG(JOB)) {
1725 		(void) fprintf(stdout, "table full\n");
1726 		(void) fflush(stdout);
1727 	    }
1728 	    (void) Lst_AtFront(stoppedJobs, (ClientData)job);
1729 	}
1730     }
1731 }
1732 
1733 /*-
1734  *-----------------------------------------------------------------------
1735  * JobStart  --
1736  *	Start a target-creation process going for the target described
1737  *	by the graph node gn.
1738  *
1739  * Results:
1740  *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
1741  *	if there isn't actually anything left to do for the job and
1742  *	JOB_RUNNING if the job has been started.
1743  *
1744  * Side Effects:
1745  *	A new Job node is created and added to the list of running
1746  *	jobs. PMake is forked and a child shell created.
1747  *-----------------------------------------------------------------------
1748  */
1749 static int
1750 JobStart(gn, flags, previous)
1751     GNode         *gn;	      /* target to create */
1752     int	  	   flags;      /* flags for the job to override normal ones.
1753 			       * e.g. JOB_SPECIAL or JOB_IGNDOTS */
1754     Job 	  *previous;  /* The previous Job structure for this node,
1755 			       * if any. */
1756 {
1757     register Job  *job;       /* new job descriptor */
1758     char	  *argv[10];  /* Argument vector to shell */
1759     Boolean	  cmdsOK;     /* true if the nodes commands were all right */
1760     Boolean 	  local;      /* Set true if the job was run locally */
1761     Boolean 	  noExec;     /* Set true if we decide not to run the job */
1762     int		  tfd;	      /* File descriptor to the temp file */
1763 
1764     if (previous != NULL) {
1765 	previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT|JOB_REMOTE);
1766 	job = previous;
1767     } else {
1768 	job = (Job *) emalloc(sizeof(Job));
1769 	if (job == NULL) {
1770 	    Punt("JobStart out of memory");
1771 	}
1772 	flags |= JOB_FIRST;
1773     }
1774 
1775     job->node = gn;
1776     job->tailCmds = NILLNODE;
1777 
1778     /*
1779      * Set the initial value of the flags for this job based on the global
1780      * ones and the node's attributes... Any flags supplied by the caller
1781      * are also added to the field.
1782      */
1783     job->flags = 0;
1784     if (Targ_Ignore(gn)) {
1785 	job->flags |= JOB_IGNERR;
1786     }
1787     if (Targ_Silent(gn)) {
1788 	job->flags |= JOB_SILENT;
1789     }
1790     job->flags |= flags;
1791 
1792     /*
1793      * Check the commands now so any attributes from .DEFAULT have a chance
1794      * to migrate to the node
1795      */
1796     if (!compatMake && job->flags & JOB_FIRST) {
1797 	cmdsOK = Job_CheckCommands(gn, Error);
1798     } else {
1799 	cmdsOK = TRUE;
1800     }
1801 
1802 #ifndef RMT_WILL_WATCH
1803 #ifndef USE_SELECT
1804     job->inPollfd = NULL;
1805 #endif
1806 #endif
1807     /*
1808      * If the -n flag wasn't given, we open up OUR (not the child's)
1809      * temporary file to stuff commands in it. The thing is rd/wr so we don't
1810      * need to reopen it to feed it to the shell. If the -n flag *was* given,
1811      * we just set the file to be stdout. Cute, huh?
1812      */
1813     if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1814 	(!noExecute && !touchFlag)) {
1815 	/*
1816 	 * tfile is the name of a file into which all shell commands are
1817 	 * put. It is used over by removing it before the child shell is
1818 	 * executed. The XXXXXX in the string are replaced by the pid of
1819 	 * the make process in a 6-character field with leading zeroes.
1820 	 */
1821 	char     tfile[sizeof(TMPPAT)];
1822 	/*
1823 	 * We're serious here, but if the commands were bogus, we're
1824 	 * also dead...
1825 	 */
1826 	if (!cmdsOK) {
1827 	    DieHorribly();
1828 	}
1829 
1830 	(void)strcpy(tfile, TMPPAT);
1831 	if ((tfd = mkstemp(tfile)) == -1)
1832 	    Punt("Could not create temporary file %s", strerror(errno));
1833 	(void) eunlink(tfile);
1834 
1835 	job->cmdFILE = fdopen(tfd, "w+");
1836 	if (job->cmdFILE == NULL) {
1837 	    Punt("Could not fdopen %s", tfile);
1838 	}
1839 	(void) fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1840 	/*
1841 	 * Send the commands to the command file, flush all its buffers then
1842 	 * rewind and remove the thing.
1843 	 */
1844 	noExec = FALSE;
1845 
1846 	/*
1847 	 * used to be backwards; replace when start doing multiple commands
1848 	 * per shell.
1849 	 */
1850 	if (compatMake) {
1851 	    /*
1852 	     * Be compatible: If this is the first time for this node,
1853 	     * verify its commands are ok and open the commands list for
1854 	     * sequential access by later invocations of JobStart.
1855 	     * Once that is done, we take the next command off the list
1856 	     * and print it to the command file. If the command was an
1857 	     * ellipsis, note that there's nothing more to execute.
1858 	     */
1859 	    if ((job->flags&JOB_FIRST) && (Lst_Open(gn->commands) != SUCCESS)){
1860 		cmdsOK = FALSE;
1861 	    } else {
1862 		LstNode	ln = Lst_Next(gn->commands);
1863 
1864 		if ((ln == NILLNODE) ||
1865 		    JobPrintCommand((ClientData) Lst_Datum(ln),
1866 				    (ClientData) job))
1867 		{
1868 		    noExec = TRUE;
1869 		    Lst_Close(gn->commands);
1870 		}
1871 		if (noExec && !(job->flags & JOB_FIRST)) {
1872 		    /*
1873 		     * If we're not going to execute anything, the job
1874 		     * is done and we need to close down the various
1875 		     * file descriptors we've opened for output, then
1876 		     * call JobDoOutput to catch the final characters or
1877 		     * send the file to the screen... Note that the i/o streams
1878 		     * are only open if this isn't the first job.
1879 		     * Note also that this could not be done in
1880 		     * Job_CatchChildren b/c it wasn't clear if there were
1881 		     * more commands to execute or not...
1882 		     */
1883 		    JobClose(job);
1884 		}
1885 	    }
1886 	} else {
1887 	    /*
1888 	     * We can do all the commands at once. hooray for sanity
1889 	     */
1890 	    numCommands = 0;
1891 	    Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1892 
1893 	    /*
1894 	     * If we didn't print out any commands to the shell script,
1895 	     * there's not much point in executing the shell, is there?
1896 	     */
1897 	    if (numCommands == 0) {
1898 		noExec = TRUE;
1899 	    }
1900 	}
1901     } else if (NoExecute(gn)) {
1902 	/*
1903 	 * Not executing anything -- just print all the commands to stdout
1904 	 * in one fell swoop. This will still set up job->tailCmds correctly.
1905 	 */
1906 	if (lastNode != gn) {
1907 	    MESSAGE(stdout, gn);
1908 	    lastNode = gn;
1909 	}
1910 	job->cmdFILE = stdout;
1911 	/*
1912 	 * Only print the commands if they're ok, but don't die if they're
1913 	 * not -- just let the user know they're bad and keep going. It
1914 	 * doesn't do any harm in this case and may do some good.
1915 	 */
1916 	if (cmdsOK) {
1917 	    Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1918 	}
1919 	/*
1920 	 * Don't execute the shell, thank you.
1921 	 */
1922 	noExec = TRUE;
1923     } else {
1924 	/*
1925 	 * Just touch the target and note that no shell should be executed.
1926 	 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1927 	 * but don't die if they're no good -- it does no harm to keep working
1928 	 * up the graph.
1929 	 */
1930 	job->cmdFILE = stdout;
1931     	Job_Touch(gn, job->flags&JOB_SILENT);
1932 	noExec = TRUE;
1933     }
1934 
1935     /*
1936      * If we're not supposed to execute a shell, don't.
1937      */
1938     if (noExec) {
1939 	/*
1940 	 * Unlink and close the command file if we opened one
1941 	 */
1942 	if (job->cmdFILE != stdout) {
1943 	    if (job->cmdFILE != NULL) {
1944 		(void) fclose(job->cmdFILE);
1945 		job->cmdFILE = NULL;
1946 	    }
1947 	} else {
1948 	     (void) fflush(stdout);
1949 	}
1950 
1951 	/*
1952 	 * We only want to work our way up the graph if we aren't here because
1953 	 * the commands for the job were no good.
1954 	 */
1955 	if (cmdsOK) {
1956 	    if (aborting == 0) {
1957 		if (job->tailCmds != NILLNODE) {
1958 		    Lst_ForEachFrom(job->node->commands, job->tailCmds,
1959 				    JobSaveCommand,
1960 				   (ClientData)job->node);
1961 		}
1962 		if (!(job->flags & JOB_SPECIAL))
1963 		    Job_TokenReturn();
1964 		Make_Update(job->node);
1965 	    }
1966 	    free((Address)job);
1967 	    return(JOB_FINISHED);
1968 	} else {
1969 	    free((Address)job);
1970 	    return(JOB_ERROR);
1971 	}
1972     } else {
1973 	(void) fflush(job->cmdFILE);
1974     }
1975 
1976     /*
1977      * Set up the control arguments to the shell. This is based on the flags
1978      * set earlier for this job.
1979      */
1980     JobMakeArgv(job, argv);
1981 
1982     /*
1983      * If we're using pipes to catch output, create the pipe by which we'll
1984      * get the shell's output. If we're using files, print out that we're
1985      * starting a job and then set up its temporary-file name.
1986      */
1987     if (!compatMake || (job->flags & JOB_FIRST)) {
1988 	if (usePipes) {
1989 	    int fd[2];
1990 	    if (pipe(fd) == -1)
1991 		Punt("Cannot create pipe: %s", strerror(errno));
1992 	    job->inPipe = fd[0];
1993 #ifdef USE_SELECT
1994 	    if (job->inPipe >= FD_SETSIZE)
1995 		Punt("Ran out of fd_set slots; "
1996 		    "recompile with a larger FD_SETSIZE.");
1997 #endif
1998 	    job->outPipe = fd[1];
1999 	    (void) fcntl(job->inPipe, F_SETFD, 1);
2000 	    (void) fcntl(job->outPipe, F_SETFD, 1);
2001 	} else {
2002 	    (void) fprintf(stdout, "Remaking `%s'\n", gn->name);
2003   	    (void) fflush(stdout);
2004 	    (void) strcpy(job->outFile, TMPPAT);
2005 	    job->outFd = mkstemp(job->outFile);
2006 	    (void) fcntl(job->outFd, F_SETFD, 1);
2007 	}
2008     }
2009 
2010 #ifdef REMOTE
2011     if (!(gn->type & OP_NOEXPORT) && !(runLocalFirst && nLocal < maxLocal)) {
2012 #ifdef RMT_NO_EXEC
2013 	local = !Rmt_Export(shellPath, argv, job);
2014 #else
2015 	local = !Rmt_Begin(shellPath, argv, job->node);
2016 #endif /* RMT_NO_EXEC */
2017 	if (!local) {
2018 	    job->flags |= JOB_REMOTE;
2019 	}
2020     } else
2021 #endif
2022 	local = TRUE;
2023 
2024     if (local && (((nLocal >= maxLocal) &&
2025 	!(job->flags & JOB_SPECIAL) &&
2026 #ifdef REMOTE
2027 	(!(gn->type & OP_NOEXPORT) || (maxLocal != 0))
2028 #else
2029 	(maxLocal != 0)
2030 #endif
2031 	)))
2032     {
2033 	/*
2034 	 * The job can only be run locally, but we've hit the limit of
2035 	 * local concurrency, so put the job on hold until some other job
2036 	 * finishes. Note that the special jobs (.BEGIN, .INTERRUPT and .END)
2037 	 * may be run locally even when the local limit has been reached
2038 	 * (e.g. when maxLocal == 0), though they will be exported if at
2039 	 * all possible. In addition, any target marked with .NOEXPORT will
2040 	 * be run locally if maxLocal is 0.
2041 	 */
2042 	job->flags |= JOB_RESTART;
2043 	(void) Lst_AtEnd(stoppedJobs, (ClientData)job);
2044     } else {
2045 	JobExec(job, argv);
2046     }
2047     return(JOB_RUNNING);
2048 }
2049 
2050 static char *
2051 JobOutput(job, cp, endp, msg)
2052     register Job *job;
2053     register char *cp, *endp;
2054     int msg;
2055 {
2056     register char *ecp;
2057 
2058     if (commandShell->noPrint) {
2059 	ecp = Str_FindSubstring(cp, commandShell->noPrint);
2060 	while (ecp != NULL) {
2061 	    if (cp != ecp) {
2062 		*ecp = '\0';
2063 		if (msg && job->node != lastNode) {
2064 		    MESSAGE(stdout, job->node);
2065 		    lastNode = job->node;
2066 		}
2067 		/*
2068 		 * The only way there wouldn't be a newline after
2069 		 * this line is if it were the last in the buffer.
2070 		 * however, since the non-printable comes after it,
2071 		 * there must be a newline, so we don't print one.
2072 		 */
2073 		(void) fprintf(stdout, "%s", cp);
2074 		(void) fflush(stdout);
2075 	    }
2076 	    cp = ecp + commandShell->noPLen;
2077 	    if (cp != endp) {
2078 		/*
2079 		 * Still more to print, look again after skipping
2080 		 * the whitespace following the non-printable
2081 		 * command....
2082 		 */
2083 		cp++;
2084 		while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
2085 		    cp++;
2086 		}
2087 		ecp = Str_FindSubstring(cp, commandShell->noPrint);
2088 	    } else {
2089 		return cp;
2090 	    }
2091 	}
2092     }
2093     return cp;
2094 }
2095 
2096 /*-
2097  *-----------------------------------------------------------------------
2098  * JobDoOutput  --
2099  *	This function is called at different times depending on
2100  *	whether the user has specified that output is to be collected
2101  *	via pipes or temporary files. In the former case, we are called
2102  *	whenever there is something to read on the pipe. We collect more
2103  *	output from the given job and store it in the job's outBuf. If
2104  *	this makes up a line, we print it tagged by the job's identifier,
2105  *	as necessary.
2106  *	If output has been collected in a temporary file, we open the
2107  *	file and read it line by line, transfering it to our own
2108  *	output channel until the file is empty. At which point we
2109  *	remove the temporary file.
2110  *	In both cases, however, we keep our figurative eye out for the
2111  *	'noPrint' line for the shell from which the output came. If
2112  *	we recognize a line, we don't print it. If the command is not
2113  *	alone on the line (the character after it is not \0 or \n), we
2114  *	do print whatever follows it.
2115  *
2116  * Results:
2117  *	None
2118  *
2119  * Side Effects:
2120  *	curPos may be shifted as may the contents of outBuf.
2121  *-----------------------------------------------------------------------
2122  */
2123 STATIC void
2124 JobDoOutput(job, finish)
2125     register Job   *job;	  /* the job whose output needs printing */
2126     Boolean	   finish;	  /* TRUE if this is the last time we'll be
2127 				   * called for this job */
2128 {
2129     Boolean       gotNL = FALSE;  /* true if got a newline */
2130     Boolean       fbuf;  	  /* true if our buffer filled up */
2131     register int  nr;	      	  /* number of bytes read */
2132     register int  i;	      	  /* auxiliary index into outBuf */
2133     register int  max;	      	  /* limit for i (end of current data) */
2134     int		  nRead;      	  /* (Temporary) number of bytes read */
2135 
2136     FILE      	  *oFILE;	  /* Stream pointer to shell's output file */
2137     char          inLine[132];
2138 
2139 
2140     if (usePipes) {
2141 	/*
2142 	 * Read as many bytes as will fit in the buffer.
2143 	 */
2144 end_loop:
2145 	gotNL = FALSE;
2146 	fbuf = FALSE;
2147 
2148 	nRead = read(job->inPipe, &job->outBuf[job->curPos],
2149 			 JOB_BUFSIZE - job->curPos);
2150 	if (nRead < 0) {
2151 	    if (DEBUG(JOB)) {
2152 		perror("JobDoOutput(piperead)");
2153 	    }
2154 	    nr = 0;
2155 	} else {
2156 	    nr = nRead;
2157 	}
2158 
2159 	/*
2160 	 * If we hit the end-of-file (the job is dead), we must flush its
2161 	 * remaining output, so pretend we read a newline if there's any
2162 	 * output remaining in the buffer.
2163 	 * Also clear the 'finish' flag so we stop looping.
2164 	 */
2165 	if ((nr == 0) && (job->curPos != 0)) {
2166 	    job->outBuf[job->curPos] = '\n';
2167 	    nr = 1;
2168 	    finish = FALSE;
2169 	} else if (nr == 0) {
2170 	    finish = FALSE;
2171 	}
2172 
2173 	/*
2174 	 * Look for the last newline in the bytes we just got. If there is
2175 	 * one, break out of the loop with 'i' as its index and gotNL set
2176 	 * TRUE.
2177 	 */
2178 	max = job->curPos + nr;
2179 	for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2180 	    if (job->outBuf[i] == '\n') {
2181 		gotNL = TRUE;
2182 		break;
2183 	    } else if (job->outBuf[i] == '\0') {
2184 		/*
2185 		 * Why?
2186 		 */
2187 		job->outBuf[i] = ' ';
2188 	    }
2189 	}
2190 
2191 	if (!gotNL) {
2192 	    job->curPos += nr;
2193 	    if (job->curPos == JOB_BUFSIZE) {
2194 		/*
2195 		 * If we've run out of buffer space, we have no choice
2196 		 * but to print the stuff. sigh.
2197 		 */
2198 		fbuf = TRUE;
2199 		i = job->curPos;
2200 	    }
2201 	}
2202 	if (gotNL || fbuf) {
2203 	    /*
2204 	     * Need to send the output to the screen. Null terminate it
2205 	     * first, overwriting the newline character if there was one.
2206 	     * So long as the line isn't one we should filter (according
2207 	     * to the shell description), we print the line, preceded
2208 	     * by a target banner if this target isn't the same as the
2209 	     * one for which we last printed something.
2210 	     * The rest of the data in the buffer are then shifted down
2211 	     * to the start of the buffer and curPos is set accordingly.
2212 	     */
2213 	    job->outBuf[i] = '\0';
2214 	    if (i >= job->curPos) {
2215 		char *cp;
2216 
2217 		cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
2218 
2219 		/*
2220 		 * There's still more in that thar buffer. This time, though,
2221 		 * we know there's no newline at the end, so we add one of
2222 		 * our own free will.
2223 		 */
2224 		if (*cp != '\0') {
2225 		    if (job->node != lastNode) {
2226 			MESSAGE(stdout, job->node);
2227 			lastNode = job->node;
2228 		    }
2229 		    (void) fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
2230 		    (void) fflush(stdout);
2231 		}
2232 	    }
2233 	    if (i < max - 1) {
2234 		/* shift the remaining characters down */
2235 		(void) memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
2236 		job->curPos = max - (i + 1);
2237 
2238 	    } else {
2239 		/*
2240 		 * We have written everything out, so we just start over
2241 		 * from the start of the buffer. No copying. No nothing.
2242 		 */
2243 		job->curPos = 0;
2244 	    }
2245 	}
2246 	if (finish) {
2247 	    /*
2248 	     * If the finish flag is true, we must loop until we hit
2249 	     * end-of-file on the pipe. This is guaranteed to happen
2250 	     * eventually since the other end of the pipe is now closed
2251 	     * (we closed it explicitly and the child has exited). When
2252 	     * we do get an EOF, finish will be set FALSE and we'll fall
2253 	     * through and out.
2254 	     */
2255 	    goto end_loop;
2256 	}
2257     } else {
2258 	/*
2259 	 * We've been called to retrieve the output of the job from the
2260 	 * temporary file where it's been squirreled away. This consists of
2261 	 * opening the file, reading the output line by line, being sure not
2262 	 * to print the noPrint line for the shell we used, then close and
2263 	 * remove the temporary file. Very simple.
2264 	 *
2265 	 * Change to read in blocks and do FindSubString type things as for
2266 	 * pipes? That would allow for "@echo -n..."
2267 	 */
2268 	oFILE = fopen(job->outFile, "r");
2269 	if (oFILE != NULL) {
2270 	    (void) fprintf(stdout, "Results of making %s:\n", job->node->name);
2271 	    (void) fflush(stdout);
2272 	    while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2273 		register char	*cp, *endp, *oendp;
2274 
2275 		cp = inLine;
2276 		oendp = endp = inLine + strlen(inLine);
2277 		if (endp[-1] == '\n') {
2278 		    *--endp = '\0';
2279 		}
2280 		cp = JobOutput(job, inLine, endp, FALSE);
2281 
2282 		/*
2283 		 * There's still more in that thar buffer. This time, though,
2284 		 * we know there's no newline at the end, so we add one of
2285 		 * our own free will.
2286 		 */
2287 		(void) fprintf(stdout, "%s", cp);
2288 		(void) fflush(stdout);
2289 		if (endp != oendp) {
2290 		    (void) fprintf(stdout, "\n");
2291 		    (void) fflush(stdout);
2292 		}
2293 	    }
2294 	    (void) fclose(oFILE);
2295 	    (void) eunlink(job->outFile);
2296 	} else {
2297 	    Punt("Cannot open `%s'", job->outFile);
2298 	}
2299     }
2300 }
2301 
2302 /*-
2303  *-----------------------------------------------------------------------
2304  * Job_CatchChildren --
2305  *	Handle the exit of a child. Called from Make_Make.
2306  *
2307  * Results:
2308  *	none.
2309  *
2310  * Side Effects:
2311  *	The job descriptor is removed from the list of children.
2312  *
2313  * Notes:
2314  *	We do waits, blocking or not, according to the wisdom of our
2315  *	caller, until there are no more children to report. For each
2316  *	job, call JobFinish to finish things off. This will take care of
2317  *	putting jobs on the stoppedJobs queue.
2318  *
2319  *-----------------------------------------------------------------------
2320  */
2321 void
2322 Job_CatchChildren(block)
2323     Boolean	  block;    	/* TRUE if should block on the wait. */
2324 {
2325     int    	  pid;	    	/* pid of dead child */
2326     register Job  *job;	    	/* job descriptor for dead child */
2327     LstNode       jnode;    	/* list element for finding job */
2328     int	  	  status;   	/* Exit/termination status */
2329 
2330     /*
2331      * Don't even bother if we know there's no one around.
2332      */
2333     if (nLocal == 0) {
2334 	return;
2335     }
2336 
2337     while ((pid = waitpid((pid_t) -1, &status,
2338 			  (block?0:WNOHANG)|WUNTRACED)) > 0)
2339     {
2340 	if (DEBUG(JOB)) {
2341 	    (void) fprintf(stdout, "Process %d exited or stopped %x.\n", pid,
2342 	      status);
2343 	    (void) fflush(stdout);
2344 	}
2345 
2346 
2347 	jnode = Lst_Find(jobs, (ClientData)&pid, JobCmpPid);
2348 
2349 	if (jnode == NILLNODE) {
2350 	    if (WIFSTOPPED(status) && (WSTOPSIG(status) == SIGCONT)) {
2351 		jnode = Lst_Find(stoppedJobs, (ClientData) &pid, JobCmpPid);
2352 		if (jnode == NILLNODE) {
2353 		    Error("Resumed child (%d) not in table", pid);
2354 		    continue;
2355 		}
2356 		job = (Job *)Lst_Datum(jnode);
2357 		(void) Lst_Remove(stoppedJobs, jnode);
2358 	    } else {
2359 		Error("Child (%d) not in table?", pid);
2360 		continue;
2361 	    }
2362 	} else {
2363 	    job = (Job *) Lst_Datum(jnode);
2364 	    (void) Lst_Remove(jobs, jnode);
2365 	    nJobs -= 1;
2366 #ifdef REMOTE
2367 	    if (!(job->flags & JOB_REMOTE)) {
2368 		if (DEBUG(JOB)) {
2369 		    (void) fprintf(stdout,
2370 				   "Job queue has one fewer local process.\n");
2371 		    (void) fflush(stdout);
2372 		}
2373 		nLocal -= 1;
2374 	    }
2375 #else
2376 	    nLocal -= 1;
2377 #endif
2378 	}
2379 
2380 	JobFinish(job, &status);
2381     }
2382 }
2383 
2384 /*-
2385  *-----------------------------------------------------------------------
2386  * Job_CatchOutput --
2387  *	Catch the output from our children, if we're using
2388  *	pipes do so. Otherwise just block time until we get a
2389  *	signal (most likely a SIGCHLD) since there's no point in
2390  *	just spinning when there's nothing to do and the reaping
2391  *	of a child can wait for a while.
2392  *
2393  * Results:
2394  *	None
2395  *
2396  * Side Effects:
2397  *	Output is read from pipes if we're piping.
2398  * -----------------------------------------------------------------------
2399  */
2400 void
2401 Job_CatchOutput()
2402 {
2403     int           	  nready;
2404     register LstNode	  ln;
2405     register Job   	  *job;
2406 #ifdef RMT_WILL_WATCH
2407     int	    	  	  pnJobs;   	/* Previous nJobs */
2408 #endif
2409 
2410     (void) fflush(stdout);
2411     Job_TokenFlush();
2412 #ifdef RMT_WILL_WATCH
2413     pnJobs = nJobs;
2414 
2415     /*
2416      * It is possible for us to be called with nJobs equal to 0. This happens
2417      * if all the jobs finish and a job that is stopped cannot be run
2418      * locally (eg if maxLocal is 0) and cannot be exported. The job will
2419      * be placed back on the stoppedJobs queue, Job_Empty() will return false,
2420      * Make_Run will call us again when there's nothing for which to wait.
2421      * nJobs never changes, so we loop forever. Hence the check. It could
2422      * be argued that we should sleep for a bit so as not to swamp the
2423      * exportation system with requests. Perhaps we should.
2424      *
2425      * NOTE: IT IS THE RESPONSIBILITY OF Rmt_Wait TO CALL Job_CatchChildren
2426      * IN A TIMELY FASHION TO CATCH ANY LOCALLY RUNNING JOBS THAT EXIT.
2427      * It may use the variable nLocal to determine if it needs to call
2428      * Job_CatchChildren (if nLocal is 0, there's nothing for which to
2429      * wait...)
2430      */
2431     while (nJobs != 0 && pnJobs == nJobs) {
2432 	Rmt_Wait();
2433     }
2434 #else
2435     if (usePipes) {
2436 #ifdef USE_SELECT
2437 	struct timeval	  timeout;
2438 	fd_set         	  readfds;
2439 
2440 	readfds = outputs;
2441 	timeout.tv_sec = SEL_SEC;
2442 	timeout.tv_usec = SEL_USEC;
2443 
2444 	if ((nready = select(FD_SETSIZE, &readfds, (fd_set *) 0,
2445 			   (fd_set *) 0, &timeout)) <= 0)
2446 	    return;
2447 #else
2448 	if ((nready = poll((wantToken ? fds : (fds + 1)),
2449 	  		   (wantToken ? nfds : (nfds - 1)), POLL_MSEC)) <= 0)
2450 	    return;
2451 #endif
2452 	else {
2453 	    if (Lst_Open(jobs) == FAILURE) {
2454 		Punt("Cannot open job table");
2455 	    }
2456 	    while (nready && (ln = Lst_Next(jobs)) != NILLNODE) {
2457 		job = (Job *) Lst_Datum(ln);
2458 #ifdef USE_SELECT
2459 		if (FD_ISSET(job->inPipe, &readfds))
2460 #else
2461 		if (readyfd(job))
2462 #endif
2463 		{
2464 		    JobDoOutput(job, FALSE);
2465 		    nready -= 1;
2466 		}
2467 
2468 	    }
2469 	    Lst_Close(jobs);
2470 	}
2471     }
2472 #endif /* RMT_WILL_WATCH */
2473 }
2474 
2475 /*-
2476  *-----------------------------------------------------------------------
2477  * Job_Make --
2478  *	Start the creation of a target. Basically a front-end for
2479  *	JobStart used by the Make module.
2480  *
2481  * Results:
2482  *	None.
2483  *
2484  * Side Effects:
2485  *	Another job is started.
2486  *
2487  *-----------------------------------------------------------------------
2488  */
2489 void
2490 Job_Make(gn)
2491     GNode   *gn;
2492 {
2493     (void) JobStart(gn, 0, NULL);
2494 }
2495 
2496 /*-
2497  *-----------------------------------------------------------------------
2498  * Job_Init --
2499  *	Initialize the process module
2500  *
2501  * Results:
2502  *	none
2503  *
2504  * Side Effects:
2505  *	lists and counters are initialized
2506  *-----------------------------------------------------------------------
2507  */
2508 void
2509 Job_Init(maxproc, maxlocal)
2510     int           maxproc;  /* the greatest number of jobs which may be
2511 			     * running at one time */
2512     int	    	  maxlocal; /* the greatest number of local jobs which may
2513 			     * be running at once. */
2514 {
2515     GNode         *begin;     /* node for commands to do at the very start */
2516 
2517     jobs =  	  Lst_Init(FALSE);
2518     stoppedJobs = Lst_Init(FALSE);
2519     maxJobs = 	  maxproc;
2520     maxLocal = 	  maxlocal;
2521     nJobs = 	  0;
2522     nLocal = 	  0;
2523     wantToken =	  FALSE;
2524 
2525     aborting = 	  0;
2526     errors = 	  0;
2527 
2528     lastNode =	  NILGNODE;
2529 
2530     if (maxJobs == 1
2531 #ifdef REMOTE
2532 	|| noMessages
2533 #endif
2534 		     ) {
2535 	/*
2536 	 * If only one job can run at a time, there's no need for a banner,
2537 	 * is there?
2538 	 */
2539 	targFmt = "";
2540     } else {
2541 	targFmt = TARG_FMT;
2542     }
2543 
2544     if (shellPath == NULL) {
2545 	/*
2546 	 * The user didn't specify a shell to use, so we are using the
2547 	 * default one... Both the absolute path and the last component
2548 	 * must be set. The last component is taken from the 'name' field
2549 	 * of the default shell description pointed-to by commandShell.
2550 	 * All default shells are located in _PATH_DEFSHELLDIR.
2551 	 */
2552 	shellName = commandShell->name;
2553 	shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2554     }
2555 
2556     if (commandShell->exit == NULL) {
2557 	commandShell->exit = "";
2558     }
2559     if (commandShell->echo == NULL) {
2560 	commandShell->echo = "";
2561     }
2562 
2563     /*
2564      * Catch the four signals that POSIX specifies if they aren't ignored.
2565      * JobPassSig will take care of calling JobInterrupt if appropriate.
2566      */
2567     if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2568 	(void) signal(SIGINT, JobPassSig);
2569     }
2570     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2571 	(void) signal(SIGHUP, JobPassSig);
2572     }
2573     if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2574 	(void) signal(SIGQUIT, JobPassSig);
2575     }
2576     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2577 	(void) signal(SIGTERM, JobPassSig);
2578     }
2579     /*
2580      * Install a NOOP  SIGCHLD handler so we are woken up if we're blocked.
2581      */
2582     signal(SIGCHLD, JobIgnoreSig);
2583 
2584     /*
2585      * There are additional signals that need to be caught and passed if
2586      * either the export system wants to be told directly of signals or if
2587      * we're giving each job its own process group (since then it won't get
2588      * signals from the terminal driver as we own the terminal)
2589      */
2590 #if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
2591     if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2592 	(void) signal(SIGTSTP, JobPassSig);
2593     }
2594     if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2595 	(void) signal(SIGTTOU, JobPassSig);
2596     }
2597     if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2598 	(void) signal(SIGTTIN, JobPassSig);
2599     }
2600     if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2601 	(void) signal(SIGWINCH, JobPassSig);
2602     }
2603     if (signal(SIGCONT, SIG_IGN) != SIG_IGN) {
2604 	(void) signal(SIGCONT, JobContinueSig);
2605     }
2606 #endif
2607 
2608     begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2609 
2610     if (begin != NILGNODE) {
2611 	JobStart(begin, JOB_SPECIAL, (Job *)0);
2612 	while (nJobs) {
2613 	    Job_CatchOutput();
2614 #ifndef RMT_WILL_WATCH
2615 	    Job_CatchChildren(!usePipes);
2616 #endif /* RMT_WILL_WATCH */
2617 	}
2618     }
2619     postCommands = Targ_FindNode(".END", TARG_CREATE);
2620 }
2621 
2622 /*-
2623  *-----------------------------------------------------------------------
2624  * Job_Empty --
2625  *	See if the job table is empty.  Because the local concurrency may
2626  *	be set to 0, it is possible for the job table to become empty,
2627  *	while the list of stoppedJobs remains non-empty. In such a case,
2628  *	we want to restart as many jobs as we can.
2629  *
2630  * Results:
2631  *	TRUE if it is. FALSE if it ain't.
2632  *
2633  * Side Effects:
2634  *	None.
2635  *
2636  * -----------------------------------------------------------------------
2637  */
2638 Boolean
2639 Job_Empty()
2640 {
2641     if (nJobs == 0) {
2642 	if (!Lst_IsEmpty(stoppedJobs) && !aborting) {
2643 	    /*
2644 	     * The job table is obviously not full if it has no jobs in
2645 	     * it...Try and restart the stopped jobs.
2646 	     */
2647 	    JobRestartJobs();
2648 	    return(FALSE);
2649 	} else {
2650 	    return(TRUE);
2651 	}
2652     } else {
2653 	return(FALSE);
2654     }
2655 }
2656 
2657 /*-
2658  *-----------------------------------------------------------------------
2659  * JobMatchShell --
2660  *	Find a matching shell in 'shells' given its final component.
2661  *
2662  * Results:
2663  *	A pointer to the Shell structure.
2664  *
2665  * Side Effects:
2666  *	None.
2667  *
2668  *-----------------------------------------------------------------------
2669  */
2670 static Shell *
2671 JobMatchShell(name)
2672     char	  *name;      /* Final component of shell path */
2673 {
2674     register Shell *sh;	      /* Pointer into shells table */
2675     Shell	   *match;    /* Longest-matching shell */
2676     register char *cp1,
2677 		  *cp2;
2678     char	  *eoname;
2679 
2680     eoname = name + strlen(name);
2681 
2682     match = NULL;
2683 
2684     for (sh = shells; sh->name != NULL; sh++) {
2685 	for (cp1 = eoname - strlen(sh->name), cp2 = sh->name;
2686 	     *cp1 != '\0' && *cp1 == *cp2;
2687 	     cp1++, cp2++) {
2688 		 continue;
2689 	}
2690 	if (*cp1 != *cp2) {
2691 	    continue;
2692 	} else if (match == NULL || strlen(match->name) < strlen(sh->name)) {
2693 	   match = sh;
2694 	}
2695     }
2696     return(match == NULL ? sh : match);
2697 }
2698 
2699 /*-
2700  *-----------------------------------------------------------------------
2701  * Job_ParseShell --
2702  *	Parse a shell specification and set up commandShell, shellPath
2703  *	and shellName appropriately.
2704  *
2705  * Results:
2706  *	FAILURE if the specification was incorrect.
2707  *
2708  * Side Effects:
2709  *	commandShell points to a Shell structure (either predefined or
2710  *	created from the shell spec), shellPath is the full path of the
2711  *	shell described by commandShell, while shellName is just the
2712  *	final component of shellPath.
2713  *
2714  * Notes:
2715  *	A shell specification consists of a .SHELL target, with dependency
2716  *	operator, followed by a series of blank-separated words. Double
2717  *	quotes can be used to use blanks in words. A backslash escapes
2718  *	anything (most notably a double-quote and a space) and
2719  *	provides the functionality it does in C. Each word consists of
2720  *	keyword and value separated by an equal sign. There should be no
2721  *	unnecessary spaces in the word. The keywords are as follows:
2722  *	    name  	    Name of shell.
2723  *	    path  	    Location of shell. Overrides "name" if given
2724  *	    quiet 	    Command to turn off echoing.
2725  *	    echo  	    Command to turn echoing on
2726  *	    filter	    Result of turning off echoing that shouldn't be
2727  *	    	  	    printed.
2728  *	    echoFlag	    Flag to turn echoing on at the start
2729  *	    errFlag	    Flag to turn error checking on at the start
2730  *	    hasErrCtl	    True if shell has error checking control
2731  *	    check 	    Command to turn on error checking if hasErrCtl
2732  *	    	  	    is TRUE or template of command to echo a command
2733  *	    	  	    for which error checking is off if hasErrCtl is
2734  *	    	  	    FALSE.
2735  *	    ignore	    Command to turn off error checking if hasErrCtl
2736  *	    	  	    is TRUE or template of command to execute a
2737  *	    	  	    command so as to ignore any errors it returns if
2738  *	    	  	    hasErrCtl is FALSE.
2739  *
2740  *-----------------------------------------------------------------------
2741  */
2742 ReturnStatus
2743 Job_ParseShell(line)
2744     char	  *line;  /* The shell spec */
2745 {
2746     char    	  **words;
2747     int	    	  wordCount;
2748     register char **argv;
2749     register int  argc;
2750     char    	  *path;
2751     Shell   	  newShell;
2752     Boolean 	  fullSpec = FALSE;
2753 
2754     while (isspace((unsigned char)*line)) {
2755 	line++;
2756     }
2757 
2758     if (shellArgv)
2759 	free(shellArgv);
2760 
2761     words = brk_string(line, &wordCount, TRUE, &shellArgv);
2762 
2763     memset((Address)&newShell, 0, sizeof(newShell));
2764 
2765     /*
2766      * Parse the specification by keyword
2767      */
2768     for (path = NULL, argc = wordCount - 1, argv = words;
2769 	argc != 0;
2770 	argc--, argv++) {
2771 	    if (strncmp(*argv, "path=", 5) == 0) {
2772 		path = &argv[0][5];
2773 	    } else if (strncmp(*argv, "name=", 5) == 0) {
2774 		newShell.name = &argv[0][5];
2775 	    } else {
2776 		if (strncmp(*argv, "quiet=", 6) == 0) {
2777 		    newShell.echoOff = &argv[0][6];
2778 		} else if (strncmp(*argv, "echo=", 5) == 0) {
2779 		    newShell.echoOn = &argv[0][5];
2780 		} else if (strncmp(*argv, "filter=", 7) == 0) {
2781 		    newShell.noPrint = &argv[0][7];
2782 		    newShell.noPLen = strlen(newShell.noPrint);
2783 		} else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2784 		    newShell.echo = &argv[0][9];
2785 		} else if (strncmp(*argv, "errFlag=", 8) == 0) {
2786 		    newShell.exit = &argv[0][8];
2787 		} else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2788 		    char c = argv[0][10];
2789 		    newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2790 					   (c != 'T') && (c != 't'));
2791 		} else if (strncmp(*argv, "check=", 6) == 0) {
2792 		    newShell.errCheck = &argv[0][6];
2793 		} else if (strncmp(*argv, "ignore=", 7) == 0) {
2794 		    newShell.ignErr = &argv[0][7];
2795 		} else {
2796 		    Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2797 				*argv);
2798 		    free(words);
2799 		    return(FAILURE);
2800 		}
2801 		fullSpec = TRUE;
2802 	    }
2803     }
2804 
2805     if (path == NULL) {
2806 	/*
2807 	 * If no path was given, the user wants one of the pre-defined shells,
2808 	 * yes? So we find the one s/he wants with the help of JobMatchShell
2809 	 * and set things up the right way. shellPath will be set up by
2810 	 * Job_Init.
2811 	 */
2812 	if (newShell.name == NULL) {
2813 	    Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2814 	    return(FAILURE);
2815 	} else {
2816 	    commandShell = JobMatchShell(newShell.name);
2817 	    shellName = newShell.name;
2818 	}
2819     } else {
2820 	/*
2821 	 * The user provided a path. If s/he gave nothing else (fullSpec is
2822 	 * FALSE), try and find a matching shell in the ones we know of.
2823 	 * Else we just take the specification at its word and copy it
2824 	 * to a new location. In either case, we need to record the
2825 	 * path the user gave for the shell.
2826 	 */
2827 	shellPath = path;
2828 	path = strrchr(path, '/');
2829 	if (path == NULL) {
2830 	    path = shellPath;
2831 	} else {
2832 	    path += 1;
2833 	}
2834 	if (newShell.name != NULL) {
2835 	    shellName = newShell.name;
2836 	} else {
2837 	    shellName = path;
2838 	}
2839 	if (!fullSpec) {
2840 	    commandShell = JobMatchShell(shellName);
2841 	} else {
2842 	    commandShell = (Shell *) emalloc(sizeof(Shell));
2843 	    *commandShell = newShell;
2844 	}
2845     }
2846 
2847     if (commandShell->echoOn && commandShell->echoOff) {
2848 	commandShell->hasEchoCtl = TRUE;
2849     }
2850 
2851     if (!commandShell->hasErrCtl) {
2852 	if (commandShell->errCheck == NULL) {
2853 	    commandShell->errCheck = "";
2854 	}
2855 	if (commandShell->ignErr == NULL) {
2856 	    commandShell->ignErr = "%s\n";
2857 	}
2858     }
2859 
2860     /*
2861      * Do not free up the words themselves, since they might be in use by the
2862      * shell specification.
2863      */
2864     free(words);
2865     return SUCCESS;
2866 }
2867 
2868 /*-
2869  *-----------------------------------------------------------------------
2870  * JobInterrupt --
2871  *	Handle the receipt of an interrupt.
2872  *
2873  * Results:
2874  *	None
2875  *
2876  * Side Effects:
2877  *	All children are killed. Another job will be started if the
2878  *	.INTERRUPT target was given.
2879  *-----------------------------------------------------------------------
2880  */
2881 static void
2882 JobInterrupt(runINTERRUPT, signo)
2883     int	    runINTERRUPT;   	/* Non-zero if commands for the .INTERRUPT
2884 				 * target should be executed */
2885     int	    signo;		/* signal received */
2886 {
2887     LstNode 	  ln;		/* element in job table */
2888     Job           *job;	    	/* job descriptor in that element */
2889     GNode         *interrupt;	/* the node describing the .INTERRUPT target */
2890 
2891     aborting = ABORT_INTERRUPT;
2892 
2893    (void) Lst_Open(jobs);
2894     while ((ln = Lst_Next(jobs)) != NILLNODE) {
2895 	job = (Job *) Lst_Datum(ln);
2896 
2897 	if (!Targ_Precious(job->node)) {
2898 	    char  	*file = (job->node->path == NULL ?
2899 				 job->node->name :
2900 				 job->node->path);
2901 	    if (!noExecute && eunlink(file) != -1) {
2902 		Error("*** %s removed", file);
2903 	    }
2904 	}
2905 #ifdef RMT_WANTS_SIGNALS
2906 	if (job->flags & JOB_REMOTE) {
2907 	    /*
2908 	     * If job is remote, let the Rmt module do the killing.
2909 	     */
2910 	    if (!Rmt_Signal(job, signo)) {
2911 		/*
2912 		 * If couldn't kill the thing, finish it out now with an
2913 		 * error code, since no exit report will come in likely.
2914 		 */
2915 		int status;
2916 
2917 		status.w_status = 0;
2918 		status.w_retcode = 1;
2919 		JobFinish(job, &status);
2920 	    }
2921 	} else if (job->pid) {
2922 	    KILL(job->pid, signo);
2923 	}
2924 #else
2925 	if (job->pid) {
2926 	    if (DEBUG(JOB)) {
2927 		(void) fprintf(stdout,
2928 			       "JobInterrupt passing signal to child %d.\n",
2929 			       job->pid);
2930 		(void) fflush(stdout);
2931 	    }
2932 	    KILL(job->pid, signo);
2933 	}
2934 #endif /* RMT_WANTS_SIGNALS */
2935     }
2936 
2937 #ifdef REMOTE
2938    (void)Lst_Open(stoppedJobs);
2939     while ((ln = Lst_Next(stoppedJobs)) != NILLNODE) {
2940 	job = (Job *) Lst_Datum(ln);
2941 
2942 	if (job->flags & JOB_RESTART) {
2943 	    if (DEBUG(JOB)) {
2944 		(void) fprintf(stdout, "%s%s",
2945 			       "JobInterrupt skipping job on stopped queue",
2946 			       "-- it was waiting to be restarted.\n");
2947 		(void) fflush(stdout);
2948 	    }
2949 	    continue;
2950 	}
2951 	if (!Targ_Precious(job->node)) {
2952 	    char  	*file = (job->node->path == NULL ?
2953 				 job->node->name :
2954 				 job->node->path);
2955 	    if (eunlink(file) == 0) {
2956 		Error("*** %s removed", file);
2957 	    }
2958 	}
2959 	/*
2960 	 * Resume the thing so it will take the signal.
2961 	 */
2962 	if (DEBUG(JOB)) {
2963 	    (void) fprintf(stdout,
2964 			   "JobInterrupt passing CONT to stopped child %d.\n",
2965 			   job->pid);
2966 	    (void) fflush(stdout);
2967 	}
2968 	KILL(job->pid, SIGCONT);
2969 #ifdef RMT_WANTS_SIGNALS
2970 	if (job->flags & JOB_REMOTE) {
2971 	    /*
2972 	     * If job is remote, let the Rmt module do the killing.
2973 	     */
2974 	    if (!Rmt_Signal(job, SIGINT)) {
2975 		/*
2976 		 * If couldn't kill the thing, finish it out now with an
2977 		 * error code, since no exit report will come in likely.
2978 		 */
2979 		int status;
2980 		status.w_status = 0;
2981 		status.w_retcode = 1;
2982 		JobFinish(job, &status);
2983 	    }
2984 	} else if (job->pid) {
2985 	    if (DEBUG(JOB)) {
2986 		(void) fprintf(stdout,
2987 		       "JobInterrupt passing interrupt to stopped child %d.\n",
2988 			       job->pid);
2989 		(void) fflush(stdout);
2990 	    }
2991 	    KILL(job->pid, SIGINT);
2992 	}
2993 #endif /* RMT_WANTS_SIGNALS */
2994     }
2995 #endif
2996     Lst_Close(stoppedJobs);
2997 
2998     if (runINTERRUPT && !touchFlag) {
2999 	interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3000 	if (interrupt != NILGNODE) {
3001 	    ignoreErrors = FALSE;
3002 
3003 	    JobStart(interrupt, JOB_IGNDOTS, (Job *)0);
3004 	    while (nJobs) {
3005 		Job_CatchOutput();
3006 #ifndef RMT_WILL_WATCH
3007 		Job_CatchChildren(!usePipes);
3008 #endif /* RMT_WILL_WATCH */
3009 	    }
3010 	}
3011     }
3012     Trace_Log(MAKEINTR, 0);
3013     exit(signo);
3014 }
3015 
3016 /*
3017  *-----------------------------------------------------------------------
3018  * Job_Finish --
3019  *	Do final processing such as the running of the commands
3020  *	attached to the .END target.
3021  *
3022  * Results:
3023  *	Number of errors reported.
3024  *
3025  * Side Effects:
3026  *	None.
3027  *-----------------------------------------------------------------------
3028  */
3029 int
3030 Job_Finish()
3031 {
3032     if (postCommands != NILGNODE && !Lst_IsEmpty(postCommands->commands)) {
3033 	if (errors) {
3034 	    Error("Errors reported so .END ignored");
3035 	} else {
3036 	    JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
3037 
3038 	    while (nJobs) {
3039 		Job_CatchOutput();
3040 #ifndef RMT_WILL_WATCH
3041 		Job_CatchChildren(!usePipes);
3042 #endif /* RMT_WILL_WATCH */
3043 	    }
3044 	}
3045     }
3046     Job_TokenFlush();
3047     return(errors);
3048 }
3049 
3050 /*-
3051  *-----------------------------------------------------------------------
3052  * Job_End --
3053  *	Cleanup any memory used by the jobs module
3054  *
3055  * Results:
3056  *	None.
3057  *
3058  * Side Effects:
3059  *	Memory is freed
3060  *-----------------------------------------------------------------------
3061  */
3062 void
3063 Job_End()
3064 {
3065 #ifdef CLEANUP
3066     if (shellArgv)
3067 	free(shellArgv);
3068 #endif
3069 }
3070 
3071 /*-
3072  *-----------------------------------------------------------------------
3073  * Job_Wait --
3074  *	Waits for all running jobs to finish and returns. Sets 'aborting'
3075  *	to ABORT_WAIT to prevent other jobs from starting.
3076  *
3077  * Results:
3078  *	None.
3079  *
3080  * Side Effects:
3081  *	Currently running jobs finish.
3082  *
3083  *-----------------------------------------------------------------------
3084  */
3085 void
3086 Job_Wait()
3087 {
3088     aborting = ABORT_WAIT;
3089     while (nJobs != 0) {
3090 	Job_CatchOutput();
3091 #ifndef RMT_WILL_WATCH
3092 	Job_CatchChildren(!usePipes);
3093 #endif /* RMT_WILL_WATCH */
3094     }
3095     Job_TokenFlush();
3096     aborting = 0;
3097 }
3098 
3099 /*-
3100  *-----------------------------------------------------------------------
3101  * Job_AbortAll --
3102  *	Abort all currently running jobs without handling output or anything.
3103  *	This function is to be called only in the event of a major
3104  *	error. Most definitely NOT to be called from JobInterrupt.
3105  *
3106  * Results:
3107  *	None
3108  *
3109  * Side Effects:
3110  *	All children are killed, not just the firstborn
3111  *-----------------------------------------------------------------------
3112  */
3113 void
3114 Job_AbortAll()
3115 {
3116     LstNode           	ln;	/* element in job table */
3117     Job            	*job;	/* the job descriptor in that element */
3118     int     	  	foo;
3119 
3120     aborting = ABORT_ERROR;
3121 
3122     if (nJobs) {
3123 
3124 	(void) Lst_Open(jobs);
3125 	while ((ln = Lst_Next(jobs)) != NILLNODE) {
3126 	    job = (Job *) Lst_Datum(ln);
3127 
3128 	    /*
3129 	     * kill the child process with increasingly drastic signals to make
3130 	     * darn sure it's dead.
3131 	     */
3132 #ifdef RMT_WANTS_SIGNALS
3133 	    if (job->flags & JOB_REMOTE) {
3134 		Rmt_Signal(job, SIGINT);
3135 		Rmt_Signal(job, SIGKILL);
3136 	    } else {
3137 		KILL(job->pid, SIGINT);
3138 		KILL(job->pid, SIGKILL);
3139 	    }
3140 #else
3141 	    KILL(job->pid, SIGINT);
3142 	    KILL(job->pid, SIGKILL);
3143 #endif /* RMT_WANTS_SIGNALS */
3144 	}
3145     }
3146 
3147     /*
3148      * Catch as many children as want to report in at first, then give up
3149      */
3150     while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
3151 	continue;
3152 }
3153 
3154 #ifdef REMOTE
3155 /*-
3156  *-----------------------------------------------------------------------
3157  * JobFlagForMigration --
3158  *	Handle the eviction of a child. Called from RmtStatusChange.
3159  *	Flags the child as remigratable and then suspends it.
3160  *
3161  * Results:
3162  *	none.
3163  *
3164  * Side Effects:
3165  *	The job descriptor is flagged for remigration.
3166  *
3167  *-----------------------------------------------------------------------
3168  */
3169 void
3170 JobFlagForMigration(hostID)
3171     int 	  hostID;    	/* ID of host we used, for matching children. */
3172 {
3173     register Job  *job;	    	/* job descriptor for dead child */
3174     LstNode       jnode;    	/* list element for finding job */
3175 
3176     if (DEBUG(JOB)) {
3177 	(void) fprintf(stdout, "JobFlagForMigration(%d) called.\n", hostID);
3178 	(void) fflush(stdout);
3179     }
3180     jnode = Lst_Find(jobs, (ClientData)hostID, JobCmpRmtID);
3181 
3182     if (jnode == NILLNODE) {
3183 	jnode = Lst_Find(stoppedJobs, (ClientData)hostID, JobCmpRmtID);
3184 		if (jnode == NILLNODE) {
3185 		    if (DEBUG(JOB)) {
3186 			Error("Evicting host(%d) not in table", hostID);
3187 		    }
3188 		    return;
3189 		}
3190     }
3191     job = (Job *) Lst_Datum(jnode);
3192 
3193     if (DEBUG(JOB)) {
3194 	(void) fprintf(stdout,
3195 		       "JobFlagForMigration(%d) found job '%s'.\n", hostID,
3196 		       job->node->name);
3197 	(void) fflush(stdout);
3198     }
3199 
3200     KILL(job->pid, SIGSTOP);
3201 
3202     job->flags |= JOB_REMIGRATE;
3203 }
3204 
3205 #endif
3206 
3207 /*-
3208  *-----------------------------------------------------------------------
3209  * JobRestartJobs --
3210  *	Tries to restart stopped jobs if there are slots available.
3211  *	Note that this tries to restart them regardless of pending errors.
3212  *	It's not good to leave stopped jobs lying around!
3213  *
3214  * Results:
3215  *	None.
3216  *
3217  * Side Effects:
3218  *	Resumes(and possibly migrates) jobs.
3219  *
3220  *-----------------------------------------------------------------------
3221  */
3222 static void
3223 JobRestartJobs()
3224 {
3225     while (!Lst_IsEmpty(stoppedJobs)) {
3226 	if (DEBUG(JOB)) {
3227 	    (void) fprintf(stdout, "Restarting a stopped job.\n");
3228 	    (void) fflush(stdout);
3229 	}
3230 	JobRestart((Job *)Lst_DeQueue(stoppedJobs));
3231     }
3232 }
3233 
3234 #ifndef RMT_WILL_WATCH
3235 #ifndef USE_SELECT
3236 static void
3237 watchfd(job)
3238     Job *job;
3239 {
3240     int i;
3241     if (job->inPollfd != NULL)
3242 	Punt("Watching watched job");
3243     if (fds == NULL) {
3244 	maxfds = JBSTART;
3245 	fds = emalloc(sizeof(struct pollfd) * maxfds);
3246 	jobfds = emalloc(sizeof(Job **) * maxfds);
3247 
3248 	fds[0].fd = job_pipe[0];
3249 	fds[0].events = POLLIN;
3250 	jobfds[0] = &tokenWaitJob;
3251 	tokenWaitJob.inPollfd = &fds[0];
3252 	nfds++;
3253     } else if (nfds == maxfds) {
3254 	maxfds *= JBFACTOR;
3255 	fds = erealloc(fds, sizeof(struct pollfd) * maxfds);
3256 	jobfds = erealloc(jobfds, sizeof(Job **) * maxfds);
3257 	for (i = 0; i < nfds; i++)
3258 	    jobfds[i]->inPollfd = &fds[i];
3259     }
3260 
3261     fds[nfds].fd = job->inPipe;
3262     fds[nfds].events = POLLIN;
3263     jobfds[nfds] = job;
3264     job->inPollfd = &fds[nfds];
3265     nfds++;
3266 }
3267 
3268 static void
3269 clearfd(job)
3270     Job *job;
3271 {
3272     int i;
3273     if (job->inPollfd == NULL)
3274 	Punt("Unwatching unwatched job");
3275     i = job->inPollfd - fds;
3276     nfds--;
3277     /*
3278      * Move last job in table into hole made by dead job.
3279      */
3280     if (nfds != i) {
3281 	fds[i] = fds[nfds];
3282 	jobfds[i] = jobfds[nfds];
3283 	jobfds[i]->inPollfd = &fds[i];
3284     }
3285     job->inPollfd = NULL;
3286 }
3287 
3288 static int
3289 readyfd(job)
3290     Job *job;
3291 {
3292     if (job->inPollfd == NULL)
3293 	Punt("Polling unwatched job");
3294     return (job->inPollfd->revents & POLLIN) != 0;
3295 }
3296 #endif
3297 #endif
3298 
3299 /*-
3300  *-----------------------------------------------------------------------
3301  * JobTokenAdd --
3302  *	Put a token into the job pipe so that some make process can start
3303  *	another job.
3304  *
3305  * Side Effects:
3306  *	Allows more build jobs to be spawned somewhere.
3307  *
3308  *-----------------------------------------------------------------------
3309  */
3310 
3311 static void
3312 JobTokenAdd()
3313 {
3314 
3315     if (DEBUG(JOB))
3316 	printf("deposit token\n");
3317     write(job_pipe[1], "+", 1);
3318 }
3319 
3320 /*-
3321  *-----------------------------------------------------------------------
3322  * Job_ServerStartTokenAdd --
3323  *	Prep the job token pipe in the root make process.
3324  *
3325  *-----------------------------------------------------------------------
3326  */
3327 
3328 void Job_ServerStart(maxproc)
3329     int maxproc;
3330 {
3331     int i, flags;
3332     char jobarg[64];
3333 
3334     if (pipe(job_pipe) < 0)
3335 	Fatal ("error in pipe: %s", strerror(errno));
3336 
3337     /*
3338      * We mark the input side of the pipe non-blocking; we poll(2) the
3339      * pipe when we're waiting for a job token, but we might lose the
3340      * race for the token when a new one becomes available, so the read
3341      * from the pipe should not block.
3342      */
3343     flags = fcntl(job_pipe[0], F_GETFL, 0);
3344     flags |= O_NONBLOCK;
3345     fcntl(job_pipe[0], F_SETFL, flags);
3346 
3347     /*
3348      * Mark job pipes as close-on-exec.
3349      * Note that we will clear this when executing submakes.
3350      */
3351     fcntl(job_pipe[0], F_SETFD, 1);
3352     fcntl(job_pipe[1], F_SETFD, 1);
3353 
3354     snprintf(jobarg, sizeof(jobarg), "%d,%d", job_pipe[0], job_pipe[1]);
3355 
3356     Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
3357     Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
3358 
3359     /*
3360      * Preload job_pipe with one token per job, save the one
3361      * "extra" token for the primary job.
3362      *
3363      * XXX should clip maxJobs against PIPE_BUF -- if maxJobs is
3364      * larger than the write buffer size of the pipe, we will
3365      * deadlock here.
3366      */
3367     for (i=1; i < maxproc; i++)
3368 	JobTokenAdd();
3369 }
3370 
3371 /*
3372  * this tracks the number of tokens currently "out" to build jobs.
3373  */
3374 int jobTokensRunning = 0;
3375 int jobTokensFree = 0;
3376 /*-
3377  *-----------------------------------------------------------------------
3378  * Job_TokenReturn --
3379  *	Return a withdrawn token to the pool.
3380  *
3381  *-----------------------------------------------------------------------
3382  */
3383 
3384 void
3385 Job_TokenReturn()
3386 {
3387     jobTokensRunning--;
3388     if (jobTokensRunning < 0)
3389 	Punt("token botch");
3390     if (jobTokensRunning)
3391 	jobTokensFree++;
3392 }
3393 
3394 /*-
3395  *-----------------------------------------------------------------------
3396  * Job_TokenWithdraw --
3397  *	Attempt to withdraw a token from the pool.
3398  *
3399  * Results:
3400  *	Returns TRUE if a token was withdrawn, and FALSE if the pool
3401  *	is currently empty.
3402  *
3403  * Side Effects:
3404  * 	If pool is empty, set wantToken so that we wake up
3405  *	when a token is released.
3406  *
3407  *-----------------------------------------------------------------------
3408  */
3409 
3410 
3411 Boolean
3412 Job_TokenWithdraw()
3413 {
3414     char tok;
3415     int count;
3416 
3417     if (aborting)
3418 	    return FALSE;
3419 
3420     if (jobTokensRunning == 0) {
3421 	if (DEBUG(JOB))
3422 	    printf("first one's free\n");
3423 	jobTokensRunning++;
3424 	wantToken = FALSE;
3425 	return TRUE;
3426     }
3427     if (jobTokensFree > 0) {
3428 	jobTokensFree--;
3429 	jobTokensRunning++;
3430 	wantToken = FALSE;
3431 	return TRUE;
3432     }
3433     count = read(job_pipe[0], &tok, 1);
3434     if (count == 0)
3435 	Fatal("eof on job pipe!");
3436     else if (count < 0) {
3437 	if (errno != EAGAIN) {
3438 	    Fatal("job pipe read: %s", strerror(errno));
3439 	}
3440 	if (DEBUG(JOB))
3441 	    printf("blocked for token\n");
3442 	wantToken = TRUE;
3443 	return FALSE;
3444     }
3445     wantToken = FALSE;
3446     jobTokensRunning++;
3447     if (DEBUG(JOB))
3448 	printf("withdrew token\n");
3449     return TRUE;
3450 }
3451 
3452 /*-
3453  *-----------------------------------------------------------------------
3454  * Job_TokenFlush --
3455  *	Return free tokens to the pool.
3456  *
3457  *-----------------------------------------------------------------------
3458  */
3459 
3460 void
3461 Job_TokenFlush()
3462 {
3463     if (compatMake) return;
3464 
3465     while (jobTokensFree > 0) {
3466 	JobTokenAdd();
3467 	jobTokensFree--;
3468     }
3469 }
3470 
3471