-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathforkrun.bash
1858 lines (1495 loc) · 97.6 KB
/
forkrun.bash
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
#!/usr/bin/env bash
# shellcheck disable=SC2004,SC2015,SC2016,SC2028,SC2162 source=/dev/null
shopt -s extglob
forkrun() {
## Efficiently parallelize a loop / run many tasks in parallel *extremely* fast using bash coprocs
#
# USAGE: printf '%s\n' "${args[@]}" | forkrun [-flags] [--] parFunc ["${args0[@]}"]
#
# LIST OF FLAGS: [-j|-P [-]<#>[,<#>,<#>]] [-t <path>] ( [-l <#>] | [-L <#[,#]>]] ) ( [-b <#>] | [-B <#>[,<#>]] ) [-d <char>] [-u <fd>] [-i] [-I] [-k] [-n] [-z|-0] [-s] [-S] [-p] [-D] [-N] [-U] [-v] [-h|-?]
#
# For help / usage info, call forkrun with one of the following flags:
#
# --usage : display brief usage info
# -? | -h | --help : dispay standard help (includes brief descriptions + short names for flags)
# --help=s[hort] : more detailed variant of '--usage'
# --help=f[lags] : display detailed info about flags (longer descriptions, short + long names)
# --help=a[ll] : display all help (includes detailed descriptions for flags)
#
# NOTE: the `?` may need to be escaped for `-?` to trigger the help (i.e., use `forkrun '-?'` or `forkrun -\?`) (otherwise bash will parse the '?' as a special char)
############################ BEGIN FUNCTION ############################
trap - EXIT INT TERM HUP USR1 USR2
shopt -s extglob
# make all variables local
local tmpDir fPath outStr delimiterVal delimiterReadStr delimiterRemoveStr exitTrapStr exitTrapStr_kill nLines0 nOrder nProcs nProcsMax nBytes tTimeout coprocSrcCode outCur tmpDirRoot returnVal tmpVar t0 readBytesProg nullDelimiterProg ddQuietStr trailingNullFlag inotifyFlag lseekFlag fallocateFlag nLinesAutoFlag nQueueFlag substituteStringFlag substituteStringIDFlag nOrderFlag readBytesFlag readBytesExactFlag nullDelimiterFlag subshellRunFlag stdinRunFlag pipeReadFlag rmTmpDirFlag exportOrderFlag noFuncFlag unescapeFlag optParseFlag continueFlag doneIndicatorFlag FORCE_allowCarriageReturnsFlag ddAvailableFlag fd_continue fd_inotify fd_inotify0 fd_nAuto fd_nAuto0 fd_nOrder fd_nOrder0 fd_read fd_read0 fd_write fd_stdout fd_stdin fd_stdin0 fd_stderr pWrite pOrder pAuto pQueue pWrite_PID pNotify_PID pOrder_PID pAuto_PID pQueue_PID fd_read_pos fd_read_pos_old fd_write_pos DEBUG_FORKRUN
local -i PID0 nLines nLinesCur nLinesNew nLinesMax nRead nWait nOrder0 nBytesRead nQueue nQueueLast nQueueMin nQueueLastCount nCPU v9 kkMax kkCur kk kkProcs verboseLevel pLOAD_max pAdd
local -a A p_PID runCmd outHave outPrint pLOADA
# # # # # PARSE OPTIONS # # # # #
: "${verboseLevel:=0}" "${returnVal:=0}" "${fd_stdin0:=0}"
# check inputs and set defaults if needed
[[ $# == 0 ]] && optParseFlag=false || optParseFlag=true
while ${optParseFlag} && (( $# > 0 )) && [[ "$1" == [-+]* ]]; do
case "${1}" in
-?(-)@([jP]|?(n)[Pp]roc?(s)?)?(?([= ])?([+-])*([0-9])@([0-9,])*([0-9])?(,*([0-9]))))
if [[ "${1}" == -?(-)@([jP]|?(n)[Pp]roc?(s)?)?([= ])?([+-])*([0-9])@([0-9,])*([0-9])?(,*([0-9])) ]]; then
nProcs="${1##@(-?(-)@([jP]|?(n)[Pp]roc?(s)?)?([= ])?(+))}"
elif [[ "${1}" == -?(-)@([jP]|?(n)[Pp]roc?(s)?) ]] && [[ "${2}" == ?([+-])*([0-9])@([0-9,-])*([0-9])?(,*([0-9])) ]]; then
nProcs="${2#'+'}"
shift 1
fi
;;
-?(-)?(n)l?(ine?(s))?(?([= ])+([0-9])))
if [[ "${1}" == -?(-)?(n)l?(ine?(s))?([= ])+([0-9]) ]]; then
nLines="${1##@(-?(-)?(n)l?(ine?(s))?([= ]))}"
nLinesAutoFlag=false
elif [[ "${1}" == -?(-)?(n)l?(ine?(s)) ]] && [[ "${2}" == +([0-9]) ]]; then
nLines="${2}"
nLinesAutoFlag=false
shift 1
fi
;;
-?(-)?(N)L?(INE?(S))?(?([= ])+([0-9])?(,+([0-9]))))
if [[ "${1}" == -?(-)?(N)L?(INE?(S))?([= ])+([0-9])?(,+([0-9])) ]]; then
nLines0="${1##@(-?(-)?(N)L?(INE?(S))?([= ]))}"
nLinesAutoFlag=true
elif [[ "${1}" == -?(-)?(N)L?(INE?(S)) ]] && [[ "${2}" == +([0-9])?(,+([0-9])) ]]; then
nLines0="${2}"
nLinesAutoFlag=true
shift 1
else
continue
fi
if [[ "${nLines0}" == +([0-9])','+([0-9]) ]]; then
nLinesMax="${nLines0##*,}"
nLines="${nLines0%%,*}"
else
nLines="${nLines0}"
fi
;;
-?(-)b?(yte?(s))?(?([= ])+([0-9])?([KkMmGgTtPp])?(i)?([Bb])))
if [[ "${1}" == -?(-)b?(yte?(s))?([= ])+([0-9])?([KkMmGgTtPp])?(i)?([Bb]) ]]; then
nBytes="${1##@(+([0-9])?([KkMmGgTtPp])?(i)?([Bb]))}"
readBytesFlag=true
readBytesExactFlag=false
elif [[ "${1}" == -?(-)b?(yte?(s)) ]] && [[ "${2}" == +([0-9])?([KkMmGgTtPp])?(i)?([Bb]) ]]; then
nBytes="${2}"
readBytesFlag=true
readBytesExactFlag=false
shift 1
fi
;;
-?(-)B?(YTE?(S))?(?([= ])+([0-9])?([KkMmGgTtPp])?(i)?([Bb])?(,+([0-9])?(.+([0-9])))))
if [[ "${1}" == -?(-)B?(YTE?(S))?([= ])+([0-9])?([KkMmGgTtPp])?(i)?([Bb])?(,+([0-9])?(.+([0-9]))) ]]; then
nBytes="${1##@(+([0-9])?([KkMmGgTtPp])?(i)?([Bb])?(,+([0-9])?(.+([0-9]))))}"
readBytesFlag=true
readBytesExactFlag=true
elif [[ "${1}" == -?(-)B?(YTE?(S)) ]] && [[ "${2}" == +([0-9])?([KkMmGgTtPp])?(i)?([Bb])?(,+([0-9])?(.+([0-9]))) ]]; then
nBytes="${2}"
readBytesFlag=true
readBytesExactFlag=true
shift 1
fi
;;
-?(-)t?(mp?(?(-)dir))?(?([= ])*@([[:graph:]])*))
if [[ "${1}" == -?(-)t?(mp?(?(-)dir))?([= ])*@([[:graph:]])* ]]; then
tmpDirRoot="${1##@(-?(-)t?(mp?(?(-)dir))?([= ]))}"
mkdir -p "${tmpDirRoot}"
elif [[ "${1}" == -?(-)t?(mp?(?(-)dir)) ]] && [[ "${2}" == *@([[:graph:]])* ]]; then
tmpDirRoot="${2}"
mkdir -p "${tmpDirRoot}"
shift 1
fi
;;
-?(-)d?(elim?(iter))?(?([= ])@([[:graph:]])*))
if [[ "${1}" == -?(-)d?(elim?(iter))?([= ])@([[:graph:]])* ]]; then
delimiterVal="${1##@(-?(-)d?(elim?(iter))?([= ]))}"
(( ${#delimiterVal} > 1 )) && printf '\nWARNING: the delimiter must be a single character, and a multi-character string was given. Only using the 1st character.\n\n' >&2
(( ${#delimiterVal} == 0 )) && nullDelimiterFlag=true || delimiterVal="${delimiterVal:0:1}"
elif [[ "${1}" == -?(-)d?(elim?(iter)) ]] && [[ "${2}" == @([[:graph:]])* ]]; then
(( ${#2} > 1 )) && printf '\nWARNING: the delimiter must be a single character, and a multi-character string was given. Only using the 1st character.\n\n' >&2
(( ${#2} == 0 )) && nullDelimiterFlag=true || delimiterVal="${2:0:1}"
shift 1
fi
;;
-?(-)@(u|fd|file?(-)descriptor)?(?([= ])+([0-9])))
if [[ "${1}" == -?(-)@(u|fd|file?(-)descriptor)?([= ])+([0-9]) ]]; then
fd_stdin0="${1##@(-?(-)@(u|fd|file?(-)descriptor)?([= ]))}"
elif [[ "${1}" == -?(-)@(u|fd|file?(-)descriptor) ]] && [[ "${2}" == +([0-9]) ]]; then
fd_stdin0="${2}"
shift 1
fi
;;
[+-]?([+-])i?(nsert))
[[ "${1:0:1}" == '-' ]] && substituteStringFlag=true || substituteStringFlag=false
;;
[+-]?([+-])@(I?(D)|INSERT?(?(-)ID)))
[[ "${1:0:1}" == '-' ]] && substituteStringIDFlag=true || substituteStringIDFlag=false
;;
[+-]?([+-])k?(eep?(?(-)order)))
[[ "${1:0:1}" == '-' ]] && nOrderFlag=true || nOrderFlag=false
;;
[+-]?([+-])@(0|z?(ero)|null))
[[ "${1:0:1}" == '-' ]] && nullDelimiterFlag=true || nullDelimiterFlag=false
;;
[+-]?([+-])s?(ub)?(?(-)shell)?(?(-)run))
[[ "${1:0:1}" == '-' ]] && subshellRunFlag=true || subshellRunFlag=false
;;
[+-]?([+-])@(S|[Ss]tdin?(?(-)run)))
[[ "${1:0:1}" == '-' ]] && stdinRunFlag=true || stdinRunFlag=false
;;
[+-]?([+-])p?(ipe)?(?(-)read))
[[ "${1:0:1}" == '-' ]] && pipeReadFlag=true || pipeReadFlag=false
;;
[+-]?([+-])@(D|[Dd]elete))
[[ "${1:0:1}" == '-' ]] && rmTmpDirFlag=true || rmTmpDirFlag=false
;;
[+-]?([+-])n?(umber)?(-)?(line?(s)))
[[ "${1:0:1}" == '-' ]] && exportOrderFlag=true || exportOrderFlag=false
;;
[+-]?([+-])@(N?(O)|[Nn][Oo]?(-)func))
[[ "${1:0:1}" == '-' ]] && noFuncFlag=true || noFuncFlag=false
;;
[+-]?([+-])U?(NESCAPE))
[[ "${1:0:1}" == '-' ]] && unescapeFlag=true || unescapeFlag=false
;;
[+-]?([+-])@(+(v)|verbose))
case "${1}" in
[+-]?([+-])verbose)
[[ "${1:0:1}" == '-' ]] && ((verboseLevel++)) || ((verboseLevel--))
;;
[+-]?([+-])+(v))
tmpVar="${1##+([+-])}"
[[ "${1:0:1}" == '-' ]] && verboseLevel=$(( ${verboseLevel} + ${#tmpVar} )) || verboseLevel=$(( ${verboseLevel} - ${#tmpVar} ))
unset tmpVar
;;
esac
;;
-?(-)@(help?(=@(a?(ll)|f?(lag?(s))|s?(hort)))|usage|[h?]))
_forkrun_displayHelp "${1}"
return 0
;;
--)
optParseFlag=false
;;
@([-+])?([-+])*@([[:graph:]])*)
printf '\nERROR: FLAG "%s" NOT RECOGNIZED. ABORTING.\n\nNOTE: If this flag was intended for the code being parallelized: then:\n1. ensure all flags for forkrun come first\n2. pass '"'"'--'"'"' to denote where forkrun flag parsing should stop.\n\nUSAGE INFO:' "$1" >&2
_forkrun_displayHelp --usage
returnVal=1
return 1
;;
*)
optParseFlag=false
break
;;
esac
shift 1
[[ ${#} == 0 ]] && optParseFlag=false
done
[ -t "${fd_stdin0}" ] && {
(( ${verboseLevel} > 0 )) && printf '\n\nERROR: STDIN is a terminal. \n\nforkrun requires STDIN to be a pipe \n(containing the inputs to parallelize over); e.g.: \n\nprintf '"'"'%%s\\n'"'"' "${args[@]}" | forkrun parFunc \n\nABORTING! \n\n'
returnVal=1
return 1
}
# # # # # SETUP TMPDIR # # # # #
[[ ${tmpDirRoot} ]] || { [[ ${TMPDIR} ]] && [[ -d "${TMPDIR}" ]] && tmpDirRoot="${TMPDIR}"; } || { [[ -d '/dev/shm' ]] && tmpDirRoot='/dev/shm'; } || { [[ -d '/tmp' ]] && tmpDirRoot='/tmp'; } || tmpDirRoot="$(pwd)"
tmpDir="$(mktemp -p "${tmpDirRoot}" -d .forkrun.XXXXXX)"
fPath="${tmpDir}"/.stdin
mkdir -p "${tmpDir}"/.run
: >"${fPath}"
# # # # # BEGIN MAIN SUBSHELL # # # # #
# several file descriptors are opened for use by things running in this subshell. See closing`)` near the end of this function.
(
# implement DEBUG functionality if DEBUG set as an environment variable
[[ ${DEBUG_FORKRUN} ]] && { source /proc/self/fd/0; } <<<"${DEBUG_FORKRUN}"
# NOTE: this DEBUG is an intentionally undocumented "easter egg". Using this with zero understanding of the forkrun source code is dangerous, so you have to actually browse through the source to find its documentation
#
# USAGE: `printf '%s\n' "${args@]}" | DEBUG_FORKRUN="${cmdStr}" forkrun [...]`
#
# EFFECT: `${cmdStr}` will be sourced at the start of forkrun's main subshell (so as to not have any effect the parent/caller shell after forkrun is finished running)
#
# INTENDED PURPOSE: to allow someone (with working knowledge of forkrun's code) to overwrite automatically set variables with custom values, set custom shopt/set flags, implement a "run-once setup script" that must be run from within forkrun's main subshell, etc.
#
# EXAMPLE 1: DEBUG_FORKRUN='set -xv' --> enable debug output to stderr as forkrun runs;
# EXAMPLE 2: DEBUG_FORKRUN='inotifyFlag=false' --> prevent using inotifywait, even if the inotifywait binary is available.
# # # # # INITIAL SETUP # # # # #
LC_ALL=C
LANG=C
IFS=
export LC_ALL=C LANG=C IFS=
#umask 177
PID0="${BASHPID}"
shopt -s nullglob
# dynamically set defaults for a few flags
: "${noFuncFlag:=false}" "${FORCE_allowCarriageReturnsFlag:=false}" "${readBytesFlag:=false}" "${readBytesExactFlag:=false}" "${nullDelimiterFlag:=false}"
if enable lseek &>/dev/null; then
: "${lseekFlag:=true}"
else
: "${lseekFlag:=false}"
fi
# determine what forkrun is using lines on stdin for
if ${FORCE_allowCarriageReturnsFlag}; then
# NOTE: allowing carriage returns in parFunC (or its initial args) is DANGEROUS. Dont do this unless you know what you are doing.
# As such, `FORCE_allowCarriageReturnsFlag` can only be enabled (set to `true`) using the DEBUG_FORKRUN environment variable
runCmd=("${@}")
else
runCmd=("${@//$'\r'/}")
fi
(( ${#runCmd[@]} > 0 )) || ${noFuncFlag} || runCmd=(printf '%s\n')
(( ${#runCmd[@]} > 0 )) && noFuncFlag=false
${noFuncFlag} && runCmd=('source' '/proc/self/fd/0')
hash "${runCmd[0]}" &>/dev/null || hash "${runCmd[0]%% *}" &>/dev/null
# setup byte reading if passed -b or -B
if ${readBytesFlag}; then
# turn off nLinesAuto
nLinesAutoFlag=false
# turn on passing data via stdin (to prevent mangling NULL's in binary data) by default when byte splitting
: "${stdinRunFlag:=true}"
# parse read size (in bytes)
nBytes="${nBytes,,}"
nBytes="${nBytes//' '/}"
[[ "${nBytes}" == +([0-9])?([KkMmGgTtPp])?(i)?([Bb]),+([0-9])?(.+([0-9])) ]] && {
tTimeout="${nBytes##*,}"
[[ "${tTimeout}" == +([0-9]).*([0-9]) ]] && { tTimeout="${tTimeout%%.*}"; ((tTimeout++)); }
nBytes="${nBytes%,*}"
}
nBytes="${nBytes%b}"
[[ "${nBytes}" == +([0-9])@([kmgtp])?(i) ]] && {
local -A nBytesParser=([k]=1 [m]=2 [g]=3 [t]=4 [p]=5)
if [[ ${nBytes: -1:1} == 'i' ]]; then
nBytes="$(( ${nBytes%[kmgtp]i} * ( 1024 ** ${nBytesParser[${nBytes: -2:1}]} ) ))"
else
nBytes="$(( ${nBytes%[kmgtp]} * ( 1000 ** ${nBytesParser[${nBytes: -1:1}]} ) ))"
fi
}
# make sure nBytes is only digits
[[ "${nBytes//[0-9]/}" ]] && (( ${verboseLevel} >= 0 )) && {
printf '\nERROR: the byte count passed to the ( -b | -B ) flag did not parse correctly. \nThis must consist solely of numbers, optionally followed by a standard si prefix. \nVALID EXAMPLES: 4 8b 16k 32mb 64G 128TB 256PiB \nNOTE: the count is always in bytes, never in bits, regardless of the case of the (optional) trailing "b" / "B"\n\n' >&${fd_stderr};
returnVal=1
return 1
}
# check for incompatible flags
{ ${nullDelimiterFlag} || [[ ${delimiterVal} ]] || [[ ${delimiterRemoveStr} ]]; } && (( ${verboseLevel} >= 0 )) && {
(( ${verboseLevel} >= 0 )) && printf '\nWARNING: The flag to use a null or a custom delimiter (-z | -0 | -d <delim> ) and the flag to read by byte count ( -b | -B ) were both passed.\nThere are no delimiters required when reading by bytes, so the delimiter flag will be unset and ignored\n\n' >&${fd_stderr};
nullDelimiterFlag=false
unset delimiterVal delimiterRemoveStr
}
# check for GNU dd or (if unavailable) check for head (either GNU or busybox)
[[ ${readBytesProg} ]] || {
if type -p dd &>/dev/null && dd --version | grep -qF 'coreutils'; then
readBytesProg='dd'
elif type -p head &>/dev/null; then
readBytesProg='head'
else
readBytesProg='bash'
(( ${verboseLevel} >= 0 )) && printf '\nWARNING: neither "dd (GNU)" nor "head" are available. The `read` builtin will be used by the worker coprocs to read data. forkrun will run considerably slower. \n\n' >&${fd_stderr};
fi
}
${stdinRunFlag} || (( ${verboseLevel} < 0 )) || printf '\nWARNING: data will be passed to coprocs via bash variables, which will drop NULLs and will probably mangle binary data (text data should still work). \nIt is not recommended to use the `+S` flag to prevent passing data to the coprocs stdin\n\n' >&${fd_stderr};
# TEMP FIX - force readBytesExactFlag if using bash and stdinRunFlag. Otherwise it gets stuck somewhere :/
[[ ${readBytesProg} == 'bash' ]] && ${stdinRunFlag} && readBytesExactFlag=true
# read from pipe for -B if using dd/head. also dont need inotifywait
if ${readBytesExactFlag} && ! { [[ ${readBytesProg} == 'bash' ]] && ${stdinRunFlag}; }; then
pipeReadFlag=true
inotifyFlag=false
else
pipeReadFlag=false
fi
[[ ${readBytesProg} == 'bash' ]] || hash "${readBytesProg}"
else
# set batch size
{ [[ ${nLines} ]] && (( ${nLines} > 0 )) && : "${nLinesAutoFlag:=false}"; } || : "${nLinesAutoFlag:=true}"
{ [[ -z ${nLines} ]] || [[ ${nLines} == 0 ]]; } && nLines=1
fi
# set number of coproc workers and (if enabled) minimim worker read queue length
[[ "${nProcs}" == '-'* ]] && {
: "${nQueueFlag:=true}"
nProcs="${nProcs#'-'}"
}
[[ "${nProcs}" == *','* ]] && {
: "${nQueueFlag:=true}"
nProcsMax="${nProcs#*,}"
nProcs="${nProcs%%,*}"
[[ "${nProcsMax}" == *','* ]] && {
nQueueMin="${nProcsMax#*,}"
nProcsMax="${nProcsMax%%,*}"
}
}
: "${nQueueFlag:=false}" "${nQueueMin:=1}"
local -i nProcs="${nProcs}" nProcsMax="${nProcsMax}"
nCPU="$({ type -a nproc &>/dev/null && nproc; } || { type -a grep &>/dev/null && grep -cE '^processor.*: ' /proc/cpuinfo; } || { mapfile -t tmpA </proc/cpuinfo && tmpA=("${tmpA[@]//processor*/$'\034'}") && tmpA=("${tmpA[@]//!($'\034')/}") && tmpA=("${tmpA[@]//$'\034'/1}") && tmpA="${tmpA[*]}" && tmpA="${tmpA// /}" && echo ${#tmpA}; } || printf '8')";
{ [[ ${nProcs} ]] && (( ${nProcs:-0} > 0 )); } || { ${nQueueFlag} && nProcs=$(( ${nCPU} / 2 )) || nProcs=${nCPU}; }
${nQueueFlag} && {
[[ ${nProcsMax//0/} ]] || nProcsMax=$(( ${nCPU} * 2 ));
[[ ${nQueueMin//0/} ]] || nQueueMin=1
}
{ ${nQueueFlag} && (( ${nQueueMin:-0} > 0 )) && { [[ ${nProcsMax:-0} == '0' ]] || (( ${nProcs} < ${nProcsMax} )); }; } || : "${nQueueFlag:=false}"
# if reading 1 line at a time (and not automatically adjusting it) skip saving the data in a tmpfile and read directly from stdin pipe
${nLinesAutoFlag} || { [[ ${nLines} == 1 ]] && : "${pipeReadFlag:=true}"; }
# set defaults for control flags/parameters
: "${nOrderFlag:=false}" "${rmTmpDirFlag:=true}" "${nLinesMax:=1024}" "${subshellRunFlag:=false}" "${pipeReadFlag:=false}" "${substituteStringFlag:=false}" "${substituteStringIDFlag:=false}" "${exportOrderFlag:=false}" "${unescapeFlag:=false}" "${stdinRunFlag:=false}"
doneIndicatorFlag=false
# check for inotifywait
type -a inotifywait &>/dev/null && ! ${pipeReadFlag} && : "${inotifyFlag:=true}" || : "${inotifyFlag:=false}"
# check for fallocate
type -a fallocate &>/dev/null && ! ${pipeReadFlag} && : "${fallocateFlag:=true}" || : "${fallocateFlag:=false}"
# check for conflict in flags that were defined on the commandline when forkrun was called
${pipeReadFlag} && ${nLinesAutoFlag} && (( ${verboseLevel} >= 0 )) && { printf '%s\n' '' 'WARNING: automatically adjusting number of lines used per function call not supported when reading directly from stdin pipe' ' Disabling reading directly from stdin pipe...a tmpfile will be used' '' >&${fd_stderr}; pipeReadFlag=false; }
# require -k to use -n
${exportOrderFlag} && nOrderFlag=true
# setup delimiter
${readBytesFlag} || {
if ${nullDelimiterFlag}; then
delimiterReadStr="-d ''"
${lseekFlag} && : "${nullDelimiterProg:='lseek'}"
: "${nullDelimiterProg:=bash}"
if type -p dd &>/dev/null; then
ddAvailableFlag=true
if dd --version | grep -qF 'coreutils'; then
ddQuietStr='status=none'
else
ddQuietStr='2>/dev/null'
fi
else
: "${ddAvailableFlag=false}"
fi
[[ "${nullDelimiterProg}" == @(dd|bash|lseek) ]] || {
if ${FORCE_allowUnsafeNullDelimiterFlag}; then
nullDelimiterProg=''
else
nullDelimiterProg='bash'
fi
}
elif [[ -z ${delimiterVal} ]]; then
delimiterVal='$'"'"'\n'"'"
${noFuncFlag} || ${lseekFlag} || delimiterRemoveStr='%$'"'"'\n'"'"
else
delimiterVal="$(printf '%q' "${delimiterVal}")"
${lseekFlag} || {
${noFuncFlag} && delimiterRemoveStr='//'"${delimiterVal}"'/\$'"'"'\n'"'" || delimiterRemoveStr="%${delimiterVal}"
}
delimiterReadStr="-d ${delimiterVal}"
fi
}
# modify runCmd if '-i' '-I' or '-u' flags are set
if ${unescapeFlag}; then
${substituteStringFlag} && {
runCmd=("${runCmd[@]//'{}'/'"${A[@]%$'"'"'\n'"'"'}"'}")
}
${substituteStringIDFlag} && {
runCmd=("${runCmd[@]//'{ID}'/'{<#>}'}")
${nOrderFlag} && runCmd=("${runCmd[@]//'{IND}'/'${nOrder0}'}")
}
else
mapfile -t runCmd < <(printf '%q\n' "${runCmd[@]}")
${substituteStringFlag} && {
runCmd=("${runCmd[@]//'\{\}'/'"${A[@]%$'"'"'\n'"'"'}"'}")
}
${substituteStringIDFlag} && {
runCmd=("${runCmd[@]//'\{ID\}'/'{<#>}'}")
${nOrderFlag} && runCmd=("${runCmd[@]//'\{IND\}'/'${nOrder0}'}")
}
fi
nLinesCur=${nLines}
mkdir -p "${tmpDir}"/.run
# if keeping tmpDir print its location to stderr
${rmTmpDirFlag} || (( ${verboseLevel} <= 0 )) || printf '\ntmpDir path: %s\n\n' "${tmpDir}" >&${fd_stderr}
(( ${verboseLevel} > 0 )) && {
printf '\n\n------------------- FLAGS INFO -------------------\n\nCOMMAND TO PARALLELIZE: %s\n' "$(printf '%s ' "${runCmd[@]}")"
${inotifyFlag} && echo 'using inotify to efficiently wait for slow inputs on stdin'
${fallocateFlag} && echo 'using fallocate to shrink the tmpfile containing stdin as forkrun runs'
${lseekFlag} && echo 'using "lseek" loadable builtin to read data faster and more efficiently'
${nQueueFlag} && printf '(-j|-P) initial / max workers: %s / %s. workers will be dynamically spawned (up to a %s workers max) whenever read queue depth is less than %s\n' "${nProcs}" "${nProcsMax}" "${nProcsMax}" "${nQueueMin}" || printf '(-j|-P) using %s coproc workers\n' ${nProcs}
${nLinesAutoFlag} && printf '(-L) automatically adjusting batch size (lines per function call). initial = %s line(s). maximum = %s line(s).\n' "${nLines}" "${nLinesMax}"
printf '(-t) forkrun tmpdir will be under %s\n' "${tmpDirRoot}"
${readBytesFlag} && printf '(-%s) data will be read in chunks of %s %s bytes using %s\n' "$(${readBytesExactFlag} && echo 'B' || echo 'b')" "$(${readBytesExactFlag} && echo 'exactly' || echo 'up to')" "${nBytes}" "${readBytesProg}"
${nOrderFlag} && echo '(-k) output will be ordered the same as if the inputs were run sequentially'
${exportOrderFlag} && echo '(-n) output batches will be numbered (index is per-batch, denoted using \\034<IND>:\\035\\n)'
${substituteStringFlag} && echo '(-i) replacing {} with lines from stdin'
${substituteStringIDFlag} && printf '%s %s\n' '(-I) replacing {ID} with coproc worker ID' "$(${nOrderFlag} && echo 'and replacing {IND} with output order INDex')"
${unescapeFlag} && echo '(-u) not escaping special characters in ${runCmd}'
${pipeReadFlag} && echo '(-p) worker coprocs will read directly from stdin pipe, not from a tmpfile'
if ${nullDelimiterFlag}; then
printf '((-0|-z)|(-d)) stdin will be parsed using nulls as delimiter (instead of newlines) (helper: %s)\n' "${nullDelimiterProg}"
else
printf '(%s) delimiter: %s\n' "$([[ "${delimiterVal}" == '$'"'"'\n'"'" ]] && echo '--' || echo '-d')" "${delimiterVal}"
fi
${rmTmpDirFlag} || printf '(-r) tmpdir (%s) will NOT be automatically removed\n' "${tmpDir}"
${subshellRunFlag} && echo '(-s) coproc workers will run each group of N lines in a subshell'
${stdinRunFlag} && echo '(-S) coproc workers will pass lines to the command being parallelized via the command'"'"'s stdin'
${noFuncFlag} && echo '(-N) no function mode enabled: commands should be included in stdin' || printf 'tmpdir: %s\n' "${tmpDir}"
echo "(-v) Verbosity Level: ${verboseLevel}"
printf '\n------------------------------------------\n\n'
} >&${fd_stderr}
# # # # # FORK "HELPER" PROCESSES # # # # #
# start building exit trap string
exitTrapStr=': >"'"${tmpDir}"'"/.done;
: >"'"${tmpDir}"'"/.quit;
kill -USR1 $(cat </dev/null "'"${tmpDir}"'"/.run/p* 2>/dev/null) 2>/dev/null; '$'\n'
${pipeReadFlag} && {
# '.done' file makes no sense when reading from a pipe
: >"${tmpDir}"/.done
} || {
# spawn a coproc to write stdin to a tmpfile
# After we are done reading all of stdin indicate this by touching .done
{ coproc pWrite {
export LC_ALL=C LANG=C IFS=
trap - EXIT
trap 'trap - TERM INT HUP USR1; kill -INT '"${PID0}"' ${BASHPID}' INT
trap 'trap - TERM INT HUP USR1; kill -TERM '"${PID0}"' ${BASHPID}' TERM
trap 'trap - TERM INT HUP USR1; kill -HUP '"${PID0}"' ${BASHPID}' HUP
trap 'trap - TERM INT HUP USR1' USR1
cat <&${fd_stdin} >&${fd_write}
: >"${tmpDir}"/.done
(( ${verboseLevel} > 1 )) && printf '\nINFO: pWrite has finished - all of stdin has been saved to the tmpfile at %s\n' "${fPath}" >&${fd_stderr}
${inotifyFlag} && {
for (( kk=0 ; kk<=nProcs ; kk++ )); do
: >&${fd_write}
done
}
}
}
exitTrapStr_kill+="${pWrite_PID} "
}
# setup (ordered) output. This uses the same naming scheme as `split -d` to ensure a simple `cat /path/*` always orders things correctly.
if ${nOrderFlag}; then
mkdir -p "${tmpDir}"/.out
outStr='>"'"${tmpDir}"'"/.out/x${nOrder}'
printf '%s\n' {10..89} >&${fd_nOrder}
# fork coproc to populate a pipe (fd_nOrder) with ordered output file name indicies for the worker copropcs to use
{ coproc pOrder {
export LC_ALL=C LANG=C IFS=
trap - EXIT
trap 'trap - TERM INT HUP USR1; kill -INT '"${PID0}"' ${BASHPID}' INT
trap 'trap - TERM INT HUP USR1; kill -TERM '"${PID0}"' ${BASHPID}' TERM
trap 'trap - TERM INT HUP USR1; kill -HUP '"${PID0}"' ${BASHPID}' HUP
trap 'trap - TERM INT HUP USR1' USR1
# generate enough nOrder indices (~10000) to fill up 64 kb pipe buffer
# start at 10 so that bash wont try to treat x0_ as an octal
printf '%s\n' {9000..9899} {990000..998999} >&${fd_nOrder}
# now that pipe buffer is full, add additional indices 1000 at a time (as needed)
v9='99'
kkMax='8'
until [[ -f "${tmpDir}"/.quit ]]; do
v9="${v9}9"
kkMax="${kkMax}9"
for (( kk=0 ; kk<=kkMax ; kk++ )); do
kkCur="$(printf '%0.'"${#kkMax}"'d' "$kk")"
{ source /proc/self/fd/0 >&${fd_nOrder}; }<<<"printf '%s\n' {${v9}${kkCur}000..${v9}${kkCur}999}"
done
done
}
} 2>/dev/null
exitTrapStr_kill+="${pOrder_PID} "
else
outStr='>&'"${fd_stdout}";
fi
# setup automatic dynamic nLines adjustment and/or fallocate pre-truncation of (already processed) stdin
if ${nLinesAutoFlag} || ${fallocateFlag}; then
printf '%s\n' ${nLines} >"${tmpDir}"/.nLines
# LOGIC FOR DYNAMICALLY SETTING 'nLines':
# The avg_bytes_per_line is estimated by looking at the byte offset position of fd_read and having each coproc keep track of how many lines it has read
# the new "proposed" 'nLines' is determined by estimating the average bytes per line, then taking the averge of the "current nLines" and "(numbedr unread bytes) / ( (avg bytes per line) * (nProcs) )"
# --> if proposed new 'nLines' is greater than current 'nLines' then use it (use case: stdin is arriving fairly fast, increase 'nLines' to match the rate lines are coming in on stdin)
# --> if proposed new 'nLines' is less than or equal to current 'nLines' ignore it (i.e., nLines can only ever increase...it will never decrease)
# --> if the new 'nLines' is greater than or equal to 'nLinesMax' or the .quit file has appeared, then break after the current iteratrion is finished
{ coproc pAuto {
export LC_ALL=C LANG=C IFS=
trap '[[ -f "'"${tmpDir}"'"/.run/pAuto ]] && \rm -f "'"${tmpDir}"'"/.run/pAuto' EXIT
trap 'trap - TERM INT HUP USR1; kill -INT '"${PID0}"' ${BASHPID}' INT
trap 'trap - TERM INT HUP USR1; kill -TERM '"${PID0}"' ${BASHPID}' TERM
trap 'trap - TERM INT HUP USR1; kill -HUP '"${PID0}"' ${BASHPID}' HUP
trap 'trap - TERM INT HUP USR1' USR1
${fallocateFlag} && {
nWait=$(( 16 + ( ${nProcs} / 2 ) ))
fd_read_pos_old=0
}
${nLinesAutoFlag} && nRead=0
while ${fallocateFlag} || ${nLinesAutoFlag}; do
read -u ${fd_nAuto} -t 0.1
case ${REPLY} in
0)
nLinesAutoFlag=false
fallocateFlag=false
break
;;
'')
nLinesAutoFlag=false
;;
esac
read -r fd_read_pos </proc/self/fdinfo/${fd_read}
fd_read_pos=${fd_read_pos##*$'\t'}
if ${nLinesAutoFlag}; then
read fd_write_pos </proc/self/fdinfo/${fd_write}
fd_write_pos=${fd_write_pos##*$'\t'}
nRead+=${REPLY}
nLinesNew=$(( 1 + ( ${nLinesCur} + ( ( 1 + ${nRead} ) * ( ${fd_write_pos} - ${fd_read_pos} ) ) / ( ${nProcs} * ( 1 + ${fd_read_pos} ) ) ) ))
(( ${nLinesNew} > ${nLinesCur} )) && {
(( ${nLinesNew} >= ${nLinesMax} )) && { nLinesNew=${nLinesMax}; nLinesAutoFlag=false; }
printf '%s\n' ${nLinesNew} >"${tmpDir}"/.nLines
# verbose output
(( ${verboseLevel} > 2 )) && printf '\nCHANGING nLines from %s to %s!!! -- ( nRead = %s ; write pos = %s ; read pos = %s )\n' ${nLinesCur} ${nLinesNew} ${nRead} ${fd_write_pos} ${fd_read_pos} >&${fd_stderr}
nLinesCur=${nLinesNew}
}
fi
if ${fallocateFlag}; then
case ${nWait} in
0)
fd_read_pos=$(( 4096 * ( ${fd_read_pos} / 4096 ) ))
(( ${fd_read_pos} > ${fd_read_pos_old} )) && {
fallocate -p -o ${fd_read_pos_old} -l $(( ${fd_read_pos} - ${fd_read_pos_old} )) "${fPath}"
(( ${verboseLevel} > 2 )) && echo "Truncating $(( ${fd_read_pos} - ${fd_read_pos_old} )) bytes off the start of the tmp file storing stdin" >&${fd_stderr}
fd_read_pos_old=${fd_read_pos}
}
nWait=$(( 16 + ( ${nProcs} / 2 ) ))
;;
*)
((nWait--))
;;
esac
fi
[[ -f "${tmpDir}"/.quit ]] && {
nLinesAutoFlag=false
fallocateFlag=false
}
done
} 2>&${fd_stderr}
} 2>/dev/null
exitTrapStr+='( printf '"'"'0\n'"'"' >&${fd_nAuto0}; ) {fd_nAuto0}>&'"${fd_nAuto}"'; '$'\n'
printf '%s\n' "${pAuto_PID}" > "${tmpDir}"/.run/pAuto
fi
# setup+fork inotifywait (if available)
${inotifyFlag} && {
{
# initially add 1 newline for each coproc to fd_inotify
{ source /proc/self/fd/0 >&${fd_inotify0}; }<<<"printf '%.0s\n' {0..${nProcs}}"
# run inotifywait
(
export LC_ALL=C LANG=C IFS=
trap - EXIT
trap 'trap - TERM INT HUP USR1; kill -INT '"${PID0}"' ${BASHPID}' INT
trap 'trap - TERM INT HUP USR1; kill -TERM '"${PID0}"' ${BASHPID}' TERM
trap 'trap - TERM INT HUP USR1; kill -HUP '"${PID0}"' ${BASHPID}' HUP
trap 'trap - TERM INT HUP USR1' USR1
inotifywait -q -m -e modify,close --format '' "${fPath}" >&${fd_inotify0} &
printf '%s\n' "${!}" >"${tmpDir}"/.run/pNotify
)
pNotify_PID="$(<"${tmpDir}"/.run/pNotify)"
} 2>/dev/null {fd_inotify0}>&${fd_inotify}
exitTrapStr+=': > "'"${tmpDir}"'"/.stdin; '$'\n'
${nOrderFlag} && exitTrapStr+=': >"'"${tmpDir}"'"/.out/.quit; '$'\n'
exitTrapStr_kill+="${pNotify_PID} "
}
# # # # # DYNAMICALLY GENERATE COPROC SOURCE CODE # # # # #
# Due to how the coproc code is dynamically generated and sourced, it cannot directly contain comments. A very brief overview of their function is below.
#
# on each loop, they will acquire a read lock by read {fd_continue}, which blocks them until they have exclusive read access
# they then read N lines with mapfile and check/fix a partial read (or read N bytes with $readBytesProg) and (if -k/-n) read the output order from {fd_nOrder}
# they then release the read lock by sending \n to {fd_continue} (so the next coproc can start to read)
# if no data was read, the coproc will either wait/continue or break, depending on if end conditions are met
# finally (assuming it read data) it will run it through whatever is being parallelized. If -k/-n write [x]$nOrder to {fd_nOrder0} to indicate that index has run / was empty
#
# NOTE: All coprocs share the same {fd_read} file descriptor ( defined just after the end of the main forkrun subshell )
# This has the benefit of keeping the coprocs in sync with each other - when one reads data the {fd_read} used by *all* of them is advanced.
# generate coproc source code template (which, in turn, allows you to then spawn many coprocs very quickly and have many "code branch selection" decisions already resolved)
# this contains the code for the coprocs but has the worker ID represented using {<#>}. coprocs will be sourced via source<<<"${coprocSrcCode//'{<#>}'/${kk}}"
#
# NOTE: because the (uncommented) coproc code generation dynamically adapts to all of forkrun's possible options, this part is...well...hard to follow.
# To see the resulting coproc code for a given set of forkrun options, run: `echo | forkrun -vvvv <FLAGS> :`
echo '0' >"${tmpDir}"/.lastReadPos
coprocSrcCode="$( echo """
local p{<#>} p{<#>}_PID
{ coproc p{<#>} {
export LC_ALL=C LANG=C IFS=
echo \"\${BASH_PID}\" >\"${tmpDir}\"/.run/p{<#>}
trap ': >\"${tmpDir}\"/.quit;
[[ -f \"${tmpDir}\"/.run/p{<#>} ]] && \\rm -f \"${tmpDir}\"/.run/p{<#>};
printf '\"'\"'\n'\"'\"' >&${fd_continue}' EXIT
trap 'trap - TERM INT HUP USR1; kill -INT ${PID0} \${BASHPID}' INT
trap 'trap - TERM INT HUP USR1; kill -TERM ${PID0} \${BASHPID}' TERM
trap 'trap - TERM INT HUP USR1; kill -HUP ${PID0} \${BASHPID}' HUP
trap 'trap - TERM INT HUP USR1' USR1
while true; do"""
${nLinesAutoFlag} && echo "\${nLinesAutoFlag} && read -r <\"${tmpDir}\"/.nLines && [[ \${REPLY} == +([0-9]) ]] && nLinesCur=\${REPLY}"
${nQueueFlag} && echo "printf '%s' '+' >&${fd_nQueue}"
echo """
read -u ${fd_continue}
[[ -f \"${tmpDir}\"/.quit ]] && {
printf '\n' >&${fd_continue}
break
}
[[ -f \"${tmpDir}\"/.done ]] && doneIndicatorFlag=true"""
if ${readBytesFlag}; then
case "${readBytesProg}" in
'dd')
printf 'dd bs=32768 count=%sB of="%s"/.stdin.tmp.{<#>} 2>"%s"/.stdin.tmp-status.{<#>} ' "${nBytes}" "${tmpDir}" "${tmpDir}"
${pipeReadFlag} && printf 'iflag=fullblock <&%s\n' "${fd_stdin}" || printf '<&%s\n' "${fd_read}"
printf '[[ "$(<"%s"/.stdin.tmp-status.{<#>})" == *$'"'"'\\n'"'"'"0 bytes"* ]] && A=() || A[0]=1\n' "${tmpDir}"
;;
'head')
printf 'head -c %s ' "${nBytes}"
${pipeReadFlag} && printf '<&%s ' "${fd_stdin}" || printf '<&%s ' "${fd_read}"
printf '>"%s"/.stdin.tmp.{<#>}\n' "${tmpDir}"
printf '[[ $(<"%s"/.stdin.tmp.{<#>}) ]] 2>/dev/null && A[0]=1 || A=()\n' "${tmpDir}"
;;
'bash')
if ${stdinRunFlag}; then
[[ ${tTimeout} ]] && echo "SECONDS=0"
printf 'if read -r -d '"''"' -n %s -u %s' "${nBytes}" "${fd_read}"
[[ ${tTimeout} ]] && printf ' -t %s' "${tTimeout}"
echo """; then
[[ \${REPLY} ]] && A=(\"\${REPLY}\") || A=('')
trailingNullFlag=true"""
${readBytesExactFlag} && echo 'nBytesRead=1'
echo """
else
[[ \${REPLY} ]] && A=(\"\${REPLY}\") || A=()
trailingNullFlag=false"""
${readBytesExactFlag} && echo 'nBytesRead=0'
echo 'fi'
if ${readBytesExactFlag}; then
echo """
nBytesRead+=\${#REPLY}
[[ \${nBytesRead} == 0 ]] || (( \${nBytesRead} >= ${nBytes} )) || {"""
[[ ${tTimeout} ]] && echo "while (( \${SECONDS} < ${tTimeout} )); do" || echo "while true; do"
echo "[[ -f \"${tmpDir}\"/.done ]] && doneIndicatorFlag=true"
printf "if read -r -d '' -n \$(( ${nBytes} - \${nBytesRead} )) -u ${fd_read}"
[[ ${tTimeout} ]] && printf ' -t %s' "${tTimeout}"
echo """; then
((nBytesRead++))
nBytesRead+=\${#REPLY}
[[ \${REPLY} ]] && A+=(\"\${REPLY}\") || A+=('')
(( \${nBytesRead} >= ${nBytes} )) && { trailingNullFlag=true; break; }
else
trailingNullFlag=false
[[ \${REPLY} ]] && A+=(\"\${REPLY}\")
{ (( \${nBytesRead} >= ${nBytes} )) || ${doneIndicatorFlag}; } && { trailingNullFlag=false; break; }
break
fi
done
}"""
fi
echo """
{
if \${trailingNullFlag}; then
printf '%s\0' \"\${A[@]}\"
else
printf '%s' \"\${A[0]}\"
printf '\0%s' \"\${A[@]:1}\"
fi
} >\"${tmpDir}\"/.stdin.tmp.{<#>}"""
else
printf 'read -r -N %s -u ' "${nBytes}"
if ${readBytesExactFlag}; then
printf '%s ' "${fd_stdin}"
[[ ${tTimeout} ]] && printf '-t %s ' "${tTimeout} "
else
printf '%s ' ${fd_read}
fi
echo '-a A'
fi
;;
esac
else
printf '%s ' "mapfile"
${lseekFlag} && printf '%s ' '-t'
printf '%s ' '-n' "\${nLinesCur}" '-u'
${pipeReadFlag} && printf '%s ' ${fd_stdin} || printf '%s ' ${fd_read}
{ ${pipeReadFlag} || ${nullDelimiterFlag}; } && printf '%s ' '-t'
echo "${delimiterReadStr} A"
${pipeReadFlag} || { ${nullDelimiterFlag} && [[ -z ${nullDelimiterProg} ]]; } || {
echo "[[ \${#A[@]} == 0 ]] || \${doneIndicatorFlag} || {"
if ${lseekFlag}; then
echo """
lseek ${fd_read} -1
read -r -u ${fd_read} -N 1"""
if ${nullDelimiterFlag}; then
echo "[[ \${#REPLY} == 0 ]] || {"
else
echo "[[ \"\${REPLY}\" == ${delimiterVal} ]] || {"
fi
elif ${nullDelimiterFlag}; then
echo """
read -r fd_read_pos </proc/self/fdinfo/${fd_read}"""
case "${nullDelimiterProg}" in
'dd') echo """
{ dd if=\"${fPath}\" bs=1 count=1 ${ddQuietStr} skip=\$(( \${fd_read_pos##*\$'\t'} - 1 )) | read -t 1 -r -d ''; } || {"""
;;
'bash') echo """
read -r fd_read_pos0 </proc/self/fdinfo/${fd_read0}
nBytes=\$(( \${fd_read_pos##*\$'\t'} - \${fd_read_pos0##*\$'\t'} - \${#A[@]} ))"""
if ${ddAvailableFlag}; then
echo """
{
if (( \${nBytes} > 65535 )); then
{ dd if=\"${fPath}\" bs=1 count=1 ${ddQuietStr} skip=\$(( \${fd_read_pos##*\$'\t'} - 1 )) | read -t 1 -r -d ''; }
else
read -r -u ${fd_read0} -N \${nBytes} _
read -r -u ${fd_read0} -d ''
[[ \${#REPLY} == 0 ]]
fi
} || {"""
else
echo """
read -r -u ${fd_read0} -N \${nBytes} _
read -r -u ${fd_read0} -d ''
[[ \${#REPLY} == 0 ]] || {"""
fi
;;
esac
else
echo "[[ \"\${A[-1]: -1}\" == ${delimiterVal} ]] || {"
fi
(( ${verboseLevel} > 2 )) && echo """
echo \"Partial read at: \${A[-1]}\" >&${fd_stderr}"""
echo """
until read -r -u ${fd_read} ${delimiterReadStr}; do
A[-1]+=\"\${REPLY}\";
done"""
printf '%s' "A[-1]+=\"\${REPLY}\""
${lseekFlag} && printf '\n' || printf '%s\n' "${delimiterVal}"
(( ${verboseLevel} > 2 )) && echo "echo \"Partial read fixed to: \${A[-1]}\" >&${fd_stderr}"
echo "}"
}
fi
${pipeReadFlag} || { ${nullDelimiterFlag} && [[ -z ${nullDelimiterProg} ]]; } || ${readBytesFlag} || echo "}"
${nOrderFlag} && echo "read -u ${fd_nOrder} nOrder"
echo """
printf '\\n' >&${fd_continue}"""
${nQueueFlag} && echo "printf '%s' '-' >&${fd_nQueue}"
echo """
[[ \${#A[@]} == 0 ]] && {
\${doneIndicatorFlag} || {
[[ -f \"${tmpDir}\"/.done ]] && {
read -r fd_read_pos </proc/self/fdinfo/${fd_read}
read -r fd_write_pos </proc/self/fdinfo/${fd_write}
[[ \"\${fd_read_pos##*$'\t'}\" == \"\${fd_write_pos##*$'\t'}\" ]] && doneIndicatorFlag=true
}
}
if \${doneIndicatorFlag} || [[ -f \"${tmpDir}\"/.quit ]]; then"""
${nLinesAutoFlag} && echo "printf '\\n' >&\${fd_nAuto0}"
${nOrderFlag} && echo ": >\"${tmpDir}\"/.out/.quit{<#>}"
${nQueueFlag} && echo "\printf '%s' '0' >&${fd_nQueue}"
${inotifyFlag} && echo 'kill -9 '"${pNotify_PID}"' 2>/dev/null'
echo """
: >\"${tmpDir}\"/.quit
printf '%.0s\\n' \"${tmpDir}\"/.run/p* >&${fd_continue}
break"""
{ ${inotifyFlag} || ${nOrderFlag}; } && echo "else"
${nOrderFlag} && echo "printf 'x%s\n' \"\${nOrder}\" >&\${fd_nOrder0}"
${inotifyFlag} && echo "[[ -f \"${tmpDir}\"/.done ]] && doneIndicatorFlag=true || read -u ${fd_inotify}"
echo """
fi
continue
}"""
${nLinesAutoFlag} && { printf '%s' """
\${nLinesAutoFlag} && {
printf '%s\\n' \${#A[@]} >&\${fd_nAuto0}
(( \${nLinesCur} < ${nLinesMax} )) || nLinesAutoFlag=false
}"""
${fallocateFlag} && printf '%s' ' || ' || echo
}
${fallocateFlag} && echo "printf '\\n' >&\${fd_nAuto0}"
${pipeReadFlag} || ${nullDelimiterFlag} || ${readBytesFlag} || ${lseekFlag} || {
echo """
{ [[ \"\${A[*]##*${delimiterVal}}\" ]] || [[ -z \${A[0]} ]]; } && {"""
(( ${verboseLevel} > 2 )) && echo "echo \"FIXING SPLIT READ\" >&${fd_stderr}"
echo """
A[-1]=\"\${A[-1]%${delimiterVal}}\"
IFS=
mapfile ${delimiterReadStr} A <<<\"\${A[*]}\"
}"""
}
${subshellRunFlag} && echo '(' || echo '{'
{ ${exportOrderFlag} || { ${nOrderFlag} && ${substituteStringIDFlag}; }; } && echo 'nOrder0="$(( ${nOrder##*(9)*(0)} + ${nOrder%%*(0)${nOrder##*(9)*(0)}}0 - 9 ))"'
${exportOrderFlag} && echo "printf '\034%s:\035\n' \"\${nOrder0}\""
${noFuncFlag} && echo 'IFS=$'"'"'\n'"'"
printf '%s ' "${runCmd[@]}"
if ${readBytesFlag} && ! { [[ ${readBytesProg} == 'bash' ]] && ! ${stdinRunFlag}; }; then
if ${stdinRunFlag} || ${noFuncFlag}; then
printf '<"%s"/%s' "${tmpDir}" '.stdin.tmp.{<#>}'
else
printf '"$(<"%s"/%s)"' "${tmpDir}" '.stdin.tmp.{<#>}'
fi
else
if ${stdinRunFlag}; then
printf '<<<%s' "\"\${A[@]${delimiterRemoveStr}}\""
elif ${noFuncFlag}; then
printf "<<<\"\${A[*]%s}\"" "${delimiterRemoveStr}"
elif ! ${substituteStringFlag}; then
printf '%s' "\"\${A[@]${delimiterRemoveStr}}\""
fi
fi
(( ${verboseLevel} > 2 )) && echo """ || {
{
printf '\\n\\n----------------------------------------------\\n\\n'
echo 'ERROR DURING \"${runCmd[*]}\" CALL'
declare -p A nLinesCur nLinesAutoFlag
echo 'fd_read:'
cat /proc/self/fdinfo/${fd_read}
echo 'fd_write:'
cat /proc/self/fdinfo/${fd_write}
echo
} >&${fd_stderr}
}"""
${readBytesFlag} && { [[ ${readBytesProg//bash/} ]] || ${stdinRunFlag}; } && printf '\n\\rm -f "'"${tmpDir}"'"/.stdin.tmp.{<#>}\n'
${noFuncFlag} && echo 'IFS='
${subshellRunFlag} && printf '\n%s ' ')' || printf '\n%s ' '}'
echo "${outStr}"
${nOrderFlag} && echo "printf '%s\n' \"\${nOrder}\" >&${fd_nOrder0}"
echo """
done
} 2>&${fd_stderr} {fd_nAuto0}>&${fd_nAuto}
} 2>/dev/null
p_PID+=(\${p{<#>}_PID})""" )"
# set traps (dynamically determined based on which option flags were active)
# if ordering output print the remaining ones in trap
${nOrderFlag} && exitTrapStr+='cat </dev/null "'"${tmpDir}"'"/.out/x* >&'"${fd_stdout}"'; '$'\n'
# make sure all processes are dead
exitTrapStr+='kill $(cat </dev/null "'"${tmpDir}"'"/.run/p* 2>/dev/null) 2>/dev/null;