summaryrefslogtreecommitdiff
path: root/usr.bin/make/job.c
blob: c1226d4866c3df435c6a448b8c8789f2389cc530 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
/*	$OpenPackages$ */
/*	$OpenBSD: job.c,v 1.43 2001/09/04 23:35:58 millert Exp $	*/
/*	$NetBSD: job.c,v 1.16 1996/11/06 17:59:08 christos Exp $	*/

/*
 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
 * Copyright (c) 1988, 1989 by Adam de Boor
 * Copyright (c) 1989 by Berkeley Softworks
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Adam de Boor.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*-
 * job.c --
 *	handle the creation etc. of our child processes.
 *
 * Interface:
 *	Job_Make		Start the creation of the given target.
 *
 *	Job_CatchChildren	Check for and handle the termination of any
 *				children. This must be called reasonably
 *				frequently to keep the whole make going at
 *				a decent clip, since job table entries aren't
 *				removed until their process is caught this way.
 *				Its single argument is true if the function
 *				should block waiting for a child to terminate.
 *
 *	Job_CatchOutput 	Print any output our children have produced.
 *				Should also be called fairly frequently to
 *				keep the user informed of what's going on.
 *				If no output is waiting, it will block for
 *				a time given by the SEL_* constants, below,
 *				or until output is ready.
 *
 *	Job_Init		Called to intialize this module. in addition,
 *				any commands attached to the .BEGIN target
 *				are executed before this function returns.
 *				Hence, the makefile must have been parsed
 *				before this function is called.
 *
 *	Job_End 		Cleanup any memory used.
 *
 *	Job_Full		Return true if the job table is filled.
 *
 *	Job_Empty		Return true if the job table is completely
 *				empty.
 *
 *	Job_ParseShell		Given the line following a .SHELL target, parse
 *				the line as a shell specification. Returns
 *				false if the spec was incorrect.
 *
 *	Job_Finish		Perform any final processing which needs doing.
 *				This includes the execution of any commands
 *				which have been/were attached to the .END
 *				target. It should only be called when the
 *				job table is empty.
 *
 *	Job_AbortAll		Abort all currently running jobs. It doesn't
 *				handle output or do anything for the jobs,
 *				just kills them. It should only be called in
 *				an emergency, as it were.
 *
 *	Job_CheckCommands	Verify that the commands for a target are
 *				ok. Provide them if necessary and possible.
 *
 *	Job_Touch		Update a target without really updating it.
 *
 *	Job_Wait		Wait for all currently-running jobs to finish.
 */

#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "config.h"
#include "defines.h"
#include "dir.h"
#include "job.h"
#include "pathnames.h"
#include "arch.h"
#include "var.h"
#include "targ.h"
#include "error.h"
#include "str.h"
#include "lst.h"
#include "extern.h"
#include "gnode.h"
#include "memory.h"
#include "make.h"
#include "timestamp.h"
#include "main.h"

#ifdef REMOTE
#include "rmt.h"
# define STATIC
#else
# define STATIC static
#endif

/*
 * error handling variables
 */
static int	errors = 0;	    /* number of errors reported */
static int	aborting = 0;	    /* why is the make aborting? */
#define ABORT_ERROR	1	    /* Because of an error */
#define ABORT_INTERRUPT 2	    /* Because it was interrupted */
#define ABORT_WAIT	3	    /* Waiting for jobs to finish */

/*
 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
 * is a char! So when we go above 127 we turn negative!
 */
#define FILENO(a) ((unsigned) fileno(a))

/*
 * post-make command processing. The node postCommands is really just the
 * .END target but we keep it around to avoid having to search for it
 * all the time.
 */
static GNode	  *postCommands;    /* node containing commands to execute when
				     * everything else is done */
static int	  numCommands;	    /* The number of commands actually printed
				     * for a target. Should this number be
				     * 0, no shell will be executed. */

/*
 * Return values from JobStart.
 */
#define JOB_RUNNING	0	/* Job is running */
#define JOB_ERROR	1	/* Error in starting the job */
#define JOB_FINISHED	2	/* The job is already finished */
#define JOB_STOPPED	3	/* The job is stopped */

/*
 * tfile is the name of a file into which all shell commands are put. It is
 * used over by removing it before the child shell is executed. The XXXXXXXXXX
 * in the string are replaced by mkstemp(3).
 */
static char	tfile[sizeof(TMPPAT)];


/*
 * Descriptions for various shells.
 */
static Shell	shells[] = {
    /*
     * CSH description. The csh can do echo control by playing
     * with the setting of the 'echo' shell variable. Sadly,
     * however, it is unable to do error control nicely.
     */
{
    "csh",
    true, "unset verbose", "set verbose", "unset verbose", 10,
    false, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
    "v", "e",
},
    /*
     * SH description. Echo control is also possible and, under
     * sun UNIX anyway, one can even control error checking.
     */
{
    "sh",
    true, "set -", "set -v", "set -", 5,
    true, "set -e", "set +e",
#ifdef OLDBOURNESHELL
    false, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
#endif
    "v", "e",
},
    /*
     * UNKNOWN.
     */
{
    (char *)0,
    false, (char *)0, (char *)0, (char *)0, 0,
    false, (char *)0, (char *)0,
    (char *)0, (char *)0,
}
};
static Shell	*commandShell = &shells[DEFSHELL];/* this is the shell to
						   * which we pass all
						   * commands in the Makefile.
						   * It is set by the
						   * Job_ParseShell function */
static char	*shellPath = NULL,		  /* full pathname of
						   * executable image */
		*shellName = NULL,		  /* last component of shell */
		*shellArgv = NULL;		  /* Custom shell args */


static int	maxJobs;	/* The most children we can run at once */
static int	maxLocal;	/* The most local ones we can have */
STATIC int	nJobs = 0;	/* The number of children currently running */
STATIC int	nLocal; 	/* The number of local children */
STATIC LIST	jobs;		/* The structures that describe them */
STATIC bool	jobFull;	/* Flag to tell when the job table is full. It
				 * is set true when (1) the total number of
				 * running jobs equals the maximum allowed or
				 * (2) a job can only be run locally, but
				 * nLocal equals maxLocal */
#ifndef RMT_WILL_WATCH
static fd_set	*outputsp;	/* Set of descriptors of pipes connected to
				 * the output channels of children */
static int	outputsn;
#endif

STATIC GNode	*lastNode;	/* The node for which output was most recently
				 * produced. */
STATIC char	*targFmt;	/* Format string to use to head output from a
				 * job when it's not the most-recent job heard
				 * from */

#ifdef REMOTE
# define TARG_FMT  "--- %s at %s ---\n" /* Default format */
# define MESSAGE(fp, gn) \
	(void)fprintf(fp, targFmt, gn->name, gn->rem.hname);
#else
# define TARG_FMT  "--- %s ---\n" /* Default format */
# define MESSAGE(fp, gn) \
	(void)fprintf(fp, targFmt, gn->name);
#endif

/*
 * When JobStart attempts to run a job remotely but can't, and isn't allowed
 * to run the job locally, or when Job_CatchChildren detects a job that has
 * been migrated home, the job is placed on the stoppedJobs queue to be run
 * when the next job finishes.
 */
STATIC LIST	stoppedJobs;	/* Lst of Job structures describing
				 * jobs that were stopped due to concurrency
				 * limits or migration home */


#if defined(USE_PGRP) && defined(SYSV)
# define KILL(pid, sig) 	killpg(-(pid), (sig))
#else
# if defined(USE_PGRP)
#  define KILL(pid, sig)	killpg((pid), (sig))
# else
#  define KILL(pid, sig)	kill((pid), (sig))
# endif
#endif

/*
 * Grmpf... There is no way to set bits of the wait structure
 * anymore with the stupid W*() macros. I liked the union wait
 * stuff much more. So, we devise our own macros... This is
 * really ugly, use dramamine sparingly. You have been warned.
 */
#define W_SETMASKED(st, val, fun)				\
	{							\
		int sh = (int) ~0;				\
		int mask = fun(sh);				\
								\
		for (sh = 0; ((mask >> sh) & 1) == 0; sh++)	\
			continue;				\
		*(st) = (*(st) & ~mask) | ((val) << sh);	\
	}

#define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
#define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)


static void JobCondPassSig(void *, void *);
static void JobPassSig(int);
static int JobCmpPid(void *, void *);
static int JobPrintCommand(void *, void *);
static void JobSaveCommand(void *, void *);
static void JobClose(Job *);
#ifdef REMOTE
static int JobCmpRmtID(Job *, int);
# ifdef RMT_WILL_WATCH
static void JobLocalInput(int, Job *);
# endif
#else
static void JobFinish(Job *, int *);
static void JobExec(Job *, char **);
#endif
static void JobMakeArgv(Job *, char **);
static void JobRestart(Job *);
static int JobStart(GNode *, int, Job *);
static char *JobOutput(Job *, char *, char *, int);
static void JobDoOutput(Job *, bool);
static Shell *JobMatchShell(char *);
static void JobInterrupt(int, int);
static void JobRestartJobs(void);

/*-
 *-----------------------------------------------------------------------
 * JobCondPassSig --
 *	Pass a signal to a job if the job is remote or if USE_PGRP
 *	is defined.
 *
 * Side Effects:
 *	None, except the job may bite it.
 *-----------------------------------------------------------------------
 */
static void
JobCondPassSig(jobp, signop)
    void		*jobp;		/* Job to biff */
    void		*signop;	/* Signal to send it */
{
    Job *job = (Job *)jobp;
    int signo = *(int *)signop;
#ifdef RMT_WANTS_SIGNALS
    if (job->flags & JOB_REMOTE) {
	(void)Rmt_Signal(job, signo);
    } else {
	KILL(job->pid, signo);
    }
#else
    /*
     * Assume that sending the signal to job->pid will signal any remote
     * job as well.
     */
    if (DEBUG(JOB)) {
	(void)fprintf(stdout,
		       "JobCondPassSig passing signal %d to child %d.\n",
		       signo, job->pid);
	(void)fflush(stdout);
    }
    KILL(job->pid, signo);
#endif
}

/*-
 *-----------------------------------------------------------------------
 * JobPassSig --
 *	Pass a signal on to all remote jobs and to all local jobs if
 *	USE_PGRP is defined, then die ourselves.
 *
 * Side Effects:
 *	We die by the same signal.
 *-----------------------------------------------------------------------
 */
static void
JobPassSig(signo)
    int     signo;	/* The signal number we've received */
{
    sigset_t nmask, omask;
    struct sigaction act;

    if (DEBUG(JOB)) {
	(void)fprintf(stdout, "JobPassSig(%d) called.\n", signo);
	(void)fflush(stdout);
    }
    Lst_ForEach(&jobs, JobCondPassSig, &signo);

    /*
     * Deal with proper cleanup based on the signal received. We only run
     * the .INTERRUPT target if the signal was in fact an interrupt. The other
     * three termination signals are more of a "get out *now*" command.
     */
    if (signo == SIGINT) {
	JobInterrupt(true, signo);
    } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
	JobInterrupt(false, signo);
    }

    /*
     * Leave gracefully if SIGQUIT, rather than core dumping.
     */
    if (signo == SIGQUIT) {
	Finish(0);
    }

    /*
     * Send ourselves the signal now we've given the message to everyone else.
     * Note we block everything else possible while we're getting the signal.
     * This ensures that all our jobs get continued when we wake up before
     * we take any other signal.
     */
    sigemptyset(&nmask);
    sigaddset(&nmask, signo);
    sigprocmask(SIG_SETMASK, &nmask, &omask);
    memset(&act, 0, sizeof act);
    act.sa_handler = SIG_DFL;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(signo, &act, NULL);

    if (DEBUG(JOB)) {
	(void)fprintf(stdout,
		       "JobPassSig passing signal to self, mask = %x.\n",
		       ~0 & ~(1 << (signo-1)));
	(void)fflush(stdout);
    }
    (void)signal(signo, SIG_DFL);

    (void)KILL(getpid(), signo);

    signo = SIGCONT;
    Lst_ForEach(&jobs, JobCondPassSig, &signo);

    (void)sigprocmask(SIG_SETMASK, &omask, NULL);
    sigprocmask(SIG_SETMASK, &omask, NULL);
    act.sa_handler = JobPassSig;
    sigaction(signo, &act, NULL);
}

/*-
 *-----------------------------------------------------------------------
 * JobCmpPid  --
 *	Compare the pid of the job with the given pid and return 0 if they
 *	are equal. This function is called from Job_CatchChildren via
 *	Lst_Find to find the job descriptor of the finished job.
 *
 * Results:
 *	0 if the pid's match
 *-----------------------------------------------------------------------
 */
static int
JobCmpPid(job, pid)
    void *job;	/* job to examine */
    void *pid;	/* process id desired */
{
    return *(int *)pid - ((Job *)job)->pid;
}

#ifdef REMOTE
/*-
 *-----------------------------------------------------------------------
 * JobCmpRmtID	--
 *	Compare the rmtID of the job with the given rmtID and return 0 if they
 *	are equal.
 *
 * Results:
 *	0 if the rmtID's match
 *-----------------------------------------------------------------------
 */
static int
JobCmpRmtID(job, rmtID)
    void	*job;	/* job to examine */
    void	*rmtID; /* remote id desired */
{
    return *(int *)rmtID - *(int *)job->rmtID;
}
#endif

/*-
 *-----------------------------------------------------------------------
 * JobPrintCommand  --
 *	Put out another command for the given job. If the command starts
 *	with an @ or a - we process it specially. In the former case,
 *	so long as the -s and -n flags weren't given to make, we stick
 *	a shell-specific echoOff command in the script. In the latter,
 *	we ignore errors for the entire job, unless the shell has error
 *	control.
 *	If the command is just "..." we take all future commands for this
 *	job to be commands to be executed once the entire graph has been
 *	made and return non-zero to signal that the end of the commands
 *	was reached. These commands are later attached to the postCommands
 *	node and executed by Job_End when all things are done.
 *	This function is called from JobStart via Lst_Find
 *
 * Results:
 *	Always 1, unless the command was "..."
 *
 * Side Effects:
 *	If the command begins with a '-' and the shell has no error control,
 *	the JOB_IGNERR flag is set in the job descriptor.
 *	If the command is "..." and we're not ignoring such things,
 *	tailCmds is set to the successor node of the cmd.
 *	numCommands is incremented if the command is actually printed.
 *-----------------------------------------------------------------------
 */
static int
JobPrintCommand(cmdp, jobp)
    void	*cmdp;		    /* command string to print */
    void	*jobp;		    /* job for which to print it */
{
    bool	  noSpecials;	    /* true if we shouldn't worry about
				     * inserting special commands into
				     * the input stream. */
    bool	  shutUp = false;   /* true if we put a no echo command
				     * into the command file */
    bool	  errOff = false;   /* true if we turned error checking
				     * off before printing the command
				     * and need to turn it back on */
    char	  *cmdTemplate;     /* Template to use when printing the
				     * command */
    char	  *cmdStart;	    /* Start of expanded command */
    LstNode	  cmdNode;	    /* Node for replacing the command */
    char	  *cmd = (char *)cmdp;
    Job 	  *job = (Job *)jobp;

    noSpecials = (noExecute && !(job->node->type & OP_MAKE));

    if (strcmp(cmd, "...") == 0) {
	job->node->type |= OP_SAVE_CMDS;
	if ((job->flags & JOB_IGNDOTS) == 0) {
	    job->tailCmds = Lst_Succ(Lst_Member(&job->node->commands, cmd));
	    return 0;
	}
	return 1;
    }

#define DBPRINTF(fmt, arg) if (DEBUG(JOB)) {	\
	(void)fprintf(stdout, fmt, arg);	\
	(void)fflush(stdout);			\
    }						\
   (void)fprintf(job->cmdFILE, fmt, arg);	\
   (void)fflush(job->cmdFILE);

    numCommands += 1;

    /* For debugging, we replace each command with the result of expanding
     * the variables in the command.  */
    cmdNode = Lst_Member(&job->node->commands, cmd);
    cmdStart = cmd = Var_Subst(cmd, &job->node->context, false);
    Lst_Replace(cmdNode, cmdStart);

    cmdTemplate = "%s\n";

    /*
     * Check for leading @' and -'s to control echoing and error checking.
     */
    for (;; cmd++) {
	if (*cmd == '@')
	    shutUp = DEBUG(LOUD) ? false : true;
	else if (*cmd == '-')
	    errOff = true;
	else if (*cmd != '+')
	    break;
    }

    while (isspace(*cmd))
	cmd++;

    if (shutUp) {
	if (!(job->flags & JOB_SILENT) && !noSpecials &&
	    commandShell->hasEchoCtl) {
		DBPRINTF("%s\n", commandShell->echoOff);
	} else {
	    shutUp = false;
	}
    }

    if (errOff) {
	if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
	    if (commandShell->hasErrCtl) {
		/*
		 * we don't want the error-control commands showing
		 * up either, so we turn off echoing while executing
		 * them. We could put another field in the shell
		 * structure to tell JobDoOutput to look for this
		 * string too, but why make it any more complex than
		 * it already is?
		 */
		if (!(job->flags & JOB_SILENT) && !shutUp &&
		    commandShell->hasEchoCtl) {
			DBPRINTF("%s\n", commandShell->echoOff);
			DBPRINTF("%s\n", commandShell->ignErr);
			DBPRINTF("%s\n", commandShell->echoOn);
		} else {
		    DBPRINTF("%s\n", commandShell->ignErr);
		}
	    } else if (commandShell->ignErr &&
		      (*commandShell->ignErr != '\0'))
	    {
		/*
		 * The shell has no error control, so we need to be
		 * weird to get it to ignore any errors from the command.
		 * If echoing is turned on, we turn it off and use the
		 * errCheck template to echo the command. Leave echoing
		 * off so the user doesn't see the weirdness we go through
		 * to ignore errors. Set cmdTemplate to use the weirdness
		 * instead of the simple "%s\n" template.
		 */
		if (!(job->flags & JOB_SILENT) && !shutUp &&
		    commandShell->hasEchoCtl) {
			DBPRINTF("%s\n", commandShell->echoOff);
			DBPRINTF(commandShell->errCheck, cmd);
			shutUp = true;
		}
		cmdTemplate = commandShell->ignErr;
		/*
		 * The error ignoration (hee hee) is already taken care
		 * of by the ignErr template, so pretend error checking
		 * is still on.
		 */
		errOff = false;
	    } else {
		errOff = false;
	    }
	} else {
	    errOff = false;
	}
    }

    DBPRINTF(cmdTemplate, cmd);

    if (errOff) {
	/*
	 * If echoing is already off, there's no point in issuing the
	 * echoOff command. Otherwise we issue it and pretend it was on
	 * for the whole command...
	 */
	if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
	    DBPRINTF("%s\n", commandShell->echoOff);
	    shutUp = true;
	}
	DBPRINTF("%s\n", commandShell->errCheck);
    }
    if (shutUp) {
	DBPRINTF("%s\n", commandShell->echoOn);
    }
    return 1;
}

/*-
 *-----------------------------------------------------------------------
 * JobSaveCommand --
 *	Save a command to be executed when everything else is done.
 *	Callback function for JobFinish...
 *
 * Side Effects:
 *	The command is tacked onto the end of postCommands's commands list.
 *-----------------------------------------------------------------------
 */
static void
JobSaveCommand(cmd, gn)
    void	*cmd;
    void	*gn;
{
    GNode	*g = (GNode *)gn;
    char	*result;

    result = Var_Subst((char *)cmd, &g->context, false);
    Lst_AtEnd(&postCommands->commands, result);
}


/*-
 *-----------------------------------------------------------------------
 * JobClose --
 *	Called to close both input and output pipes when a job is finished.
 *
 * Side Effects:
 *	The file descriptors associated with the job are closed.
 *-----------------------------------------------------------------------
 */
static void
JobClose(job)
    Job *job;
{
    if (usePipes) {
#ifdef RMT_WILL_WATCH
	Rmt_Ignore(job->inPipe);
#else
	FD_CLR(job->inPipe, outputsp);
#endif
	if (job->outPipe != job->inPipe) {
	   (void)close(job->outPipe);
	}
	JobDoOutput(job, true);
	(void)close(job->inPipe);
    } else {
	(void)close(job->outFd);
	JobDoOutput(job, true);
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobFinish  --
 *	Do final processing for the given job including updating
 *	parents and starting new jobs as available/necessary. Note
 *	that we pay no attention to the JOB_IGNERR flag here.
 *	This is because when we're called because of a noexecute flag
 *	or something, jstat.w_status is 0 and when called from
 *	Job_CatchChildren, the status is zeroed if it s/b ignored.
 *
 * Side Effects:
 *	Some nodes may be put on the toBeMade queue.
 *	Final commands for the job are placed on postCommands.
 *
 *	If we got an error and are aborting (aborting == ABORT_ERROR) and
 *	the job list is now empty, we are done for the day.
 *	If we recognized an error (errors !=0), we set the aborting flag
 *	to ABORT_ERROR so no more jobs will be started.
 *-----------------------------------------------------------------------
 */
/*ARGSUSED*/
static void
JobFinish(job, status)
    Job 	*job;		  /* job to finish */
    int 	*status;	  /* sub-why job went away */
{
    bool	 done;

    if ((WIFEXITED(*status) &&
	 WEXITSTATUS(*status) != 0 && !(job->flags & JOB_IGNERR)) ||
	(WIFSIGNALED(*status) && WTERMSIG(*status) != SIGCONT))
    {
	/*
	 * If it exited non-zero and either we're doing things our
	 * way or we're not ignoring errors, the job is finished.
	 * Similarly, if the shell died because of a signal
	 * the job is also finished. In these
	 * cases, finish out the job's output before printing the exit
	 * status...
	 */
#ifdef REMOTE
	KILL(job->pid, SIGCONT);
#endif
	JobClose(job);
	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
	   (void)fclose(job->cmdFILE);
	}
	done = true;
#ifdef REMOTE
	if (job->flags & JOB_REMOTE)
	    Rmt_Done(job->rmtID, job->node);
#endif
    } else if (WIFEXITED(*status)) {
	/*
	 * Deal with ignored errors in -B mode. We need to print a message
	 * telling of the ignored error as well as setting status.w_status
	 * to 0 so the next command gets run. To do this, we set done to be
	 * true if in -B mode and the job exited non-zero.
	 */
	done = WEXITSTATUS(*status) != 0;
	/*
	 * Old comment said: "Note we don't
	 * want to close down any of the streams until we know we're at the
	 * end."
	 * But we do. Otherwise when are we going to print the rest of the
	 * stuff?
	 */
	JobClose(job);
#ifdef REMOTE
	if (job->flags & JOB_REMOTE)
	    Rmt_Done(job->rmtID, job->node);
#endif /* REMOTE */
    } else {
	/*
	 * No need to close things down or anything.
	 */
	done = false;
    }

    if (done ||
	WIFSTOPPED(*status) ||
	(WIFSIGNALED(*status) && WTERMSIG(*status) == SIGCONT) ||
	DEBUG(JOB))
    {
	FILE	  *out;

	if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
	    /*
	     * If output is going to a file and this job is ignoring
	     * errors, arrange to have the exit status sent to the
	     * output file as well.
	     */
	    out = fdopen(job->outFd, "w");
	} else {
	    out = stdout;
	}

	if (WIFEXITED(*status)) {
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "Process %d exited.\n", job->pid);
		(void)fflush(stdout);
	    }
	    if (WEXITSTATUS(*status) != 0) {
		if (usePipes && job->node != lastNode) {
		    MESSAGE(out, job->node);
		    lastNode = job->node;
		}
		(void)fprintf(out, "*** Error code %d%s\n",
			       WEXITSTATUS(*status),
			       (job->flags & JOB_IGNERR) ? "(ignored)" : "");

		if (job->flags & JOB_IGNERR) {
		    *status = 0;
		}
	    } else if (DEBUG(JOB)) {
		if (usePipes && job->node != lastNode) {
		    MESSAGE(out, job->node);
		    lastNode = job->node;
		}
		(void)fprintf(out, "*** Completed successfully\n");
	    }
	} else if (WIFSTOPPED(*status)) {
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "Process %d stopped.\n", job->pid);
		(void)fflush(stdout);
	    }
	    if (usePipes && job->node != lastNode) {
		MESSAGE(out, job->node);
		lastNode = job->node;
	    }
	    if (!(job->flags & JOB_REMIGRATE)) {
		(void)fprintf(out, "*** Stopped -- signal %d\n",
		    WSTOPSIG(*status));
	    }
	    job->flags |= JOB_RESUME;
	    Lst_AtEnd(&stoppedJobs, job);
#ifdef REMOTE
	    if (job->flags & JOB_REMIGRATE)
		JobRestart(job);
#endif
	    (void)fflush(out);
	    return;
	} else if (WTERMSIG(*status) == SIGCONT) {
	    /*
	     * If the beastie has continued, shift the Job from the stopped
	     * list to the running one (or re-stop it if concurrency is
	     * exceeded) and go and get another child.
	     */
	    if (job->flags & (JOB_RESUME|JOB_REMIGRATE|JOB_RESTART)) {
		if (usePipes && job->node != lastNode) {
		    MESSAGE(out, job->node);
		    lastNode = job->node;
		}
		(void)fprintf(out, "*** Continued\n");
	    }
	    if (!(job->flags & JOB_CONTINUING)) {
		if (DEBUG(JOB)) {
		    (void)fprintf(stdout,
				   "Warning: process %d was not continuing.\n",
				   job->pid);
		    (void)fflush(stdout);
		}
#ifdef notdef
		/*
		 * We don't really want to restart a job from scratch just
		 * because it continued, especially not without killing the
		 * continuing process!	That's why this is ifdef'ed out.
		 * FD - 9/17/90
		 */
		JobRestart(job);
#endif
	    }
	    job->flags &= ~JOB_CONTINUING;
	    Lst_AtEnd(&jobs, job);
	    nJobs += 1;
	    if (!(job->flags & JOB_REMOTE)) {
		if (DEBUG(JOB)) {
		    (void)fprintf(stdout,
				   "Process %d is continuing locally.\n",
				   job->pid);
		    (void)fflush(stdout);
		}
		nLocal += 1;
	    }
	    if (nJobs == maxJobs) {
		jobFull = true;
		if (DEBUG(JOB)) {
		    (void)fprintf(stdout, "Job queue is full.\n");
		    (void)fflush(stdout);
		}
	    }
	    (void)fflush(out);
	    return;
	} else {
	    if (usePipes && job->node != lastNode) {
		MESSAGE(out, job->node);
		lastNode = job->node;
	    }
	    (void)fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
	}

	(void)fflush(out);
    }

    /*
     * Now handle the -B-mode stuff. If the beast still isn't finished,
     * try and restart the job on the next command. If JobStart says it's
     * ok, it's ok. If there's an error, this puppy is done.
     */
    if (compatMake && WIFEXITED(*status) && job->node->current != NULL) {
	switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
	case JOB_RUNNING:
	    done = false;
	    break;
	case JOB_ERROR:
	    done = true;
	    W_SETEXITSTATUS(status, 1);
	    break;
	case JOB_FINISHED:
	    /*
	     * If we got back a JOB_FINISHED code, JobStart has already
	     * called Make_Update and freed the job descriptor. We set
	     * done to false here to avoid fake cycles and double frees.
	     * JobStart needs to do the update so we can proceed up the
	     * graph when given the -n flag..
	     */
	    done = false;
	    break;
	}
    } else
	done = true;

    if (done &&
	aborting != ABORT_ERROR &&
	aborting != ABORT_INTERRUPT &&
	*status == 0) {
	/* As long as we aren't aborting and the job didn't return a non-zero
	 * status that we shouldn't ignore, we call Make_Update to update
	 * the parents. In addition, any saved commands for the node are placed
	 * on the .END target.	*/
	Lst_ForEachFrom(job->tailCmds, JobSaveCommand, job->node);
	job->node->made = MADE;
	Make_Update(job->node);
	free(job);
    } else if (*status != 0) {
	errors += 1;
	free(job);
    }

    JobRestartJobs();

    /*
     * Set aborting if any error.
     */
    if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
	/*
	 * If we found any errors in this batch of children and the -k flag
	 * wasn't given, we set the aborting flag so no more jobs get
	 * started.
	 */
	aborting = ABORT_ERROR;
    }

    if (aborting == ABORT_ERROR && Job_Empty()) {
	/*
	 * If we are aborting and the job table is now empty, we finish.
	 */
	(void)eunlink(tfile);
	Finish(errors);
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_Touch --
 *	Touch the given target. Called by JobStart when the -t flag was
 *	given
 *
 * Side Effects:
 *	The data modification of the file is changed. In addition, if the
 *	file did not exist, it is created.
 *-----------------------------------------------------------------------
 */
void
Job_Touch(gn, silent)
    GNode	  *gn;		/* the node of the file to touch */
    bool	  silent;	/* true if should not print messages */
{
    int 	  streamID;	/* ID of stream opened to do the touch */

    if (gn->type & (OP_JOIN|OP_USE|OP_EXEC|OP_OPTIONAL)) {
	/*
	 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
	 * and, as such, shouldn't really be created.
	 */
	return;
    }

    if (!silent) {
	(void)fprintf(stdout, "touch %s\n", gn->name);
	(void)fflush(stdout);
    }

    if (noExecute) {
	return;
    }

    if (gn->type & OP_ARCHV) {
	Arch_Touch(gn);
    } else if (gn->type & OP_LIB) {
	Arch_TouchLib(gn);
    } else {
	const char *file = gn->path != NULL ? gn->path : gn->name;

	if (set_times(file) == -1){
	    streamID = open(file, O_RDWR | O_CREAT, 0666);

	    if (streamID >= 0) {
		char	c;

		/*
		 * Read and write a byte to the file to change the
		 * modification time, then close the file.
		 */
		if (read(streamID, &c, 1) == 1) {
		    (void)lseek(streamID, 0, SEEK_SET);
		    (void)write(streamID, &c, 1);
		}

		(void)close(streamID);
	    } else {
		(void)fprintf(stdout, "*** couldn't touch %s: %s",
			       file, strerror(errno));
		(void)fflush(stdout);
	    }
	}
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_CheckCommands --
 *	Make sure the given node has all the commands it needs.
 *
 * Results:
 *	true if the commands list is/was ok.
 *
 * Side Effects:
 *	The node will have commands from the .DEFAULT rule added to it
 *	if it needs them.
 *-----------------------------------------------------------------------
 */
bool
Job_CheckCommands(gn, abortProc)
    GNode	   *gn; 	    /* The target whose commands need
				     * verifying */
    void	 (*abortProc)(char *, ...);
			/* Function to abort with message */
{
    if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
	(gn->type & OP_LIB) == 0) {
	/*
	 * No commands. Look for .DEFAULT rule from which we might infer
	 * commands
	 */
	if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
	    /*
	     * Make only looks for a .DEFAULT if the node was never the
	     * target of an operator, so that's what we do too. If
	     * a .DEFAULT was given, we substitute its commands for gn's
	     * commands and set the IMPSRC variable to be the target's name
	     * The DEFAULT node acts like a transformation rule, in that
	     * gn also inherits any attributes or sources attached to
	     * .DEFAULT itself.
	     */
	    Make_HandleUse(DEFAULT, gn);
	    Varq_Set(IMPSRC_INDEX, Varq_Value(TARGET_INDEX, gn), gn);
	} else if (is_out_of_date(Dir_MTime(gn))) {
	    /*
	     * The node wasn't the target of an operator we have no .DEFAULT
	     * rule to go on and the target doesn't already exist. There's
	     * nothing more we can do for this branch. If the -k flag wasn't
	     * given, we stop in our tracks, otherwise we just don't update
	     * this node's parents so they never get examined.
	     */
	    static const char msg[] = "make: don't know how to make";

	    if (gn->type & OP_OPTIONAL) {
		(void)fprintf(stdout, "%s %s(ignored)\n", msg, gn->name);
		(void)fflush(stdout);
	    } else if (keepgoing) {
		(void)fprintf(stdout, "%s %s(continuing)\n", msg, gn->name);
		(void)fflush(stdout);
		return false;
	    } else {
		(*abortProc)("%s %s. Stop in %s.", msg, gn->name,
			Var_Value(".CURDIR"));
		return false;
	    }
	}
    }
    return true;
}
#ifdef RMT_WILL_WATCH
/*-
 *-----------------------------------------------------------------------
 * JobLocalInput --
 *	Handle a pipe becoming readable. Callback function for Rmt_Watch
 *
 * Side Effects:
 *	JobDoOutput is called.
 *-----------------------------------------------------------------------
 */
/*ARGSUSED*/
static void
JobLocalInput(stream, job)
    int     stream;	/* Stream that's ready (ignored) */
    Job     *job;	/* Job to which the stream belongs */
{
    JobDoOutput(job, false);
}
#endif /* RMT_WILL_WATCH */

/*-
 *-----------------------------------------------------------------------
 * JobExec --
 *	Execute the shell for the given job. Called from JobStart and
 *	JobRestart.
 *
 * Side Effects:
 *	A shell is executed, outputs is altered and the Job structure added
 *	to the job table.
 *-----------------------------------------------------------------------
 */
static void
JobExec(job, argv)
    Job 	  *job; 	/* Job to execute */
    char	  **argv;
{
    int 	  cpid; 	/* ID of new child */

    if (DEBUG(JOB)) {
	int	  i;

	(void)fprintf(stdout, "Running %s %sly\n", job->node->name,
		       job->flags&JOB_REMOTE?"remote":"local");
	(void)fprintf(stdout, "\tCommand: ");
	for (i = 0; argv[i] != NULL; i++) {
	    (void)fprintf(stdout, "%s ", argv[i]);
	}
	(void)fprintf(stdout, "\n");
	(void)fflush(stdout);
    }

    /*
     * Some jobs produce no output and it's disconcerting to have
     * no feedback of their running (since they produce no output, the
     * banner with their name in it never appears). This is an attempt to
     * provide that feedback, even if nothing follows it.
     */
    if (lastNode != job->node && (job->flags & JOB_FIRST) &&
	!(job->flags & JOB_SILENT)) {
	MESSAGE(stdout, job->node);
	lastNode = job->node;
    }

#ifdef RMT_NO_EXEC
    if (job->flags & JOB_REMOTE) {
	goto jobExecFinish;
    }
#endif /* RMT_NO_EXEC */

    if ((cpid = vfork()) == -1) {
	Punt("Cannot fork");
    } else if (cpid == 0) {

	/*
	 * Must duplicate the input stream down to the child's input and
	 * reset it to the beginning (again). Since the stream was marked
	 * close-on-exec, we must clear that bit in the new input.
	 */
	if (dup2(FILENO(job->cmdFILE), 0) == -1)
	    Punt("Cannot dup2: %s", strerror(errno));
	(void)fcntl(0, F_SETFD, 0);
	(void)lseek(0, 0, SEEK_SET);

	if (usePipes) {
	    /*
	     * Set up the child's output to be routed through the pipe
	     * we've created for it.
	     */
	    if (dup2(job->outPipe, 1) == -1)
		Punt("Cannot dup2: %s", strerror(errno));
	} else {
	    /*
	     * We're capturing output in a file, so we duplicate the
	     * descriptor to the temporary file into the standard
	     * output.
	     */
	    if (dup2(job->outFd, 1) == -1)
		Punt("Cannot dup2: %s", strerror(errno));
	}
	/*
	 * The output channels are marked close on exec. This bit was
	 * duplicated by the dup2 (on some systems), so we have to clear
	 * it before routing the shell's error output to the same place as
	 * its standard output.
	 */
	(void)fcntl(1, F_SETFD, 0);
	if (dup2(1, 2) == -1)
	    Punt("Cannot dup2: %s", strerror(errno));

#ifdef USE_PGRP
	/*
	 * We want to switch the child into a different process family so
	 * we can kill it and all its descendants in one fell swoop,
	 * by killing its process family, but not commit suicide.
	 */
# if defined(SYSV)
	(void)setsid();
# else
	(void)setpgid(0, getpid());
# endif
#endif /* USE_PGRP */

#ifdef REMOTE
	if (job->flags & JOB_REMOTE) {
	    Rmt_Exec(shellPath, argv, false);
	} else
#endif /* REMOTE */
	   (void)execv(shellPath, argv);

	(void)write(2, "Could not execute shell\n",
		     sizeof("Could not execute shell"));
	_exit(1);
    } else {
#ifdef REMOTE
	sigset_t mask, omask;

	sigemptyset(&mask);
	sigaddset(&mask, SIGCHLD);
	sigprocmask(SIG_BLOCK, &mask, &omask);
#endif
	job->pid = cpid;

	if (usePipes && (job->flags & JOB_FIRST) ) {
	    /*
	     * The first time a job is run for a node, we set the current
	     * position in the buffer to the beginning and mark another
	     * stream to watch in the outputs mask
	     */
	    job->curPos = 0;

#ifdef RMT_WILL_WATCH
	    Rmt_Watch(job->inPipe, JobLocalInput, job);
#else
	    if (outputsp == NULL || job->inPipe > outputsn) {
		int bytes = howmany(job->inPipe+1, NFDBITS) * sizeof(fd_mask);
		int obytes = howmany(outputsn+1, NFDBITS) * sizeof(fd_mask);

		if (outputsp == NULL || obytes != bytes) {
			outputsp = realloc(outputsp, bytes);
			if (outputsp == NULL)
				return;
			memset(outputsp + obytes, 0, bytes - obytes);
		}
		outputsn = job->inPipe;
	    }
	    FD_SET(job->inPipe, outputsp);
#endif /* RMT_WILL_WATCH */
	}

	if (job->flags & JOB_REMOTE) {
#ifndef REMOTE
	    job->rmtID = 0;
#else
	    job->rmtID = Rmt_LastID(job->pid);
#endif /* REMOTE */
	} else {
	    nLocal += 1;
	    /*
	     * XXX: Used to not happen if REMOTE. Why?
	     */
	    if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
		(void)fclose(job->cmdFILE);
		job->cmdFILE = NULL;
	    }
	}
#ifdef REMOTE
	sigprocmask(SIG_SETMASK, &omask, NULL);
#endif
    }

#ifdef RMT_NO_EXEC
jobExecFinish:
#endif
    /*
     * Now the job is actually running, add it to the table.
     */
    nJobs += 1;
    Lst_AtEnd(&jobs, job);
    if (nJobs == maxJobs) {
	jobFull = true;
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobMakeArgv --
 *	Create the argv needed to execute the shell for a given job.
 *-----------------------------------------------------------------------
 */
static void
JobMakeArgv(job, argv)
    Job 	  *job;
    char	  **argv;
{
    int 	  argc;
    static char   args[10];	/* For merged arguments */

    argv[0] = shellName;
    argc = 1;

    if ((commandShell->exit && *commandShell->exit != '-') ||
	(commandShell->echo && *commandShell->echo != '-'))
    {
	/*
	 * At least one of the flags doesn't have a minus before it, so
	 * merge them together. Have to do this because the *(&(@*#*&#$#
	 * Bourne shell thinks its second argument is a file to source.
	 * Grrrr. Note the ten-character limitation on the combined arguments.
	 */
	(void)sprintf(args, "-%s%s",
		      ((job->flags & JOB_IGNERR) ? "" :
		       (commandShell->exit ? commandShell->exit : "")),
		      ((job->flags & JOB_SILENT) ? "" :
		       (commandShell->echo ? commandShell->echo : "")));

	if (args[1]) {
	    argv[argc] = args;
	    argc++;
	}
    } else {
	if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
	    argv[argc] = commandShell->exit;
	    argc++;
	}
	if (!(job->flags & JOB_SILENT) && commandShell->echo) {
	    argv[argc] = commandShell->echo;
	    argc++;
	}
    }
    argv[argc] = NULL;
}

/*-
 *-----------------------------------------------------------------------
 * JobRestart --
 *	Restart a job that stopped for some reason.
 *
 * Side Effects:
 *	jobFull will be set if the job couldn't be run.
 *-----------------------------------------------------------------------
 */
static void
JobRestart(job)
    Job 	  *job; 	/* Job to restart */
{
#ifdef REMOTE
    int host;
#endif

    if (job->flags & JOB_REMIGRATE) {
	if (
#ifdef REMOTE
	    verboseRemigrates ||
#endif
	    DEBUG(JOB)) {
	   (void)fprintf(stdout, "*** remigrating %x(%s)\n",
			   job->pid, job->node->name);
	   (void)fflush(stdout);
	}

#ifdef REMOTE
	if (!Rmt_ReExport(job->pid, job->node, &host)) {
	    if (verboseRemigrates || DEBUG(JOB)) {
		(void)fprintf(stdout, "*** couldn't migrate...\n");
		(void)fflush(stdout);
	    }
#endif
	    if (nLocal != maxLocal) {
		/*
		 * Job cannot be remigrated, but there's room on the local
		 * machine, so resume the job and note that another
		 * local job has started.
		 */
		if (
#ifdef REMOTE
		    verboseRemigrates ||
#endif
		    DEBUG(JOB)) {
		    (void)fprintf(stdout, "*** resuming on local machine\n");
		    (void)fflush(stdout);
		}
		KILL(job->pid, SIGCONT);
		nLocal +=1;
#ifdef REMOTE
		job->flags &= ~(JOB_REMIGRATE|JOB_RESUME|JOB_REMOTE);
		job->flags |= JOB_CONTINUING;
#else
		job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
#endif
	} else {
		/*
		 * Job cannot be restarted. Mark the table as full and
		 * place the job back on the list of stopped jobs.
		 */
		if (
#ifdef REMOTE
		    verboseRemigrates ||
#endif
		    DEBUG(JOB)) {
		   (void)fprintf(stdout, "*** holding\n");
		   (void)fflush(stdout);
		}
		Lst_AtFront(&stoppedJobs, job);
		jobFull = true;
		if (DEBUG(JOB)) {
		   (void)fprintf(stdout, "Job queue is full.\n");
		   (void)fflush(stdout);
		}
		return;
	    }
#ifdef REMOTE
	} else {
	    /*
	     * Clear out the remigrate and resume flags. Set the continuing
	     * flag so we know later on that the process isn't exiting just
	     * because of a signal.
	     */
	    job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
	    job->flags |= JOB_CONTINUING;
	    job->rmtID = host;
	}
#endif

	Lst_AtEnd(&jobs, job);
	nJobs += 1;
	if (nJobs == maxJobs) {
	    jobFull = true;
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "Job queue is full.\n");
		(void)fflush(stdout);
	    }
	}
    } else if (job->flags & JOB_RESTART) {
	/*
	 * Set up the control arguments to the shell. This is based on the
	 * flags set earlier for this job. If the JOB_IGNERR flag is clear,
	 * the 'exit' flag of the commandShell is used to cause it to exit
	 * upon receiving an error. If the JOB_SILENT flag is clear, the
	 * 'echo' flag of the commandShell is used to get it to start echoing
	 * as soon as it starts processing commands.
	 */
	char	  *argv[4];

	JobMakeArgv(job, argv);

	if (DEBUG(JOB)) {
	    (void)fprintf(stdout, "Restarting %s...", job->node->name);
	    (void)fflush(stdout);
	}
#ifdef REMOTE
	if ((job->node->type&OP_NOEXPORT) ||
	    (nLocal < maxLocal && runLocalFirst)
# ifdef RMT_NO_EXEC
	    || !Rmt_Export(shellPath, argv, job)
# else
	    || !Rmt_Begin(shellPath, argv, job->node)
# endif
#endif
	{
	    if (nLocal >= maxLocal && !(job->flags & JOB_SPECIAL)) {
		/*
		 * Can't be exported and not allowed to run locally -- put it
		 * back on the hold queue and mark the table full
		 */
		if (DEBUG(JOB)) {
		    (void)fprintf(stdout, "holding\n");
		    (void)fflush(stdout);
		}
		Lst_AtFront(&stoppedJobs, job);
		jobFull = true;
		if (DEBUG(JOB)) {
		    (void)fprintf(stdout, "Job queue is full.\n");
		    (void)fflush(stdout);
		}
		return;
	    } else {
		/*
		 * Job may be run locally.
		 */
		if (DEBUG(JOB)) {
		    (void)fprintf(stdout, "running locally\n");
		    (void)fflush(stdout);
		}
		job->flags &= ~JOB_REMOTE;
	    }
	}
#ifdef REMOTE
	else {
	    /*
	     * Can be exported. Hooray!
	     */
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "exporting\n");
		(void)fflush(stdout);
	    }
	    job->flags |= JOB_REMOTE;
	}
#endif
	JobExec(job, argv);
    } else {
	/*
	 * The job has stopped and needs to be restarted. Why it stopped,
	 * we don't know...
	 */
	if (DEBUG(JOB)) {
	   (void)fprintf(stdout, "Resuming %s...", job->node->name);
	   (void)fflush(stdout);
	}
	if (((job->flags & JOB_REMOTE) ||
	    nLocal < maxLocal ||
#ifdef REMOTE
	    ((job->flags & JOB_SPECIAL) &&
	      (job->node->type & OP_NOEXPORT) &&
	     maxLocal == 0)
#else
	    ((job->flags & JOB_SPECIAL) &&
	     maxLocal == 0)
#endif
	   ) && nJobs != maxJobs)
	{
	    /*
	     * If the job is remote, it's ok to resume it as long as the
	     * maximum concurrency won't be exceeded. If it's local and
	     * we haven't reached the local concurrency limit already (or the
	     * job must be run locally and maxLocal is 0), it's also ok to
	     * resume it.
	     */
	    bool error;
	    int status;

#ifdef RMT_WANTS_SIGNALS
	    if (job->flags & JOB_REMOTE) {
		error = !Rmt_Signal(job, SIGCONT);
	    } else
#endif	/* RMT_WANTS_SIGNALS */
		error = KILL(job->pid, SIGCONT) != 0;

	    if (!error) {
		/*
		 * Make sure the user knows we've continued the beast and
		 * actually put the thing in the job table.
		 */
		job->flags |= JOB_CONTINUING;
		W_SETTERMSIG(&status, SIGCONT);
		JobFinish(job, &status);

		job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
		if (DEBUG(JOB)) {
		   (void)fprintf(stdout, "done\n");
		   (void)fflush(stdout);
		}
	    } else {
		Error("couldn't resume %s: %s",
		    job->node->name, strerror(errno));
		status = 0;
		W_SETEXITSTATUS(&status, 1);
		JobFinish(job, &status);
	    }
	} else {
	    /*
	     * Job cannot be restarted. Mark the table as full and
	     * place the job back on the list of stopped jobs.
	     */
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "table full\n");
		(void)fflush(stdout);
	    }
	    Lst_AtFront(&stoppedJobs, job);
	    jobFull = true;
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "Job queue is full.\n");
		(void)fflush(stdout);
	    }
	}
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobStart  --
 *	Start a target-creation process going for the target described
 *	by the graph node gn.
 *
 * Results:
 *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
 *	if there isn't actually anything left to do for the job and
 *	JOB_RUNNING if the job has been started.
 *
 * Side Effects:
 *	A new Job node is created and added to the list of running
 *	jobs. PMake is forked and a child shell created.
 *-----------------------------------------------------------------------
 */
static int
JobStart(gn, flags, previous)
    GNode	  *gn;	      /* target to create */
    int 	   flags;      /* flags for the job to override normal ones.
			       * e.g. JOB_SPECIAL or JOB_IGNDOTS */
    Job 	  *previous;  /* The previous Job structure for this node,
			       * if any. */
{
    Job 	  *job;       /* new job descriptor */
    char	  *argv[4];   /* Argument vector to shell */
    bool	  cmdsOK;     /* true if the nodes commands were all right */
    bool	  local;      /* Set true if the job was run locally */
    bool	  noExec;     /* Set true if we decide not to run the job */

    if (previous != NULL) {
	previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT|JOB_REMOTE);
	job = previous;
    } else {
	job = emalloc(sizeof(Job));
	if (job == NULL) {
	    Punt("JobStart out of memory");
	}
	flags |= JOB_FIRST;
    }

    job->node = gn;
    job->tailCmds = NULL;

    /*
     * Set the initial value of the flags for this job based on the global
     * ones and the node's attributes... Any flags supplied by the caller
     * are also added to the field.
     */
    job->flags = 0;
    if (Targ_Ignore(gn)) {
	job->flags |= JOB_IGNERR;
    }
    if (Targ_Silent(gn)) {
	job->flags |= JOB_SILENT;
    }
    job->flags |= flags;

    /*
     * Check the commands now so any attributes from .DEFAULT have a chance
     * to migrate to the node
     */
    if (!compatMake && job->flags & JOB_FIRST) {
	cmdsOK = Job_CheckCommands(gn, Error);
    } else {
	cmdsOK = true;
    }

    /*
     * If the -n flag wasn't given, we open up OUR (not the child's)
     * temporary file to stuff commands in it. The thing is rd/wr so we don't
     * need to reopen it to feed it to the shell. If the -n flag *was* given,
     * we just set the file to be stdout. Cute, huh?
     */
    if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
	/*
	 * We're serious here, but if the commands were bogus, we're
	 * also dead...
	 */
	if (!cmdsOK) {
	    DieHorribly();
	}

	job->cmdFILE = fopen(tfile, "w+");
	if (job->cmdFILE == NULL) {
	    Punt("Could not open %s", tfile);
	}
	(void)fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
	/*
	 * Send the commands to the command file, flush all its buffers then
	 * rewind and remove the thing.
	 */
	noExec = false;

	/*
	 * used to be backwards; replace when start doing multiple commands
	 * per shell.
	 */
	if (compatMake) {
	    /*
	     * Be compatible: If this is the first time for this node,
	     * verify its commands are ok and open the commands list for
	     * sequential access by later invocations of JobStart.
	     * Once that is done, we take the next command off the list
	     * and print it to the command file. If the command was an
	     * ellipsis, note that there's nothing more to execute.
	     */
	    if ((job->flags&JOB_FIRST))
		gn->current = Lst_First(&gn->commands);
	    else
		gn->current = Lst_Succ(gn->current);

	    if (gn->current == NULL ||
		!JobPrintCommand(Lst_Datum(gn->current), job)) {
		noExec = true;
		gn->current = NULL;
	    }
	    if (noExec && !(job->flags & JOB_FIRST)) {
		/*
		 * If we're not going to execute anything, the job
		 * is done and we need to close down the various
		 * file descriptors we've opened for output, then
		 * call JobDoOutput to catch the final characters or
		 * send the file to the screen... Note that the i/o streams
		 * are only open if this isn't the first job.
		 * Note also that this could not be done in
		 * Job_CatchChildren b/c it wasn't clear if there were
		 * more commands to execute or not...
		 */
		JobClose(job);
	    }
	} else {
	    /*
	     * We can do all the commands at once. hooray for sanity
	     */
	    numCommands = 0;
	    Lst_Find(&gn->commands, JobPrintCommand, job);

	    /*
	     * If we didn't print out any commands to the shell script,
	     * there's not much point in executing the shell, is there?
	     */
	    if (numCommands == 0) {
		noExec = true;
	    }
	}
    } else if (noExecute) {
	/*
	 * Not executing anything -- just print all the commands to stdout
	 * in one fell swoop. This will still set up job->tailCmds correctly.
	 */
	if (lastNode != gn) {
	    MESSAGE(stdout, gn);
	    lastNode = gn;
	}
	job->cmdFILE = stdout;
	/*
	 * Only print the commands if they're ok, but don't die if they're
	 * not -- just let the user know they're bad and keep going. It
	 * doesn't do any harm in this case and may do some good.
	 */
	if (cmdsOK) {
	    Lst_Find(&gn->commands, JobPrintCommand, job);
	}
	/*
	 * Don't execute the shell, thank you.
	 */
	noExec = true;
    } else {
	/*
	 * Just touch the target and note that no shell should be executed.
	 * Set cmdFILE to stdout to make life easier. Check the commands, too,
	 * but don't die if they're no good -- it does no harm to keep working
	 * up the graph.
	 */
	job->cmdFILE = stdout;
	Job_Touch(gn, job->flags&JOB_SILENT);
	noExec = true;
    }

    /*
     * If we're not supposed to execute a shell, don't.
     */
    if (noExec) {
	/*
	 * Unlink and close the command file if we opened one
	 */
	if (job->cmdFILE != stdout) {
	    (void)eunlink(tfile);
	    if (job->cmdFILE != NULL)
		(void)fclose(job->cmdFILE);
	} else {
	     (void)fflush(stdout);
	}

	/*
	 * We only want to work our way up the graph if we aren't here because
	 * the commands for the job were no good.
	 */
	if (cmdsOK) {
	    if (aborting == 0) {
		Lst_ForEachFrom(job->tailCmds, JobSaveCommand, job->node);
		Make_Update(job->node);
	    }
	    free(job);
	    return JOB_FINISHED;
	} else {
	    free(job);
	    return JOB_ERROR;
	}
    } else {
	(void)fflush(job->cmdFILE);
	(void)eunlink(tfile);
    }

    /*
     * Set up the control arguments to the shell. This is based on the flags
     * set earlier for this job.
     */
    JobMakeArgv(job, argv);

    /*
     * If we're using pipes to catch output, create the pipe by which we'll
     * get the shell's output. If we're using files, print out that we're
     * starting a job and then set up its temporary-file name.
     */
    if (!compatMake || (job->flags & JOB_FIRST)) {
	if (usePipes) {
	    int fd[2];
	    if (pipe(fd) == -1)
		Punt("Cannot create pipe: %s", strerror(errno));
	    job->inPipe = fd[0];
	    job->outPipe = fd[1];
	    (void)fcntl(job->inPipe, F_SETFD, 1);
	    (void)fcntl(job->outPipe, F_SETFD, 1);
	} else {
	    (void)fprintf(stdout, "Remaking `%s'\n", gn->name);
	    (void)fflush(stdout);
	    (void)strcpy(job->outFile, TMPPAT);
	    if ((job->outFd = mkstemp(job->outFile)) == -1)
		Punt("Cannot create temp file: %s", strerror(errno));
	    (void)fcntl(job->outFd, F_SETFD, 1);
	}
    }

#ifdef REMOTE
    if (!(gn->type & OP_NOEXPORT) && !(runLocalFirst && nLocal < maxLocal)) {
#ifdef RMT_NO_EXEC
	local = !Rmt_Export(shellPath, argv, job);
#else
	local = !Rmt_Begin(shellPath, argv, job->node);
#endif /* RMT_NO_EXEC */
	if (!local) {
	    job->flags |= JOB_REMOTE;
	}
    } else
#endif
	local = true;

    if (local && nLocal >= maxLocal &&
	!(job->flags & JOB_SPECIAL) &&
#ifdef REMOTE
	(!(gn->type & OP_NOEXPORT) || maxLocal != 0)
#else
	maxLocal != 0
#endif
	)
    {
	/*
	 * The job can only be run locally, but we've hit the limit of
	 * local concurrency, so put the job on hold until some other job
	 * finishes. Note that the special jobs (.BEGIN, .INTERRUPT and .END)
	 * may be run locally even when the local limit has been reached
	 * (e.g. when maxLocal == 0), though they will be exported if at
	 * all possible. In addition, any target marked with .NOEXPORT will
	 * be run locally if maxLocal is 0.
	 */
	jobFull = true;

	if (DEBUG(JOB)) {
	   (void)fprintf(stdout, "Can only run job locally.\n");
	   (void)fflush(stdout);
	}
	job->flags |= JOB_RESTART;
	Lst_AtEnd(&stoppedJobs, job);
    } else {
	if (nLocal >= maxLocal && local) {
	    /*
	     * If we're running this job locally as a special case (see above),
	     * at least say the table is full.
	     */
	    jobFull = true;
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "Local job queue is full.\n");
		(void)fflush(stdout);
	    }
	}
	JobExec(job, argv);
    }
    return JOB_RUNNING;
}

static char *
JobOutput(job, cp, endp, msg)
    Job *job;
    char *cp, *endp;
    int msg;
{
    char *ecp;

    if (commandShell->noPrint) {
	ecp = strstr(cp, commandShell->noPrint);
	while (ecp != NULL) {
	    if (cp != ecp) {
		*ecp = '\0';
		if (msg && job->node != lastNode) {
		    MESSAGE(stdout, job->node);
		    lastNode = job->node;
		}
		/*
		 * The only way there wouldn't be a newline after
		 * this line is if it were the last in the buffer.
		 * however, since the non-printable comes after it,
		 * there must be a newline, so we don't print one.
		 */
		(void)fprintf(stdout, "%s", cp);
		(void)fflush(stdout);
	    }
	    cp = ecp + commandShell->noPLen;
	    if (cp != endp) {
		/*
		 * Still more to print, look again after skipping
		 * the whitespace following the non-printable
		 * command....
		 */
		cp++;
		while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
		    cp++;
		}
		ecp = strstr(cp, commandShell->noPrint);
	    } else {
		return cp;
	    }
	}
    }
    return cp;
}

/*-
 *-----------------------------------------------------------------------
 * JobDoOutput	--
 *	This function is called at different times depending on
 *	whether the user has specified that output is to be collected
 *	via pipes or temporary files. In the former case, we are called
 *	whenever there is something to read on the pipe. We collect more
 *	output from the given job and store it in the job's outBuf. If
 *	this makes up a line, we print it tagged by the job's identifier,
 *	as necessary.
 *	If output has been collected in a temporary file, we open the
 *	file and read it line by line, transfering it to our own
 *	output channel until the file is empty. At which point we
 *	remove the temporary file.
 *	In both cases, however, we keep our figurative eye out for the
 *	'noPrint' line for the shell from which the output came. If
 *	we recognize a line, we don't print it. If the command is not
 *	alone on the line (the character after it is not \0 or \n), we
 *	do print whatever follows it.
 *
 * Side Effects:
 *	curPos may be shifted as may the contents of outBuf.
 *-----------------------------------------------------------------------
 */
STATIC void
JobDoOutput(job, finish)
    Job 	  *job;   /* the job whose output needs printing */
    bool	   finish;	  /* true if this is the last time we'll be
				   * called for this job */
{
    bool	  gotNL = false;  /* true if got a newline */
    bool	  fbuf; 	  /* true if our buffer filled up */
    int 	  nr;		  /* number of bytes read */
    int 	  i;		  /* auxiliary index into outBuf */
    int 	  max;		  /* limit for i (end of current data) */
    int 	  nRead;	  /* (Temporary) number of bytes read */

    FILE	  *oFILE;	  /* Stream pointer to shell's output file */
    char	  inLine[132];


    if (usePipes) {
	/*
	 * Read as many bytes as will fit in the buffer.
	 */
end_loop:
	gotNL = false;
	fbuf = false;

	nRead = read(job->inPipe, &job->outBuf[job->curPos],
			 JOB_BUFSIZE - job->curPos);
	if (nRead == -1) {
	    if (DEBUG(JOB)) {
		perror("JobDoOutput(piperead)");
	    }
	    nr = 0;
	} else {
	    nr = nRead;
	}

	/*
	 * If we hit the end-of-file (the job is dead), we must flush its
	 * remaining output, so pretend we read a newline if there's any
	 * output remaining in the buffer.
	 * Also clear the 'finish' flag so we stop looping.
	 */
	if (nr == 0 && job->curPos != 0) {
	    job->outBuf[job->curPos] = '\n';
	    nr = 1;
	    finish = false;
	} else if (nr == 0) {
	    finish = false;
	}

	/*
	 * Look for the last newline in the bytes we just got. If there is
	 * one, break out of the loop with 'i' as its index and gotNL set
	 * true.
	 */
	max = job->curPos + nr;
	for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
	    if (job->outBuf[i] == '\n') {
		gotNL = true;
		break;
	    } else if (job->outBuf[i] == '\0') {
		/*
		 * Why?
		 */
		job->outBuf[i] = ' ';
	    }
	}

	if (!gotNL) {
	    job->curPos += nr;
	    if (job->curPos == JOB_BUFSIZE) {
		/*
		 * If we've run out of buffer space, we have no choice
		 * but to print the stuff. sigh.
		 */
		fbuf = true;
		i = job->curPos;
	    }
	}
	if (gotNL || fbuf) {
	    /*
	     * Need to send the output to the screen. Null terminate it
	     * first, overwriting the newline character if there was one.
	     * So long as the line isn't one we should filter (according
	     * to the shell description), we print the line, preceeded
	     * by a target banner if this target isn't the same as the
	     * one for which we last printed something.
	     * The rest of the data in the buffer are then shifted down
	     * to the start of the buffer and curPos is set accordingly.
	     */
	    job->outBuf[i] = '\0';
	    if (i >= job->curPos) {
		char *cp;

		cp = JobOutput(job, job->outBuf, &job->outBuf[i], false);

		/*
		 * There's still more in that thar buffer. This time, though,
		 * we know there's no newline at the end, so we add one of
		 * our own free will.
		 */
		if (*cp != '\0') {
		    if (job->node != lastNode) {
			MESSAGE(stdout, job->node);
			lastNode = job->node;
		    }
		    (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
		    (void)fflush(stdout);
		}
	    }
	    if (i < max - 1) {
		/* shift the remaining characters down */
		(void)memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
		job->curPos = max - (i + 1);

	    } else {
		/*
		 * We have written everything out, so we just start over
		 * from the start of the buffer. No copying. No nothing.
		 */
		job->curPos = 0;
	    }
	}
	if (finish) {
	    /*
	     * If the finish flag is true, we must loop until we hit
	     * end-of-file on the pipe. This is guaranteed to happen
	     * eventually since the other end of the pipe is now closed
	     * (we closed it explicitly and the child has exited). When
	     * we do get an EOF, finish will be set false and we'll fall
	     * through and out.
	     */
	    goto end_loop;
	}
    } else {
	/*
	 * We've been called to retrieve the output of the job from the
	 * temporary file where it's been squirreled away. This consists of
	 * opening the file, reading the output line by line, being sure not
	 * to print the noPrint line for the shell we used, then close and
	 * remove the temporary file. Very simple.
	 *
	 * Change to read in blocks and do FindSubString type things as for
	 * pipes? That would allow for "@echo -n..."
	 */
	oFILE = fopen(job->outFile, "r");
	if (oFILE != NULL) {
	    (void)fprintf(stdout, "Results of making %s:\n", job->node->name);
	    (void)fflush(stdout);
	    while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
		char	*cp, *endp, *oendp;

		cp = inLine;
		oendp = endp = inLine + strlen(inLine);
		if (endp[-1] == '\n') {
		    *--endp = '\0';
		}
		cp = JobOutput(job, inLine, endp, false);

		/*
		 * There's still more in that thar buffer. This time, though,
		 * we know there's no newline at the end, so we add one of
		 * our own free will.
		 */
		(void)fprintf(stdout, "%s", cp);
		(void)fflush(stdout);
		if (endp != oendp) {
		    (void)fprintf(stdout, "\n");
		    (void)fflush(stdout);
		}
	    }
	    (void)fclose(oFILE);
	    (void)eunlink(job->outFile);
	}
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_CatchChildren --
 *	Handle the exit of a child. Called from Make_Make.
 *
 * Side Effects:
 *	The job descriptor is removed from the list of children.
 *
 * Notes:
 *	We do waits, blocking or not, according to the wisdom of our
 *	caller, until there are no more children to report. For each
 *	job, call JobFinish to finish things off. This will take care of
 *	putting jobs on the stoppedJobs queue.
 *-----------------------------------------------------------------------
 */
void
Job_CatchChildren(block)
    bool	  block;	/* true if should block on the wait. */
{
    int 	  pid;		/* pid of dead child */
    Job 	  *job; 	/* job descriptor for dead child */
    LstNode	  jnode;	/* list element for finding job */
    int 	  status;	/* Exit/termination status */

    /*
     * Don't even bother if we know there's no one around.
     */
    if (nLocal == 0) {
	return;
    }

    while ((pid = waitpid((pid_t) -1, &status,
			  (block?0:WNOHANG)|WUNTRACED)) > 0)
    {
	if (DEBUG(JOB)) {
	    (void)fprintf(stdout, "Process %d exited or stopped.\n", pid);
	    (void)fflush(stdout);
	}


	jnode = Lst_Find(&jobs, JobCmpPid, &pid);

	if (jnode == NULL) {
	    if (WIFSIGNALED(status) && (WTERMSIG(status) == SIGCONT)) {
		jnode = Lst_Find(&stoppedJobs, JobCmpPid, &pid);
		if (jnode == NULL) {
		    Error("Resumed child (%d) not in table", pid);
		    continue;
		}
		job = (Job *)Lst_Datum(jnode);
		Lst_Remove(&stoppedJobs, jnode);
	    } else {
		Error("Child (%d) not in table?", pid);
		continue;
	    }
	} else {
	    job = (Job *)Lst_Datum(jnode);
	    Lst_Remove(&jobs, jnode);
	    nJobs -= 1;
	    if (jobFull && DEBUG(JOB)) {
		(void)fprintf(stdout, "Job queue is no longer full.\n");
		(void)fflush(stdout);
	    }
	    jobFull = false;
#ifdef REMOTE
	    if (!(job->flags & JOB_REMOTE)) {
		if (DEBUG(JOB)) {
		    (void)fprintf(stdout,
				   "Job queue has one fewer local process.\n");
		    (void)fflush(stdout);
		}
		nLocal -= 1;
	    }
#else
	    nLocal -= 1;
#endif
	}

	JobFinish(job, &status);
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_CatchOutput --
 *	Catch the output from our children, if we're using
 *	pipes do so. Otherwise just block time until we get a
 *	signal (most likely a SIGCHLD) since there's no point in
 *	just spinning when there's nothing to do and the reaping
 *	of a child can wait for a while.
 *
 * Side Effects:
 *	Output is read from pipes if we're piping.
 * -----------------------------------------------------------------------
 */
void
Job_CatchOutput()
{
    int 		  nfds;
    struct timeval	  timeout;
    LstNode		  ln;
    Job 		  *job;
#ifdef RMT_WILL_WATCH
    int 		  pnJobs;	/* Previous nJobs */
#endif

    (void)fflush(stdout);
#ifdef RMT_WILL_WATCH
    pnJobs = nJobs;

    /*
     * It is possible for us to be called with nJobs equal to 0. This happens
     * if all the jobs finish and a job that is stopped cannot be run
     * locally (eg if maxLocal is 0) and cannot be exported. The job will
     * be placed back on the stoppedJobs queue, Job_Empty() will return false,
     * Make_Run will call us again when there's nothing for which to wait.
     * nJobs never changes, so we loop forever. Hence the check. It could
     * be argued that we should sleep for a bit so as not to swamp the
     * exportation system with requests. Perhaps we should.
     *
     * NOTE: IT IS THE RESPONSIBILITY OF Rmt_Wait TO CALL Job_CatchChildren
     * IN A TIMELY FASHION TO CATCH ANY LOCALLY RUNNING JOBS THAT EXIT.
     * It may use the variable nLocal to determine if it needs to call
     * Job_CatchChildren (if nLocal is 0, there's nothing for which to
     * wait...)
     */
    while (nJobs != 0 && pnJobs == nJobs) {
	Rmt_Wait();
    }
#else
    if (usePipes) {
	int count = howmany(outputsn+1, NFDBITS) * sizeof(fd_mask);
	fd_set *readfdsp = malloc(count);
	if (readfdsp == NULL)
	    return;

	memcpy(readfdsp, outputsp, count);
	timeout.tv_sec = SEL_SEC;
	timeout.tv_usec = SEL_USEC;

	if ((nfds = select(outputsn+1, readfdsp, (fd_set *) 0,
			   (fd_set *) 0, &timeout)) <= 0) {
	    free(readfdsp);
	    return;
	} else {
	    for (ln = Lst_First(&jobs); nfds && ln != NULL; ln = Lst_Adv(ln)) {
		job = (Job *)Lst_Datum(ln);
		if (FD_ISSET(job->inPipe, readfdsp)) {
		    JobDoOutput(job, false);
		    nfds -= 1;
		}
	    }
	}
	free(readfdsp);
    }
#endif /* RMT_WILL_WATCH */
}

/*-
 *-----------------------------------------------------------------------
 * Job_Make --
 *	Start the creation of a target. Basically a front-end for
 *	JobStart used by the Make module.
 *
 * Side Effects:
 *	Another job is started.
 *-----------------------------------------------------------------------
 */
void
Job_Make(gn)
    GNode   *gn;
{
    (void)JobStart(gn, 0, NULL);
}

/*-
 *-----------------------------------------------------------------------
 * Job_Init --
 *	Initialize the process module
 *
 * Side Effects:
 *	lists and counters are initialized
 *-----------------------------------------------------------------------
 */
void
Job_Init(maxproc, maxlocal)
    int 	  maxproc;  /* the greatest number of jobs which may be
			     * running at one time */
    int 	  maxlocal; /* the greatest number of local jobs which may
			     * be running at once. */
{
    GNode	  *begin;     /* node for commands to do at the very start */
    int 	  tfd;

    (void)strcpy(tfile, TMPPAT);
    if ((tfd = mkstemp(tfile)) == -1)
	Punt("Cannot create temp file: %s", strerror(errno));
    else
	(void)close(tfd);

    Lst_Init(&jobs);
    Lst_Init(&stoppedJobs);
    maxJobs =	  maxproc;
    maxLocal =	  maxlocal;
    nJobs =	  0;
    nLocal =	  0;
    jobFull =	  false;

    aborting =	  0;
    errors =	  0;

    lastNode =	  NULL;

    if (maxJobs == 1
#ifdef REMOTE
	|| noMessages
#endif
		     ) {
	/*
	 * If only one job can run at a time, there's no need for a banner,
	 * no is there?
	 */
	targFmt = "";
    } else {
	targFmt = TARG_FMT;
    }

    if (shellPath == NULL) {
	/*
	 * The user didn't specify a shell to use, so we are using the
	 * default one... Both the absolute path and the last component
	 * must be set. The last component is taken from the 'name' field
	 * of the default shell description pointed-to by commandShell.
	 * All default shells are located in _PATH_DEFSHELLDIR.
	 */
	shellName = commandShell->name;
	shellPath = Str_concat(_PATH_DEFSHELLDIR, shellName, '/');
    }

    if (commandShell->exit == NULL) {
	commandShell->exit = "";
    }
    if (commandShell->echo == NULL) {
	commandShell->echo = "";
    }

    /*
     * Catch the four signals that POSIX specifies if they aren't ignored.
     * JobPassSig will take care of calling JobInterrupt if appropriate.
     */
    if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGINT, JobPassSig);
    }
    if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGHUP, JobPassSig);
    }
    if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGQUIT, JobPassSig);
    }
    if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGTERM, JobPassSig);
    }
    /*
     * There are additional signals that need to be caught and passed if
     * either the export system wants to be told directly of signals or if
     * we're giving each job its own process group (since then it won't get
     * signals from the terminal driver as we own the terminal)
     */
#if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
    if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGTSTP, JobPassSig);
    }
    if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGTTOU, JobPassSig);
    }
    if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGTTIN, JobPassSig);
    }
    if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
	(void)signal(SIGWINCH, JobPassSig);
    }
#endif

    begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);

    if (begin != NULL) {
	JobStart(begin, JOB_SPECIAL, (Job *)0);
	while (nJobs) {
	    Job_CatchOutput();
#ifndef RMT_WILL_WATCH
	    Job_CatchChildren(!usePipes);
#endif /* RMT_WILL_WATCH */
	}
    }
    postCommands = Targ_FindNode(".END", TARG_CREATE);
}

/*-
 *-----------------------------------------------------------------------
 * Job_Full --
 *	See if the job table is full. It is considered full if it is OR
 *	if we are in the process of aborting OR if we have
 *	reached/exceeded our local quota. This prevents any more jobs
 *	from starting up.
 *
 * Results:
 *	true if the job table is full, false otherwise
 *-----------------------------------------------------------------------
 */
bool
Job_Full()
{
    return aborting || jobFull;
}

/*-
 *-----------------------------------------------------------------------
 * Job_Empty --
 *	See if the job table is empty.	Because the local concurrency may
 *	be set to 0, it is possible for the job table to become empty,
 *	while the list of stoppedJobs remains non-empty. In such a case,
 *	we want to restart as many jobs as we can.
 *
 * Results:
 *	true if it is. false if it ain't.
 * -----------------------------------------------------------------------
 */
bool
Job_Empty()
{
    if (nJobs == 0) {
	if (!Lst_IsEmpty(&stoppedJobs) && !aborting) {
	    /*
	     * The job table is obviously not full if it has no jobs in
	     * it...Try and restart the stopped jobs.
	     */
	    jobFull = false;
	    JobRestartJobs();
	    return false;
	} else {
	    return true;
	}
    } else {
	return false;
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobMatchShell --
 *	Find a matching shell in 'shells' given its final component.
 *
 * Results:
 *	A pointer to the Shell structure.
 *-----------------------------------------------------------------------
 */
static Shell *
JobMatchShell(name)
    char	  *name;      /* Final component of shell path */
{
    Shell	  *sh;	      /* Pointer into shells table */
    Shell	  *match;     /* Longest-matching shell */
    char	  *cp1,
		  *cp2;
    char	  *eoname;

    eoname = name + strlen(name);

    match = NULL;

    for (sh = shells; sh->name != NULL; sh++) {
	for (cp1 = eoname - strlen(sh->name), cp2 = sh->name;
	     *cp1 != '\0' && *cp1 == *cp2;
	     cp1++, cp2++) {
		 continue;
	}
	if (*cp1 != *cp2) {
	    continue;
	} else if (match == NULL || strlen(match->name) < strlen(sh->name)) {
	   match = sh;
	}
    }
    return match == NULL ? sh : match;
}

/*-
 *-----------------------------------------------------------------------
 * Job_ParseShell --
 *	Parse a shell specification and set up commandShell, shellPath
 *	and shellName appropriately.
 *
 * Results:
 *	false if the specification was incorrect.
 *
 * Side Effects:
 *	commandShell points to a Shell structure (either predefined or
 *	created from the shell spec), shellPath is the full path of the
 *	shell described by commandShell, while shellName is just the
 *	final component of shellPath.
 *
 * Notes:
 *	A shell specification consists of a .SHELL target, with dependency
 *	operator, followed by a series of blank-separated words. Double
 *	quotes can be used to use blanks in words. A backslash escapes
 *	anything (most notably a double-quote and a space) and
 *	provides the functionality it does in C. Each word consists of
 *	keyword and value separated by an equal sign. There should be no
 *	unnecessary spaces in the word. The keywords are as follows:
 *	    name	    Name of shell.
 *	    path	    Location of shell. Overrides "name" if given
 *	    quiet	    Command to turn off echoing.
 *	    echo	    Command to turn echoing on
 *	    filter	    Result of turning off echoing that shouldn't be
 *			    printed.
 *	    echoFlag	    Flag to turn echoing on at the start
 *	    errFlag	    Flag to turn error checking on at the start
 *	    hasErrCtl	    True if shell has error checking control
 *	    check	    Command to turn on error checking if hasErrCtl
 *			    is true or template of command to echo a command
 *			    for which error checking is off if hasErrCtl is
 *			    false.
 *	    ignore	    Command to turn off error checking if hasErrCtl
 *			    is true or template of command to execute a
 *			    command so as to ignore any errors it returns if
 *			    hasErrCtl is false.
 *-----------------------------------------------------------------------
 */
bool
Job_ParseShell(line)
    char	  *line;  /* The shell spec */
{
    char	  **words;
    int 	  wordCount;
    char	  **argv;
    int 	  argc;
    char	  *path;
    Shell	  newShell;
    bool	  fullSpec = false;

    while (isspace(*line)) {
	line++;
    }

    efree(shellArgv);

    words = brk_string(line, &wordCount, &shellArgv);

    memset(&newShell, 0, sizeof(newShell));

    /*
     * Parse the specification by keyword
     */
    for (path = NULL, argc = wordCount - 1, argv = words;
	 argc != 0;
	 argc--, argv++) {
	     if (strncmp(*argv, "path=", 5) == 0) {
		 path = &argv[0][5];
	     } else if (strncmp(*argv, "name=", 5) == 0) {
		 newShell.name = &argv[0][5];
	     } else {
		 if (strncmp(*argv, "quiet=", 6) == 0) {
		     newShell.echoOff = &argv[0][6];
		 } else if (strncmp(*argv, "echo=", 5) == 0) {
		     newShell.echoOn = &argv[0][5];
		 } else if (strncmp(*argv, "filter=", 7) == 0) {
		     newShell.noPrint = &argv[0][7];
		     newShell.noPLen = strlen(newShell.noPrint);
		 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
		     newShell.echo = &argv[0][9];
		 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
		     newShell.exit = &argv[0][8];
		 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
		     char c = argv[0][10];
		     newShell.hasErrCtl = !(c != 'Y' && c != 'y' &&
					   c != 'T' && c != 't');
		 } else if (strncmp(*argv, "check=", 6) == 0) {
		     newShell.errCheck = &argv[0][6];
		 } else if (strncmp(*argv, "ignore=", 7) == 0) {
		     newShell.ignErr = &argv[0][7];
		 } else {
		     Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
				  *argv);
		     free(words);
		     return false;
		 }
		 fullSpec = true;
	     }
    }

    if (path == NULL) {
	/*
	 * If no path was given, the user wants one of the pre-defined shells,
	 * yes? So we find the one s/he wants with the help of JobMatchShell
	 * and set things up the right way. shellPath will be set up by
	 * Job_Init.
	 */
	if (newShell.name == NULL) {
	    Parse_Error(PARSE_FATAL, "Neither path nor name specified");
	    return false;
	} else {
	    commandShell = JobMatchShell(newShell.name);
	    shellName = newShell.name;
	}
    } else {
	/*
	 * The user provided a path. If s/he gave nothing else (fullSpec is
	 * false), try and find a matching shell in the ones we know of.
	 * Else we just take the specification at its word and copy it
	 * to a new location. In either case, we need to record the
	 * path the user gave for the shell.
	 */
	shellPath = path;
	path = strrchr(path, '/');
	if (path == NULL) {
	    path = shellPath;
	} else {
	    path += 1;
	}
	if (newShell.name != NULL) {
	    shellName = newShell.name;
	} else {
	    shellName = path;
	}
	if (!fullSpec) {
	    commandShell = JobMatchShell(shellName);
	} else {
	    commandShell = emalloc(sizeof(Shell));
	    *commandShell = newShell;
	}
    }

    if (commandShell->echoOn && commandShell->echoOff) {
	commandShell->hasEchoCtl = true;
    }

    if (!commandShell->hasErrCtl) {
	if (commandShell->errCheck == NULL) {
	    commandShell->errCheck = "";
	}
	if (commandShell->ignErr == NULL) {
	    commandShell->ignErr = "%s\n";
	}
    }

    /*
     * Do not free up the words themselves, since they might be in use by the
     * shell specification...
     */
    free(words);
    return true;
}

/*-
 *-----------------------------------------------------------------------
 * JobInterrupt --
 *	Handle the receipt of an interrupt.
 *
 * Side Effects:
 *	All children are killed. Another job will be started if the
 *	.INTERRUPT target was given.
 *-----------------------------------------------------------------------
 */
static void
JobInterrupt(runINTERRUPT, signo)
    int     runINTERRUPT;	/* Non-zero if commands for the .INTERRUPT
				 * target should be executed */
    int     signo;		/* signal received */
{
    LstNode	  ln;		/* element in job table */
    Job 	  *job; 	/* job descriptor in that element */
    GNode	  *interrupt;	/* the node describing the .INTERRUPT target */

    aborting = ABORT_INTERRUPT;

    for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
	job = (Job *)Lst_Datum(ln);

	if (!Targ_Precious(job->node)) {
	    const char	*file = job->node->path == NULL ?
				 job->node->name :
				 job->node->path;
	    if (!noExecute && eunlink(file) != -1) {
		Error("*** %s removed", file);
	    }
	}
#ifdef RMT_WANTS_SIGNALS
	if (job->flags & JOB_REMOTE) {
	    /*
	     * If job is remote, let the Rmt module do the killing.
	     */
	    if (!Rmt_Signal(job, signo)) {
		/*
		 * If couldn't kill the thing, finish it out now with an
		 * error code, since no exit report will come in likely.
		 */
		int status;

		status.w_status = 0;
		status.w_retcode = 1;
		JobFinish(job, &status);
	    }
	} else if (job->pid) {
	    KILL(job->pid, signo);
	}
#else
	if (job->pid) {
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout,
			       "JobInterrupt passing signal to child %d.\n",
			       job->pid);
		(void)fflush(stdout);
	    }
	    KILL(job->pid, signo);
	}
#endif /* RMT_WANTS_SIGNALS */
    }

#ifdef REMOTE
    for (ln = Lst_First(&stoppedJobs); ln != NULL; ln = Lst_Adv(ln)) {
	job = (Job *)Lst_Datum(ln);

	if (job->flags & JOB_RESTART) {
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout, "%s%s",
			       "JobInterrupt skipping job on stopped queue",
			       "-- it was waiting to be restarted.\n");
		(void)fflush(stdout);
	    }
	    continue;
	}
	if (!Targ_Precious(job->node)) {
	    char	*file = job->node->path == NULL ?
				 job->node->name :
				 job->node->path;
	    if (eunlink(file) == 0) {
		Error("*** %s removed", file);
	    }
	}
	/*
	 * Resume the thing so it will take the signal.
	 */
	if (DEBUG(JOB)) {
	    (void)fprintf(stdout,
			   "JobInterrupt passing CONT to stopped child %d.\n",
			   job->pid);
	    (void)fflush(stdout);
	}
	KILL(job->pid, SIGCONT);
#ifdef RMT_WANTS_SIGNALS
	if (job->flags & JOB_REMOTE) {
	    /*
	     * If job is remote, let the Rmt module do the killing.
	     */
	    if (!Rmt_Signal(job, SIGINT)) {
		/*
		 * If couldn't kill the thing, finish it out now with an
		 * error code, since no exit report will come in likely.
		 */
		int status;
		status.w_status = 0;
		status.w_retcode = 1;
		JobFinish(job, &status);
	    }
	} else if (job->pid) {
	    if (DEBUG(JOB)) {
		(void)fprintf(stdout,
		       "JobInterrupt passing interrupt to stopped child %d.\n",
			       job->pid);
		(void)fflush(stdout);
	    }
	    KILL(job->pid, SIGINT);
	}
#endif /* RMT_WANTS_SIGNALS */
    }
#endif

    if (runINTERRUPT && !touchFlag) {
	interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
	if (interrupt != NULL) {
	    ignoreErrors = false;

	    JobStart(interrupt, JOB_IGNDOTS, (Job *)0);
	    while (nJobs) {
		Job_CatchOutput();
#ifndef RMT_WILL_WATCH
		Job_CatchChildren(!usePipes);
#endif /* RMT_WILL_WATCH */
	    }
	}
    }
    (void)eunlink(tfile);
    exit(signo);
}

/*
 *-----------------------------------------------------------------------
 * Job_Finish --
 *	Do final processing such as the running of the commands
 *	attached to the .END target.
 *
 * Results:
 *	Number of errors reported.
 *
 * Side Effects:
 *	The process' temporary file (tfile) is removed if it still
 *	existed.
 *-----------------------------------------------------------------------
 */
int
Job_Finish()
{
    if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
	if (errors) {
	    Error("Errors reported so .END ignored");
	} else {
	    JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);

	    while (nJobs) {
		Job_CatchOutput();
#ifndef RMT_WILL_WATCH
		Job_CatchChildren(!usePipes);
#endif /* RMT_WILL_WATCH */
	    }
	}
    }
    (void)eunlink(tfile);
    return errors;
}

/*-
 *-----------------------------------------------------------------------
 * Job_End --
 *	Cleanup any memory used by the jobs module
 *
 * Side Effects:
 *	Memory is freed
 *-----------------------------------------------------------------------
 */
#ifdef CLEANUP
void
Job_End()
{
    efree(shellArgv);
}
#endif

/*-
 *-----------------------------------------------------------------------
 * Job_Wait --
 *	Waits for all running jobs to finish and returns. Sets 'aborting'
 *	to ABORT_WAIT to prevent other jobs from starting.
 *
 * Side Effects:
 *	Currently running jobs finish.
 *
 *-----------------------------------------------------------------------
 */
void
Job_Wait()
{
    aborting = ABORT_WAIT;
    while (nJobs != 0) {
	Job_CatchOutput();
#ifndef RMT_WILL_WATCH
	Job_CatchChildren(!usePipes);
#endif /* RMT_WILL_WATCH */
    }
    aborting = 0;
}

/*-
 *-----------------------------------------------------------------------
 * Job_AbortAll --
 *	Abort all currently running jobs without handling output or anything.
 *	This function is to be called only in the event of a major
 *	error. Most definitely NOT to be called from JobInterrupt.
 *
 * Side Effects:
 *	All children are killed, not just the firstborn
 *-----------------------------------------------------------------------
 */
void
Job_AbortAll()
{
    LstNode		ln;	/* element in job table */
    Job 		*job;	/* the job descriptor in that element */
    int 		foo;

    aborting = ABORT_ERROR;

    if (nJobs) {
	for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
	    job = (Job *)Lst_Datum(ln);

	    /*
	     * kill the child process with increasingly drastic signals to make
	     * darn sure it's dead.
	     */
#ifdef RMT_WANTS_SIGNALS
	    if (job->flags & JOB_REMOTE) {
		Rmt_Signal(job, SIGINT);
		Rmt_Signal(job, SIGKILL);
	    } else {
		KILL(job->pid, SIGINT);
		KILL(job->pid, SIGKILL);
	    }
#else
	    KILL(job->pid, SIGINT);
	    KILL(job->pid, SIGKILL);
#endif /* RMT_WANTS_SIGNALS */
	}
    }

    /*
     * Catch as many children as want to report in at first, then give up
     */
    while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
	continue;
    (void)eunlink(tfile);
}

#ifdef REMOTE
/*-
 *-----------------------------------------------------------------------
 * JobFlagForMigration --
 *	Handle the eviction of a child. Called from RmtStatusChange.
 *	Flags the child as remigratable and then suspends it.
 *
 * Side Effects:
 *	The job descriptor is flagged for remigration.
 *-----------------------------------------------------------------------
 */
void
JobFlagForMigration(hostID)
    int 	  hostID;	/* ID of host we used, for matching children. */
{
    Job 	  *job; 	/* job descriptor for dead child */
    LstNode	  jnode;	/* list element for finding job */

    if (DEBUG(JOB)) {
	(void)fprintf(stdout, "JobFlagForMigration(%d) called.\n", hostID);
	(void)fflush(stdout);
    }
    jnode = Lst_Find(&jobs, JobCmpRmtID, &hostID);

    if (jnode == NULL) {
	jnode = Lst_Find(&stoppedJobs, JobCmpRmtID, &hostID);
		if (jnode == NULL) {
		    if (DEBUG(JOB)) {
			Error("Evicting host(%d) not in table", hostID);
		    }
		    return;
		}
    }
    job = (Job *)Lst_Datum(jnode);

    if (DEBUG(JOB)) {
	(void)fprintf(stdout,
		       "JobFlagForMigration(%d) found job '%s'.\n", hostID,
		       job->node->name);
	(void)fflush(stdout);
    }

    KILL(job->pid, SIGSTOP);

    job->flags |= JOB_REMIGRATE;
}

#endif

/*-
 *-----------------------------------------------------------------------
 * JobRestartJobs --
 *	Tries to restart stopped jobs if there are slots available.
 *	Note that this tries to restart them regardless of pending errors.
 *	It's not good to leave stopped jobs lying around!
 *
 * Side Effects:
 *	Resumes(and possibly migrates) jobs.
 *-----------------------------------------------------------------------
 */
static void
JobRestartJobs()
{
    Job *job;

    while (!jobFull && (job = (Job *)Lst_DeQueue(&stoppedJobs)) != NULL) {
	if (DEBUG(JOB)) {
	    (void)fprintf(stdout,
		       "Job queue is not full. Restarting a stopped job.\n");
	    (void)fflush(stdout);
	}
	JobRestart(job);
    }
}