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