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