File: startpar.c

package info (click to toggle)
startpar 0.64-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 224 kB
  • sloc: ansic: 2,061; makefile: 87; sh: 59; cpp: 16
file content (1617 lines) | stat: -rw-r--r-- 36,209 bytes parent folder | download
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
/* Copyright (c) 2003 SuSE Linux AG
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *  
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program (see the file COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 ****************************************************************
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif

#ifdef SUSE
# define USE_PRELOAD
# undef  CHECK_FORDEVPTS
#else
# undef  USE_PRELOAD
# define CHECK_FORDEVPTS
#endif
#ifdef __FreeBSD__
#undef CHECK_FORDEVPTS
#endif
#include <stdio.h>
#include <termios.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#ifndef __FreeBSD__
#include <sys/sysinfo.h>
#endif
#include <sys/stat.h>
#include <sys/mman.h>
#ifdef CHECK_FORDEVPTS
# include <sys/vfs.h>
#endif
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef USE_BLOGD
# include <libblogger.h>
#else
# define bootlog(arg...)
# define closeblog()
#endif
#include "makeboot.h"
#include "proc.h"

#if !defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L)
# ifndef  inline
#  define inline		__inline__
# endif
# ifndef  restrict
#  define restrict		__restrict__
# endif
# ifndef  volatile
#  define volatile		__volatile__
# endif
# ifndef  extension
#  define extension		__extension__
# endif
#endif
#ifndef  attribute
# define attribute(attr)	__attribute__(attr)
#endif

#ifdef __FreeBSD__
# define TEMP_FAILURE_RETRY(expression) \
  (__extension__                                                              \
    ({ long int __result;                                                     \
       do __result = (long int) (expression);                                 \
       while (__result == -1L && errno == EINTR);                             \
       __result; }))
#endif

typedef enum _boolean {false, true} boolean;
extern char *optarg;
extern int optind;

static long int numcpu = -1;
static char *myname;
static struct termios tio;
static volatile struct winsize wz;
static struct {
  char env_row[128];
  char env_col[128];
} sz;
static sig_atomic_t wzok;
static char *arg;
static boolean isstart;
static struct sigaction sa;
static struct timeval glastio;
static struct timeval now;
static struct timeval lastlim;
static char *run_mode = NULL;
static struct makenode **nodevec;
static sig_atomic_t signaled;
const char *initddir = "/etc/init.d";
const char *etcdir = "/etc";

#define WRITE_TO_FD 2

#ifndef PATH_MAX
#define PATH_MAX 2048
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

#define PBUF_SIZE	8192
#define PRUNNING	0x0001
#define PFINISHED	0x0002
struct prg {
  const char *name;
  const char *arg0;
  int num;
  int fd;
  pid_t pid;
  struct timeval lastio;
  int splashadd;
  int status;
  int flags;
  size_t len;
  char buf[PBUF_SIZE];
};

static struct prg *prgs;
static int inpar, par;
static double iorate = 800.0;
int print_program_name = FALSE;

#ifdef USE_PRELOAD
static volatile enum { Unknown, Preload, NoPreload } ispreload = Unknown;

static void sighandler_nopreload(int x attribute((unused)))
{
    ispreload = NoPreload;
}

static void sighandler_preload(int x attribute((unused)))
{
    ispreload = Preload;
}

# define SOCK_PATH "/dev/shm/preload_sock"
#endif

void *xcalloc(size_t nmemb, size_t size)
{
  void *r;
  if ((r = (void *)calloc(nmemb, size)) == 0)
    {
      fprintf(stderr, "calloc: out of memory\n");
      exit(1);
    }
  return r;
}

static int splashpos = -1;
static char *splashcfg;

int calcsplash(int x, int n, char *opt)
{
  char *p;
  int i;
  int r, d;

  if (opt == 0)
    return -1;
  for (i = 0; i <= x; i++)
    {
      if ((p = strchr(opt, ':')) == 0)
        break;
      if (i == x)
	return atoi(opt);
      opt = p + 1;
    }
  r = atoi(opt);
  n -= i;
  for (;; i++, n--)
    {
      if (n < 1)
	n = 1;
      d = r / n;
      if (i == x)
	return d;
      r -= d;
    }
}

pid_t splashpid;

void waitsplash()
{
  int status;
  if (!splashpid)
    return;
  TEMP_FAILURE_RETRY(waitpid(splashpid, &status, 0));
}

void closeall(void)
{
  int s;

  if (!prgs)
    return;
  for (s = 0; s < par; s++)
    if (prgs[s].fd)
      close(prgs[s].fd);
  closeblog();
}

void callsplash(int n, const char *path, char *action)
{
  const char *p;
  char sbuf[32];
  char tbuf[256];
  pid_t pid;
  struct stat stb;
  sigset_t nmask;

  if (n < 0 || splashpos < 0)
    return;
  if (splashpos + n > 65535)
    n = 65535 - splashpos;
  splashpos += n;
  if (stat("/proc/splash", &stb))
     return;
  p = strrchr(path, '/');
  if (p)
    path = p + 1;
  for (p = path; *p; p++)
    if ((*p == 'S' || *p == 'K') && p[1] >= '0' && p[1] <= '9' && p[2] >= '0' && p[2] <= '9' && p[3])
      break;
  if (*p)
    p += 3;
  else
    p = path;
  if (!action)
    action = "";
  if (strlen(p) + strlen(action) + 2 > sizeof(tbuf))
    return;
  sprintf(tbuf, "%s%s%s", p, *action ? " " : "", action);
  sprintf(sbuf, "%d:%d", splashpos - n, n);
  waitsplash();
  pid = fork();
  if (pid == (pid_t)-1)
    return;
  if (pid)
    {
      splashpid = pid;
      return;
    }

  (void)sigfillset(&nmask);
  sigprocmask(SIG_UNBLOCK, &nmask, NULL);

  (void)signal(SIGHUP,  SIG_DFL);
  (void)signal(SIGQUIT, SIG_DFL);
  (void)signal(SIGSEGV, SIG_DFL);
  (void)signal(SIGTERM, SIG_DFL);
  (void)signal(SIGCHLD, SIG_DFL);
  (void)signal(SIGTTIN, SIG_DFL);
  (void)signal(SIGTTOU, SIG_DFL);

  TEMP_FAILURE_RETRY(dup2(2, 1));
  closeall();
  execl("/sbin/splash", "splash", "-p", sbuf, "-t", tbuf, splashcfg, (char *)0);
  _exit(1);
}

void writebuf(struct prg *p)
{
  char *b = p->buf;
  int r;

  #ifdef DEBUG
  fprintf(stderr, "About to write buf\n");
  #endif
  if ( (print_program_name) && (p->name) && (p->len > 0) )
  { 
     char *temp_name;
     int status;

     status = asprintf(&temp_name, "%s: ", p->name);
     if (status >= 0)
     {
        write(WRITE_TO_FD, temp_name, status);
        free(temp_name);
     }
  }
  while (p->len > 0)
    {
      r = write(WRITE_TO_FD, b, p->len);
      if (r < 0)
      {
	  if (errno == EINTR)
	    continue;
	  perror("write");
	  r = p->len;
      }
      else
      {
          /* make sure we finish output with a newline */
          if (b[p->len - 1] != '\n')
             write(WRITE_TO_FD, "\n", 2);
      }
      p->len -= r;
      b += r;
    }
  glastio = now;
}

static int checksystem(const int par, const boolean start, const boolean limit)
{
  const      int pg_size       = sysconf(_SC_PAGESIZE);
  #ifdef __FreeBSD__
  const long int minphys_bytes = (2<<21);
  const long int avphys_pg = 10;
  #else
  const long int minphys_bytes = (sysconf(_SC_LONG_BIT) > 32L) ? (2<<22) : (2<<21);
  const long int avphys_pg     = sysconf(_SC_AVPHYS_PAGES);
  #endif
  long int minphys_pg;
  unsigned long int prcs_run, prcs_blked;
  int newpar;
  
  if (avphys_pg < 0)
    return 1;

  if (pg_size < 0)
    return par;

  if (!start)
    minphys_pg = avphys_pg;
  else
    minphys_pg = minphys_bytes / pg_size;

  if (avphys_pg < minphys_pg)
    return 1;

  if (numcpu < 1)
    return par;
  
  if (!limit)
    return (par*numcpu);

  if (read_proc(&prcs_run, &prcs_blked))
    return par;

#ifdef USE_PRELOAD
  /* if we have preload running, we expect I/O not to be a problem */
  if (ispreload != NoPreload)
    prcs_blked = 0;
#endif

  newpar  = (par*numcpu) - (prcs_run + prcs_blked);
  newpar -= ((int)(((double)prcs_blked)*iorate))/1000;	/* I/O load reduction */

#if DEBUG
  fprintf(stderr, "checksystem par=%d newpar=%d (prcs_run=%lu) %ld\n", par, newpar, prcs_run, time(0));
#endif
  if (newpar <= 0)
    return 1;
  else
    return newpar;
}

static inline int checklimit(const int par, const boolean start)
{
  return checksystem(par, start, true);
}

static inline int checkpar(const int par, const boolean start)
{
  return checksystem(par, start, false);
}

#ifdef CHECK_FORDEVPTS
/*
 * Based on __posix_openpt() from glibc.  Reimplemented here to work
 * around the problem with getpt() failing for the entire process life
 * time if /dev/pts/ is missing the first time it is called but
 * mounted while the process is running.  BSD style pts is not
 * supported, but might be copied from glibc too if there is need.
 */
# define DEVFS_SUPER_MAGIC       0x1373
# define DEVPTS_SUPER_MAGIC      0x1cd1

static int startpar_getpt(void) {
  int fd = open("/dev/ptmx", O_RDWR|O_NOCTTY);

  if (fd != -1)
    {
      struct statfs fsbuf;

      /* Check that the /dev/pts filesystem is mounted
        or if /dev is a devfs filesystem (this implies /dev/pts).  */
      if ((statfs ("/dev/pts", &fsbuf) == 0
             && fsbuf.f_type == DEVPTS_SUPER_MAGIC)
         || (statfs ("/dev", &fsbuf) == 0
             && fsbuf.f_type == DEVFS_SUPER_MAGIC))
        {
          /* Everything is ok, switch to the getpt() in libc.  */
          return fd;
        }

      /* If /dev/pts is not mounted then the UNIX98 pseudo terminals
        are not usable.  */
      close (fd);
    }

  return -1;
}

static int checkdevpts(void)
{
  int ptsfd = startpar_getpt();

  if (ptsfd == -1)
    {
      #ifdef DEBUG
      fprintf(stderr, "No PT found\n");
      #endif
      return 0;
    }
  else if (ptsname(ptsfd) == 0 || grantpt(ptsfd) || unlockpt(ptsfd))
    {
      #ifdef DEBUG
      fprintf(stderr, "Error getting PT\n");
      #endif
      close(ptsfd);
      return 0;
    }
  else
    {
      #ifdef DEBUG
      fprintf(stderr, "PT found\n");
      #endif
      close(ptsfd);
      return 1;
    }
}
#else
static int attribute((unused)) checkdevpts(void)
{
  return 1;	/* /dev/pts is always mounted */
}
#endif

void run(struct prg *p)
{
  const char * m = (char*)0;
  sigset_t nmask;
#ifdef USE_PRELOAD
  pid_t parent;
#endif

  p->len = 0;
  p->pid = (pid_t)0;
  #ifndef __FreeBSD__
  p->fd = getpt();
  #endif
  if (p->fd <= 0)
    {
      p->fd = 0;
      perror("getpt");
      fprintf(stderr, "could not get pty for %s\n", p->name);
    }
  else if ((m = ptsname(p->fd)) == 0 || grantpt(p->fd) || unlockpt(p->fd))
    {
      fprintf(stderr, "could not init pty for %s\n", p->name);
      close(p->fd);
      p->fd = 0;
    }
#ifdef USE_PRELOAD
  parent = getpid();
#endif
  if ((p->pid = fork()) == (pid_t)-1)
    {
      perror("fork");
      fprintf(stderr, "could not fork %s\n", p->name);
      p->pid = (pid_t)0;
      if (p->fd)
	{
	  close(p->fd);
	  p->fd = 0;
	}
      p->status = 0;
      p->flags = 0;
      return;
    }
  if (p->pid != 0)
    {
      p->flags |= PRUNNING;
      return;
    }

  (void)sigfillset(&nmask);
  sigprocmask(SIG_UNBLOCK, &nmask, NULL);

  (void)signal(SIGHUP,  SIG_DFL);
  (void)signal(SIGQUIT, SIG_DFL);
  (void)signal(SIGSEGV, SIG_DFL);
  (void)signal(SIGTERM, SIG_DFL);
  (void)signal(SIGCHLD, SIG_DFL);
  (void)signal(SIGTTIN, SIG_DFL);
  (void)signal(SIGTTOU, SIG_DFL);

  if (setpgid(0, 0))
    perror("setpgid");

  if (m && p->fd)
    {
      sigset_t smask, omask;
      TEMP_FAILURE_RETRY(close(1));
      if (open(m, O_RDWR) != 1)
	{
	  perror(m);
	  _exit(1);
	}
      TEMP_FAILURE_RETRY(dup2(1, 2));
      sigemptyset(&smask);
      sigaddset(&smask, SIGTTOU);
      sigprocmask(SIG_BLOCK, &smask, &omask);
      if (tcsetattr(1, TCSANOW, &tio) && errno != ENOTTY)
	perror("tcsetattr");
      sigprocmask(SIG_SETMASK, &omask, NULL);
      if (wzok)
	ioctl(1, TIOCSWINSZ, &wz);
      putenv(sz.env_row);
      putenv(sz.env_col);
    }
  else
    {
      TEMP_FAILURE_RETRY(dup2(2, 1));
    }

  closeall();

#ifdef USE_PRELOAD
  if (arg && !strcmp(arg, "start")) 
    { 
      int s;

      if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) != -1)
	{
	  struct sockaddr_un remote;
	  pid_t child;
	  int t, len;

	  memset(&remote, 0, sizeof(struct sockaddr_un));
	  remote.sun_family = AF_UNIX;
	  strcpy(remote.sun_path, SOCK_PATH);
	  len = strlen(remote.sun_path) + sizeof(remote.sun_family);

	  if ((t = connect(s, (struct sockaddr *)&remote, len)) != -1)
	    {
	      char str[100];
	      if (ispreload != Preload)
		kill(parent, SIGUSR1);
	      send(s, p->name, strlen(p->name), 0);
	      recv(s, str, sizeof(str), 0);
	    } 
	  else if (ispreload == Unknown) 
	    {
	      /*
	       * if we connected to preload once, we know it ran.
	       * In case we can't connect to it later, it means it did
	       * its job and we can guess I/O is no longer a problem. 
	       */
	      kill(parent, SIGUSR2);
	    }
	  close(s);
	  /*
	   * if we use preload, we fork again to make bootcharts easier to read.
	   * The reason is that the name of the init script will otherwise be used
	   * when in reality the above code waited for preload. If we fork away
	   * before the exec, the waiting code will be folded into startpar
	   */
	  if ((child = fork()))
	    {
	      int status;
	      int ret = waitpid(child, &status, 0);
	      if (ret == -1)
		perror("waitpid");
	      exit(WEXITSTATUS(status));
	    }
	}
    }
#endif

  if (run_mode)
    {
      char path[PATH_MAX];
      snprintf(path, PATH_MAX, "%s/%s", initddir, p->name);
      execlp(path, p->arg0, arg, (char *)0);
    }
  else if (arg)
    execlp(p->name, p->arg0, arg, (char *)0);
  else
    execlp(p->name, p->arg0, (char *)0);
  perror(p->name);
  _exit(1);
}

int run_single(const char *prg, const char *arg0, int spl)
{
  pid_t pid;
  int r;

  #ifdef DEBUG
  fprintf(stderr, "Running interactive, single task.\n");
  #endif

  if ((pid = fork()) == (pid_t)-1)
    {
      perror("fork");
      fprintf(stderr, "could not fork %s\n", prg);
      return 1;
    }

  if (pid == 0)
    {
      sigset_t nmask;

      (void)sigfillset(&nmask);
      sigprocmask(SIG_UNBLOCK, &nmask, NULL);

      (void)signal(SIGINT,  SIG_DFL);	/* Interactive init scripts may be interrupted */
      (void)signal(SIGHUP,  SIG_DFL);
      (void)signal(SIGQUIT, SIG_DFL);
      (void)signal(SIGSEGV, SIG_DFL);
      (void)signal(SIGTERM, SIG_DFL);
      (void)signal(SIGCHLD, SIG_DFL);
      (void)signal(SIGTTIN, SIG_DFL);
      (void)signal(SIGTTOU, SIG_DFL);

      TEMP_FAILURE_RETRY(dup2(2, 1));
      closeall();
      if (run_mode)
	{
	  char path[PATH_MAX];
	  snprintf(path, PATH_MAX, "%s/%s", initddir, prg);
	  execlp(path, arg0 ? arg0 : path, arg, (char *)0);
	}
      else if (arg)
	execlp(prg, arg0 ? arg0 : prg, arg, (char *)0);
      else
	execlp(prg, arg0 ? arg0 : prg, (char *)0);
      perror(prg);
      _exit(1);
    }

   TEMP_FAILURE_RETRY(waitpid(pid, &r, 0));
   callsplash(spl, prg, arg);
   return WIFEXITED(r) ? WEXITSTATUS(r) : (WIFSIGNALED(r) ? 1 : 255);
}

void do_forward(void)
{
  char buf[4096], *b;
  ssize_t r, rr;
  setsid();
  while ((r = read(0, buf, sizeof(buf))))
    {
      if (r < 0)
	{
	  if (errno == EINTR)
	    continue;
#if defined(DEBUG) && (DEBUG > 0)
	  perror("\n\rstartpar: forward read");
#endif
	  break;
	}
      b = buf;
      while (r > 0)
	{
	  rr = write(1, b, r);
	  if (rr < 0)
	    {
	      if (errno == EINTR)
		continue;
	      perror("\n\rstartpar: forward write");
	      rr = r;
	    }
	  r -= rr;
	  b += rr;
	}
    }
  _exit(0);
}

static char *gtimo_buf;
static size_t gtimo_bufsize;
static size_t gtimo_buflen;

void storebuf(struct prg *p)
{
  if ((gtimo_buflen + p->len) > gtimo_bufsize)
  {
      writebuf(p);				/* In case of overflow or memory shortage */
      return;
  }

  (void)memcpy(gtimo_buf + gtimo_buflen, p->buf, p->len);
  gtimo_buflen += p->len;
  p->len = 0;
  glastio = now;
}

void flushbuf(struct prg *p)
{
  size_t len = gtimo_buflen;
  char * buf = gtimo_buf;

  if (!buf)
	return;					/* In case of memory shortage */

  #ifdef DEBUG
  fprintf(stderr, "About to flush buf\n");
  #endif
  if ( (print_program_name) && (len > 0) && (p->name) )
  {
      char *temp_name;
      int status;
      status = asprintf(&temp_name, "%s: ", p->name);
      if (status >= 0)
      {
          write(WRITE_TO_FD, temp_name, status);
          free(temp_name);
      }
  }
  while (len > 0)
    {
      int r = write(WRITE_TO_FD, buf, len);
      if (r < 0)
      {
	  perror("write");
	  r = len;
      }
      else
      {
         /* make sure we finish output with a newline */
         if (buf[len - 1] != '\n')
            write(WRITE_TO_FD, "\n", 2);
      }
      len -= r;
      buf += r;
    }
  gtimo_buflen = 0;
  *gtimo_buf = 0;
}

#define GTIMO_OFFL	0
#define GTIMO_USED	1

void detach(struct prg *p, const int store)
{
  int flags = fcntl(p->fd, F_GETFL);
  ssize_t r;
  pid_t pid;

  if (flags > 0)
    flags |= FNONBLOCK;
  else
    flags = FNONBLOCK;

  if (-1 == fcntl(p->fd, F_SETFL, flags))
    {
      perror("unable to set FNONBLOCK flag on program file descriptor");
    }
  while ((r = read(p->fd, p->buf, sizeof(p->buf))))
    {
      if (r < 0)
	{
	  if (errno == EINTR)
	    continue;
	  break;
	}
      p->len = r;
      if (store)
	storebuf(p);
      else
	writebuf(p);
    }
  flags &= ~FNONBLOCK;
  if (-1 == fcntl(p->fd, F_SETFL, flags))
    {
      perror("unable to unset FNONBLOCK flag on program file descriptor");
    }
  if (r == -1 && errno == EWOULDBLOCK)
    {
      if ((pid = fork()) == 0)
	{
	  sigset_t nmask;
	  (void)sigfillset(&nmask);
	  sigprocmask(SIG_UNBLOCK, &nmask, NULL);

	  (void)signal(SIGINT,  SIG_DFL);   /* some interactive services may be interruptable */
	  (void)signal(SIGHUP,  SIG_DFL);
	  (void)signal(SIGQUIT, SIG_DFL);
	  (void)signal(SIGSEGV, SIG_DFL);
	  (void)signal(SIGTERM, SIG_DFL);
	  (void)signal(SIGCHLD, SIG_DFL);
	  (void)signal(SIGTTIN, SIG_DFL);
	  (void)signal(SIGTTOU, SIG_DFL);

	  TEMP_FAILURE_RETRY(dup2(p->fd, 0));
	  TEMP_FAILURE_RETRY(dup2(2, 1));
	  closeall();

	  execlp(myname, myname, "-f", "--", p->name, NULL);
	  do_forward();
	}
      if (pid == -1)
	perror("fork");
    }
  close(p->fd);
  p->fd = 0;
}

static struct prg *interactive_task = NULL;
static volatile int active;
static void sigchld(int sig attribute((unused)))
{
  const int old_errno = errno;
  int status;
  pid_t pid;
 
  while ((pid = waitpid(-1, &status, WNOHANG|WUNTRACED)) != 0)
    {
      int s;

      if (errno == ECHILD)
	break;

      if (pid < 0)
	continue;

      if (pid == splashpid)
	{
	  splashpid = (pid_t)0;
	  continue;
	}

      for (s = 0; s < par; s++)
	{
	  struct prg * p = prgs + s;
	  if (p == interactive_task)
	    continue;
	  if (p->pid != pid)
	    continue;
	  if (p->flags & PRUNNING)
	    {
	      p->status = status;
	      p->flags |= PFINISHED;
	      break;
	    }
	}
    }

  signaled = 1;
  errno = old_errno;
}

static void sigwinch(int sig attribute((unused)))
{
  if (ioctl(0, TIOCGWINSZ, &wz) < 0)
    {
      wzok = 0;
      return;
    }
  if (wz.ws_row == 0) wz.ws_row = 24;
  if (wz.ws_col == 0) wz.ws_col = 80;
  snprintf(sz.env_row, sizeof(sz.env_row), "LINES=%d",   wz.ws_row);
  snprintf(sz.env_col, sizeof(sz.env_col), "COLUMNS=%d", wz.ws_col);
  kill(-1, SIGWINCH);
}

static long timerdiff(const struct timeval n,const struct timeval l)
{
    return (((n).tv_sec-(l).tv_sec)*1000)+(((n).tv_usec-(l).tv_usec)/1000);
}

void usage(int status)
{
  fprintf(stderr, "usage: startpar [options] [-a arg] prgs\n");
  fprintf(stderr, "           run given programs parallel\n");
  fprintf(stderr, "       startpar [options] [-P prev] [-R run] [-S <start>:<num>] -M mode\n");
  fprintf(stderr, "           run parallel with Makefile\n");
  fprintf(stderr, "       startpar -v\n");
  fprintf(stderr, "           show version number\n");
  fprintf(stderr, "general options:\n");
  /*
  fprintf(stderr, "       -l use legacy /etc/init.d path for Makefile-style scripts\n");
  fprintf(stderr, "          The default is to use the location /lib/insserv\n");
  */
  fprintf(stderr, "       -n prefix output with name of program displaying output\n");
  fprintf(stderr, "       -p parallel tasks\n");
  fprintf(stderr, "       -t I/O timeout\n");
  fprintf(stderr, "       -T global I/O timeout\n");
  fprintf(stderr, "       -f copy stdin to stdout without running any programs\n");
  fprintf(stderr, "       -e set the location of etc directory (default is /etc)\n");
  exit(status);
}

int main(int argc, char **argv)
{
  int gtimo = -1;
  int timo = -1;
  int isgtimo;
  int forw = 0;
  int c, i, num;
  int limit;
  int notty = 0;
  int *resvec;
  struct timeval tv;
  struct prg *p;
  struct prg *gtimo_running = 0;
  char *prev_level = getenv("PREVLEVEL");
  char *run_level = getenv("RUNLEVEL");
  char *splashopt = 0;
  sigset_t nmask, omask, smask;
  int status;     /* check if parsing makefile worked */

  detect_consoles();

  (void)sigemptyset(&nmask);
  (void)sigaddset(&nmask, SIGHUP);
  sigprocmask(SIG_UNBLOCK, &nmask, NULL);

  (void)signal(SIGINT,  SIG_IGN);	/* Init scripts should not be interruptible */
  (void)signal(SIGCHLD, SIG_DFL);
  numcpu = sysconf(_SC_NPROCESSORS_ONLN);
  myname = argv[0];

  while ((c = getopt(argc, argv, "fhnp:t:T:a:M:P:R:S:vi:e:d:")) != EOF)
    {
      switch(c)
        {
        case 'n':
          print_program_name = TRUE;
          break;
	case 'p':
	  par = atoi(optarg);
	  break;
	case 't':
	  timo = atoi(optarg);
	  break;
	case 'T':
	  gtimo = atoi(optarg);
	  break;
	case 'f':
	  forw = 1;
	  break;
	case 'a':
	  arg = optarg;
	  break;
	case 'd':
	  initddir = optarg;
	  break;
        case 'e':
          etcdir = optarg;
          break;
	case 'M':
	  run_mode = optarg;
	  break;
	case 'P':
	  prev_level = optarg;
	  break;
	case 'R':
	  run_level = optarg;
	  break;
	case 'S':
	  splashopt = optarg;
	  break;
	case 'v':
	  printf("startpar version %s\n", VERSION);
	  exit(0);
	case 'i':
	  iorate = atof(optarg);
	  if (iorate < 0.0)
	    iorate = 800.0;
	  break;
	case 'h':
	  usage(0);     /* usage does not return, no need for break */
	default:
	  usage(1);
        }
    }
  if (forw)
    do_forward();
  argc -= optind;
  argv += optind;

  if (splashopt)
    {
      char *so = strchr(splashopt, ':');
      if (!so)
	splashopt = 0;
      else
	{
	  splashpos = atoi(splashopt);
	  splashopt = so + 1;
	}
      splashcfg = getenv("SPLASHCFG");
      if (!splashcfg)
	{
	  splashpos = -1;
	  splashopt = 0;
	}
    }
  if (run_mode)
    {
      char makefile[PATH_MAX];
      if (!strcmp(run_mode, "boot"))
	arg = "start";
      else if (!strcmp(run_mode, "halt"))
	arg = "stop";
      else if (!strcmp(run_mode, "start") || !strcmp(run_mode, "stop"))
	{
	  arg = run_mode;
	  if (!prev_level || !run_level)
	    {
	      fprintf(stderr, "You must specify previous and next runlevels\n");
	      exit(1);
	    }
	}
      else
	{
	  fprintf(stderr, "invalid run mode %s\n", run_mode);
	  exit(1);
	}
      snprintf(makefile, PATH_MAX, "%s/.depend.%s", initddir, run_mode);
      status = parse_makefile(makefile);
      if (! status) 
      {
         fprintf(stderr, "Unable to run scripts using dependency information in %s\n",
                 initddir);
         exit(1);      /* no other place to try so drop out */
      }

      check_run_files(run_mode, prev_level, run_level);

      argc = tree_entries;			/* number of handled scripts */
      isstart = !strcmp(arg, "start");

      if (argc == 0)
	exit(0);

      if (par == 0)
	par = 8;
      if (par > argc)				/* not more than the number of all scripts */
	par = argc;

      inpar = par;			/* the original argument of parallel procs per cpu */

      par = checkpar(inpar, isstart);		/* the number of parallel procs on all cpu's */

      if (par > argc)				/* not more than the number of all scripts */
	par = argc;

      nodevec = xcalloc(argc, sizeof(*nodevec));
    }
  else
    {
      if (par < 0)
	usage(1);

      if (arg)
	isstart = !strcmp(arg, "start");

      if (argc == 0)
	exit(0);

      if (par == 0)
	par = argc;
      if (par > argc)				/* not more than the number of all scripts */
	par = argc;

      inpar = par;				/* the original argument of parallel procs per cpu */

      par = checkpar(inpar, isstart);		/* the number of parallel procs on all cpu's */

      if (par > argc)				/* not more than the number of all scripts */
	par = argc;
    }

  num = 0;
  resvec = (int *)xcalloc(argc, sizeof(int));
  for (i = 0; i < argc; i++)
    resvec[i] = 255;

  if (argc == 1)
    {
      if (run_mode)
	{
	  if ((*nodevec = pickup_task()))
	  {
            #ifdef DEBUG
            fprintf(stderr, "About to run single task in run mode %s\n", run_mode);
            #endif
	    *resvec = run_single((*nodevec)->name, (*nodevec)->arg0, calcsplash(0, 1, splashopt));
	    finish_task(*nodevec);
	  }
      } else
        {
            #ifdef DEBUG
            fprintf(stderr, "About to run single task with no devec\n");
            #endif
	   *resvec = run_single(*argv, *argv, calcsplash(0, 1, splashopt));
        }
      goto finished;
    }

  prgs = (struct prg *)xcalloc(par, sizeof *prgs);
  gtimo_bufsize = par * PBUF_SIZE;
  gtimo_buf = (char *) calloc(gtimo_bufsize, sizeof(char));
  if (!gtimo_buf)
    gtimo_bufsize = 0;				/* Accept error due memory shortage */

  sa.sa_handler = sigwinch;
  sa.sa_flags = SA_RESTART|SA_NODEFER;
  (void)sigemptyset(&sa.sa_mask);
  if (sigaction(SIGWINCH, &sa, 0))
    {
      perror("sigwinch sigaction");
      exit(1);
    }

  if (tcgetattr(0, &tio))
    {
      if (errno != ENOTTY)
	perror("tcgetattr");
      tcgetattr(2, &tio);
      if (errno == ENOTTY)
	notty = 1;
    }
  cfmakeraw(&tio);
  tio.c_lflag &= ~ECHO;
  tio.c_lflag |= ISIG;
  tio.c_cc[VTIME] = 0;
  tio.c_cc[VMIN]  = CMIN;

  if (ioctl(0, TIOCGWINSZ, &wz) == 0)
    wzok = 1;
  if (wz.ws_row == 0) wz.ws_row = 24;
  if (wz.ws_col == 0) wz.ws_col = 80;

  strcat(&sz.env_row[0], "LINES=");
  strcat(&sz.env_col[0], "COLUMNS=");
  snprintf(sz.env_row, sizeof(sz.env_row), "LINES=%d",   wz.ws_row);
  snprintf(sz.env_col, sizeof(sz.env_col), "COLUMNS=%d", wz.ws_col);

  sa.sa_handler = sigchld;
  sa.sa_flags = SA_RESTART;
  (void)sigemptyset(&sa.sa_mask);
  (void)sigaddset(&sa.sa_mask, SIGCHLD);
  (void)sigaddset(&sa.sa_mask, SIGWINCH);
  (void)sigaddset(&sa.sa_mask, SIGUSR1);
  (void)sigaddset(&sa.sa_mask, SIGUSR2);
  if (sigaction(SIGCHLD, &sa, 0))
    {
      perror("sigchld sigaction");
      exit(1);
    }

#ifdef USE_PRELOAD
  sa.sa_handler = sighandler_preload;
  sa.sa_flags = SA_RESTART;
  (void)sigemptyset(&sa.sa_mask);
  if (sigaction(SIGUSR1, &sa, 0))
    {
      perror("sigusr1(preload) sigaction");
      exit(1);
    }

  sa.sa_handler = sighandler_nopreload;
  sa.sa_flags = SA_RESTART;
  (void)sigemptyset(&sa.sa_mask);
  if (sigaction(SIGUSR2, &sa, 0))
    {
      perror("sigusr2(preload) sigaction");
      exit(1);
    }
#endif

#if defined(__linux__)
  /* lock us into memory */
  if (geteuid() == 0)
    mlockall(MCL_CURRENT|MCL_FUTURE);
#endif
  errno = 0;

  gettimeofday(&glastio, 0);
  limit = checklimit(inpar, isstart);
  lastlim = glastio;

  (void)sigemptyset(&nmask);
  (void)sigaddset(&nmask, SIGCHLD);
  sigprocmask(SIG_BLOCK, &nmask, &omask);

  (void)sigfillset(&smask);
  (void)sigdelset(&smask, SIGHUP);
  (void)sigdelset(&smask, SIGINT);
  (void)sigdelset(&smask, SIGQUIT);
  (void)sigdelset(&smask, SIGTERM);
  (void)sigdelset(&smask, SIGCHLD);

  for (;;)
    {
#ifdef CHECK_FORDEVPTS
      int devpts = checkdevpts();
#endif
      int maxfd = -1;
      int last = -1;
      int r, s;
      long diff;
      pid_t pid;
      fd_set rset;

      gettimeofday(&now, 0);
      pid = (pid_t)-1;
      FD_ZERO(&rset);
      tv = now;

      if ((diff = timerdiff(now, lastlim)) >= 300 || diff < 0)
	{
#if DEBUG
	  fprintf(stderr, "%d: doing checklimit after %ldms %ld\n", getpid(), diff, time(0));
#endif
	  if ((limit = checklimit(inpar, isstart)) > argc)
	    limit = argc;			/* not more than the number of all scripts */
	  lastlim = now;
	  diff = 0;
	} 
#if DEBUG
      fprintf(stderr, "par=%d, inpar=%d, limit=%d (diff=%ld)\n", par, inpar, limit, diff);
#endif
      for (s = 0; s < par; s++)			/* never leave this with break!! */
	{
	  p = prgs + s;
	  if (p == interactive_task)
	    continue;				/* don't count this here */
	  if (p->fd == 0)
	    {
	      if (interactive_task)
		continue;			/* dont't start new processes */
	      if (num >= argc)
		continue;			/* nothing to do */
	    redo:
	      if (p->pid == 0)
		{
		  if (active >= limit)
		    continue;			/* load balancing */
		  if (run_mode)
		    {
		      if ((nodevec[num] = pickup_task()) == NULL)
			continue;
		      if (nodevec[num]->interactive)
			interactive_task = p;
		      p->name = nodevec[num]->name;
		      p->arg0 = nodevec[num]->arg0 ? nodevec[num]->arg0 : nodevec[num]->name;
		    }
		  else {
		    p->name = *argv++;
		    p->arg0 = p->name;
		  }
		  p->splashadd = calcsplash(num, argc, splashopt);
		  p->num = num++;
#ifdef CHECK_FORDEVPTS
		  if (!devpts)
                  {
                      #ifdef DEBUG
                      fprintf(stderr, "No devpts. Setting interactive.\n");
                      #endif
		      interactive_task = p;	/* no /dev/pts, treat as interactive */
                  }
#endif
		  if (notty)
                  {
                    #ifdef DEBUG
                    fprintf(stderr, "No tty available. Set as interactive.\n");
                    #endif
		    interactive_task = p;	/* no tty, treat as interactive */
                  }
		  if (interactive_task)
		    continue;			/* don't start this here */
		  run(p);
		  if (p->pid == 0)
		    {
		      resvec[p->num] = 1;
		      if (run_mode)
			finish_task(nodevec[p->num]);
		      p->status = 0;
		      p->flags = 0;
		      if (p->fd)
			{
			  close(p->fd);
			  p->fd = 0;
			}
		      goto redo;		/* this one is free again */
		    }
		  else
		    {
		      active++;			/* count this active job */
		    }
		  gettimeofday(&now, 0);
		  tv = now;
		}
	    }

	  FD_SET(p->fd, &rset);
	  if (p->fd > maxfd)
	    maxfd = p->fd;

	  if (p->len == 0)
	    continue;
          if ((last < 0) || timercmp(&tv,&p->lastio,>))
	    {
	      last = s;
	      tv = p->lastio;
	    }

	} /* for (s = 0; s < par; s++) */

      if (interactive_task)
	{
	  if (active == 0)
	    {
	      p = interactive_task;
	      p->flags |= PRUNNING;
              #ifdef DEBUG
              fprintf(stderr, "About to run single, interactive task, active zero.\n");
              #endif
	      resvec[p->num] = run_single(p->name, p->arg0, p->splashadd);
	      if (run_mode)
		finish_task(nodevec[p->num]);
	      p->flags = 0;
	      p->pid = 0;
	      p->fd = 0;
	      interactive_task = NULL;
	      continue;
	    }
	}

      if (active == 0)
	{
	  if (num < argc)
	    fprintf(stderr, "ERROR: not all processed (%d of %d)\n", num, argc);
	  break;
	}
#if DEBUG
      fprintf(stderr, "active = %d, maxfd = %d, last = %d\n", active, maxfd, last);
#endif
      if (active == 1 && last >= 0 && num >= argc)
	{
	  p = prgs + last;
	  if ((pid = waitpid(p->pid, &r, (maxfd < 0 ? 0 : WNOHANG)|WUNTRACED)) == 0)
	    {
	      writebuf(p);
	      continue;
	    }
	  else
	    {
	      p->status = r;
	      p->flags |= PFINISHED;
	      signaled = 1;
	    }
	}
      else
	{
	  const struct timespec zero = {0,0};
	  const int old_errno = errno;
	  (void)pselect(0,0,0,0,&zero,&smask);
	  errno = old_errno;
	}

      if (signaled)
	{
	  signaled = 0;

	  for (s = 0; s < par; s++)
	    {
	      p = prgs + s;

	      if ((p->flags & PFINISHED) == 0)
		continue;
	      r = p->status;

	      if (WIFSTOPPED(r))
		{
		  pid_t pg = getpgid(p->pid);
		  if (pg > 0)
		    killpg(pg, SIGCONT);
		  else
		    kill(-p->pid, SIGCONT);
		  p->flags &= ~PFINISHED;
		  continue;
		}

	      callsplash(p->splashadd, p->name, arg);
	      resvec[p->num] = WIFEXITED(r) ? WEXITSTATUS(r) : (WIFSIGNALED(r) ? 1 : 255);
	      if (run_mode)
		finish_task(nodevec[p->num]);
	      p->status = 0;
	      p->flags = 0;
	      p->pid = 0;
	      active--;

	      if (gtimo_running == p)
		{
		  writebuf(p);
		  if (p->fd) detach(p, GTIMO_OFFL);
		  flushbuf(p);
		  gtimo_running = 0;
		}
	      else if (gtimo_running)
		{
		  storebuf(p);
		  if (p->fd) detach(p, GTIMO_USED);
		}
	      else
		{
		  writebuf(p);
		  if (p->fd) detach(p, GTIMO_OFFL);
		}
#ifdef START_OUTRIGHT
	      break;		/* one free slot ... start outright new process */
#endif
	    } /* for (s = 0; s < par; s++) */

#ifdef CHECK_FORDEVPTS
	  if (!devpts)
          {
	      devpts = checkdevpts();
              #ifdef DEBUG
              fprintf(stderr, "Check for devpts returned %d\n", devpts);
              #endif
          }
#endif
	  continue;		/* start new processes */
	}

      if (timo >= 0)
        tv.tv_sec += timo;

      isgtimo = 0;
      if (gtimo >= 0 && !gtimo_running && last >= 0 && prgs[last].pid)
	{
	  struct timeval gl = glastio;
	  gl.tv_sec += gtimo;
	  if ((timo < 0) || timercmp(&tv,&gl,>))
	    {
	      tv = glastio;
	      tv.tv_sec += gtimo;
	      isgtimo = 1;
	    }
	}

      r = 0;
      if (timo >= 0 || isgtimo)
	{
	  struct timeval wait;
	  struct timespec spec;

	  timersub(&tv, &now, &wait);
	  if (wait.tv_usec < 0)
	    {
	      wait.tv_usec += 1000000;
	      wait.tv_sec--;
	    }
	  if (wait.tv_sec >= 0)
	    {
	      int check = limit < par && num < argc;

	      if (check)			/* shorten timeout for new limit and procs  ... */
		{
		  wait.tv_sec = 0;
		  wait.tv_usec = (300 - diff) * 1000;
		}
#if DEBUG
	      fprintf(stderr, "going into select1 %d %ld %ld\n", last, wait.tv_sec, wait.tv_usec);
#endif
	      TIMEVAL_TO_TIMESPEC(&wait, &spec);
	      r = pselect(maxfd + 1, &rset, 0, 0, (last >= 0 || check) ? &spec : 0, &smask);

	      if (check && (r == 0))		/* ... but do not throw out messages to early!!! */
		continue;
	    }
	  else
	    {
	      wait.tv_sec  = 0;			/* Avoid looping around (does this ever happen?) */
	      wait.tv_usec = 20*1000;
	      TIMEVAL_TO_TIMESPEC(&wait, &spec);
	      r = pselect(maxfd + 1, &rset, 0, 0, last >= 0 ? &spec : 0, &smask);
	    }
	}
      else
	{
	  r = pselect(maxfd + 1, &rset, 0, 0, 0, &smask);
	}

      if (r == -1)
	{
	  if (errno == EINTR)
	    continue;		/* SIGCHLD has happen in most cases */
	  perror("select");
	  exit(1);
	}
      if (r == 0)
	{
	  if (last < 0)		/* just in case... */
	    continue;
	  p = prgs + last;
	  writebuf(p);
	  if (isgtimo && p->pid)
	    gtimo_running = p;
	}
      else
	{
	  for (s = 0; s < par; s++)
	    {
	      p = prgs + s;
	      if (p->fd == 0)
		continue;
	      if (!FD_ISSET(p->fd, &rset))
		continue;
	      r = (int)TEMP_FAILURE_RETRY(read(p->fd, p->buf + p->len, sizeof(p->buf) - p->len));
	      if (r <= 0)
		{
		  if (!gtimo_running || p == gtimo_running)
		    writebuf(p);
		  if (r < 0)
		    {
		      close(p->fd);
		      p->fd = 0;
#ifdef START_OUTRIGHT
		      break;		/* one free slot ... start outright new process */
#endif
		    }
		  continue;
		}
	      p->len += r;
	      if (p->len == sizeof(p->buf))
		{
		  for (i = p->len - 1; i >= 0; i--)
		    {
		      if (p->buf[i] == '\n')
			break;
		    }
		  if (++i <= 0)
		    i = p->len;
		  p->len = i;
		  writebuf(p);
		  p->len = i;	/* writebuf clears p->len */
		  if (p->len < sizeof(p->buf))
		    memmove(p->buf, p->buf + p->len, sizeof(p->buf) - p->len);
		  p->len = sizeof(p->buf) - p->len;
		}
	      p->lastio = now;

	    } /* for (s = 0; s < par; s++) */
	}

    } /* for (;;) */

  sigprocmask(SIG_SETMASK, &omask, NULL);

finished:
  waitsplash();
  if (run_mode)
    print_run_result(resvec, nodevec, run_mode);
  else
    {
      for (i = 0; i < argc; i++)
	{
#if DEBUG
	  if (resvec[i] == 255)
	    {
	      fprintf(stderr, "ERROR: forgotten process??\n");
	      exit (1);
	    }
#endif
#if VERBOSE
	  printf(i ? " %d" : "%d", resvec[i]);
#endif /* VERBOSE */
	}
#if VERBOSE
      printf("\n");
#endif /* VERBOSE */
    }
  return 0;
}