-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathkilltree.bash
executable file
·1199 lines (1035 loc) · 31.1 KB
/
killtree.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
#!/bin/bash
[ -n "${BASH_VERSION}" ] && \
eval '[[ BASH_VERSINFO -ge 4 || (BASH_VERSINFO -eq 3 && BASH_VERSINFO[1] -ge 2) ]]' || {
echo "This script requires Bash version 3.2 or newer to run." >&2
exit 1
}
set -f +o posix && shopt -s extglob || exit 1
# ------------------------------------------------------------------------------
#
# killtree
#
# Sends signals to process trees with style.
#
# It uses pgrep to find processes.
#
# Usage: killtree[.bash] [options] [--] [[pattern|pid][/'filter_opts']] ...
# [// [filter_opts] [--] [[pattern|pid][/'filter_opts']] ...]
# [// [filter_opts] [--] [[pattern|pid][/'filter_opts']] ...]
#
# Disclaimer: This tool comes with no warranty.
#
# Author: konsolebox
# Copyright Free / Public Domain
# May 12, 2022
#
# ------------------------------------------------------------------------------
# kill_tree (pid, [signal = SIGTERM])
#
# Creates a list of all the processes in the hierarchy first, and then sends
# signal to all of them simultaneously.
#
function kill_tree {
local DESCENDANTS=()
list_descendants_inner "$1"
kill -s "${2-SIGTERM}" "$1" "${DESCENDANTS[@]}"
}
# kill_tree_2 (pid, [signal = SIGTERM])
#
# This version sends signals to processes one at a time. It sends signal
# to a process right after it finishes enumerating the child processes of the
# process, and then it processes the child processes if they exist, or move to
# the next process in queue.
#
function kill_tree_2 {
local s=${2-SIGTERM} CHILDREN __
list_children "$1"
kill -s "$s" "$1"
for __ in "${CHILDREN[@]}"; do
kill_tree_2 "$__" "$s"
done
}
# kill_tree_3 (pid, [signal = SIGTERM])
#
# This version does reverse mode. It sends signals to child processes first
# before the parents.
#
function kill_tree_3 {
local s=${2-SIGTERM} CHILDREN __
list_children "$1"
for __ in "${CHILDREN[@]}"; do
kill_tree_3 "$__" "$s"
done
kill -s "$s" "$1"
}
# kill_descendants (pid, [signal = SIGTERM])
#
# Same as kill_tree, but it only sends signals to the descendants of the
# specified target.
#
function kill_descendants {
local DESCENDANTS=()
list_descendants_inner "$1"
[[ ${#DESCENDANTS[@]} -gt 0 ]] && kill -s "${2-SIGTERM}" "${DESCENDANTS[@]}"
}
# kill_descendants_2 (pid, [signal = SIGTERM])
#
# Same as kill_tree_2, but it only sends signals to the descendants of the
# specified target.
#
function kill_descendants_2 {
local s=${2-SIGTERM} CHILDREN __
list_children "$1"
for __ in "${CHILDREN[@]}"; do
kill_tree_2 "$__" "$s"
done
}
# kill_descendants_3 (pid, [signal = SIGTERM])
#
# Same as kill_tree_3, but it only sends signals to the descendants of the
# specified target.
#
function kill_descendants_3 {
local s=${2-SIGTERM} CHILDREN __
list_children "$1"
for __ in "${CHILDREN[@]}"; do
kill_tree_3 "$__" "$s"
done
}
# kill_children (pid, [signal = SIGTERM])
#
# Sends signals to direct descendants of specified target.
#
function kill_children {
local CHILDREN
list_children "$1"
kill -s "${2-SIGTERM}" "${CHILDREN[@]}"
}
# list_tree (pid)
#
# Saves a list of found PIDs that composes the hierarchy of the specified PID
# including the PID to array variable TREE.
#
function list_tree {
local DESCENDANTS=()
list_descendants_inner "$1"
TREE=("$1" "${DESCENDANTS[@]}")
}
# list_descendants (pid)
#
# Saves list of found PIDs that are descendants of specified PID to array
# variable DESCENDANTS.
#
function list_descendants {
DESCENDANTS=()
list_descendants_inner "$1"
}
# list_descendants_inner (pid)
#
# Inner recursive function of list_descendants(). It doesn't initialize the
# DESCENDANTS variable.
#
function list_descendants_inner {
local CHILDREN __
list_children "$1"
DESCENDANTS+=("${CHILDREN[@]}")
for __ in "${CHILDREN[@]}"; do
list_descendants_inner "$__"
done
}
# list_children (pid)
#
# Saves list of found PIDs that are direct descendants of specified PID to array
# variable CHILDREN.
#
function list_children {
IFS=$'\n' read -ra CHILDREN -d '' < <(exec pgrep -P "$1")
}
# ------------------------------------------------------------------------------
ASK=false
ASK_ONCE=false
EXCLUDED_SELF=false
FILTER_EUIDS=()
FILTER_EXACT=()
FILTER_EXACT_DEFAULT=false
FILTER_EXACT_SUPER=
FILTER_GROUPS=()
FILTER_IGNORE_CASE=()
FILTER_IGNORE_CASE_DEFAULT=false
FILTER_IGNORE_CASE_SUPER=
FILTER_NSLIST=()
FILTER_NS=()
FILTER_PGROUPS=()
FILTER_SESSION=()
FILTER_TERMINAL=()
FILTER_UIDS=()
HAS_GEN_FILTERS=false
IFS=$' \t\r\n'
INITIAL_TARGET_PIDS=()
LAST_PRI_TARGET_ID=0
LAST_SEC_TARGET_ID=0
LAST_TER_TARGET_ID=0
PRETEND=false
SEC_FILTER_ARGS=()
SEC_FILTER_ID=0
SEC_FILTER_INDICES=()
SEC_FILTER_LENGTHS=()
SEC_FILTER_PIDS=()
SEC_GLOBAL_ID=0
SELF=${BASHPID-$$}
TARGETS=()
TARGET_ID=0
TER_FILTER_ARGS=()
TER_FILTER_ID=0
TER_FILTER_INDICES=()
TER_FILTER_LENGTHS=()
TER_FILTER_PIDS=()
TER_GLOBAL_ID=0
VERBOSE=false
VERSION=2022.05.12
function show_help_info {
echo "killtree ${VERSION}
Sends signals to process trees with style.
Usage: killtree[.bash] [options] [--] [[pattern|pid][/'filter_opts']] ...
[// [filter_opts] [--] [[pattern|pid][/'filter_opts']] ...]
[// [filter_opts] [--] [[pattern|pid][/'filter_opts']] ...]
This script uses pgrep. Expansion of pattern depends on how pgrep expands it.
See pgrep(1). To prevent a pattern from being interpreted as a PID, place it
around parentheses. E.g. '(1234)'.
Basic Options:
-a, --ask Ask before sending a signal to each process. PIDs are
resolved to their command names in prompt if the system
is Linux. Verbose mode makes it show long commands
instead of the basic \"comm\" form.
-A, --ask-once Same as '--ask', but only do it once on every major set
of processes. This can only be used with
'--simultaneous' and '--union'.
-h, --help Show this help message and exit.
-H, --ignore-sighup Catch SIGHUP signal and ignore it.
-P, --pretend Do no actually send signals. Useful with '--verbose'.
-q, --quiet Do not show warnings and info. It negates verbose mode.
-s, --signal signal Specify the signal to send to every process.
The default is SIGTERM.
-<signal> Shortcut version of '-s'. Signal can only be numeric.
-v, --verbose Show verbose messages. It negates quiet mode.
-V, --version Show version and exit.
Filter Options:
-e, --euid euid,... Only match processes with mentioned effective user ID.
-g, --group gid,... Only match processes with mentioned real group ID.
-i, --ignore-case Make matching of processes case-insensitive.
-I, --no-ignore-case Do not make matching of processes case-insensitive.
-n, --ns pid Only match processes that belong to same namespace as
PID. This may not be supported by pgrep or system.
-N, --nslist name,... Limit the namespaces to match processes with when
using '--ns'. Available namespaces are 'ipc', 'mnt',
'net', 'pid', 'user', and 'uts'. This may not be
supported by pgrep or the system.
-p, --pgroup pgid,... Only match processes with mentioned process group ID.
-u, --uid uid,... Only match processes with mentioned real user ID.
-z, --session sid,... Only match processes with mentioned session ID.
-T, --terminal tty,... Only match processes with mentioned controlling
terminal.
-x, --exact Match process names in an exact manner.
-X, --no-exact Do not match process names in an exact manner.
Superglobal Filter Options:
-Gi, --global-ignore-case Superglobal version of '--ignore-case'.
-GI, --global-no-ignore-case Superglobal version of '--no-ignore-case'.
-Gx, --global-exact Superglobal version of '--exact'.
-GX, --global-no-exact Superglobal version of '--no-exact'.
Exact mode by default is set to ${FILTER_EXACT_DEFAULT}.
Ignore-case mode by default is set to ${FILTER_IGNORE_CASE_DEFAULT}.
Target Options:
-c, --children[-only] Only send signals to direct child processes.
-d, --descendants[-only] Only send signals to descendant processes.
-t, --tree Send signals to all processes in a tree including
the initial parent. (Default)
Strategy Options:
-o, --one-at-a-time Immediately send signal to a process in a tree after
enumerating the process' child processes.
-r, --reverse Send signals to child processes first before parents in a
tree.
-S, --simultaneous Simultaneously send signals to all processes in a tree
after they get enumerated. (Default)
-U, --unify Uniquely gather all PIDs in every tree of every specified
PID before sending signals to all of them at once. The
options '--children' and '--descendants' are still
respected when generating targets in every tree, but the
initial parent targets of those trees won't get exempted
from being targetted if they are part of another initial
target's tree, even when one of those options is in
effect.
Filtering Details
Filtering happens in three phrases. The first phase collects and filters
initial parent targets of trees. The second phase collects and filters child
processes. The third phase finally, selects which processes to actually send
signals to.
Each phase is configured separately with their own filters and/or
patterns/PIDs, and each phase configuration is separated by '//'.
Filter options generally can be declared global or pattern/pid-specific.
Global options affect how all patterns behave for a specific phase, while
pattern/PID-specific options are the most basic, and they affect a single
matching set criteria. Some filter options have superglobal versions which
can affect all phases. Global filters override superglobal filters, and
pattern/PID-specific filters override global filters.
Each pattern/PID-filter-opts pair produces their own set of matched PIDs and
doesn't affect other pairs. All PIDs matched by all pairs are unified to a
single set. If no pattern/PID-filter-opts pair is specified, the global
filter options are used instead.
Specifying global filter options and/or specifying pattern/PID-filter-opts is
only required in the first phase where initial targets are generated. When
no filtering expression is specified in other phases, no other extra filtering
happens.
Using '--ns' and '--nslist' to match processes may not work if
namespace-related features are not supported by the system, or the feature
itself is not supported by pgrep. Support for these features was added in
procps-ng-3.3.9. It may also be not included during pgrep's build time.
Target Mode and Strategy Details
The default action is to send signals to all processes simultaneously.
If '--one-at-a-time', '--reverse', '--simultaneous', and '--unify' are used
together, only the last specified option becomes effective. The behavior
applies to '--children', '--descendants', and '--tree' as well. It allows
cancelling out default arguments.
When the '--children' option is in effect, the options '--one-at-a-time',
'--reverse', and '--simultaneous' are virtually the same since targets belong
to only one level.
Other Details
killtree excludes itself from matched targets. It also prints a warning
message if its own PID is specified.
Just like pgrep, killtree also silently ignores specified processes that don't
exist.
Exit Status
The script returns 0 only when one or more processes are processed.
Examples
killtree --descendants --reverse --signal SIGKILL --exact -- 1234 zombie
killtree --unify --terminal tty5 --signal SIGHUP // // --exact bash"
}
function log_info {
printf '%s\n' "$@"
}
function log_warning {
printf 'Warning: %s\n' "$@" >&2
}
function log_verbose {
printf '%s\n' "$@"
}
function fail {
printf '%s\n' "$@" >&2
exit 2
}
function check_if_valid_name_or_id_list_arg {
local opt=$1 arg=$2 has_entry=false IFS=, __
[[ ${arg} ]] || fail "Invalid empty argument to '${opt}'."
for __ in ${arg}; do
if [[ ${arg} ]]; then
[[ ${arg} != @(+([[:digit:]])|+([[:lower:]])*([[:lower:][:digit:]-])) ]] && \
log_warning "Username or group name argument to '${opt}' may be invalid: $__"
has_entry=true
fi
done
[[ ${has_entry} == false ]] && \
fail "Specified list argument to '${opt}' is empty: ${arg}"
[[ ${arg} == @(,*|*,,*|*,) ]] && \
log_warning "Ignoring empty elements in list argument to '${opt}': ${arg}"
}
function check_if_valid_id_list_arg {
local opt=$1 arg=$2 has_entry=false IFS=, __
[[ ${arg} ]] || fail "Invalid empty argument to '${opt}'."
for __ in ${arg}; do
if [[ ${arg} ]]; then
[[ ${arg} != +([[:digit:]]) ]] && \
fail "Invalid ID argument to '${opt}': $__"
has_entry=true
fi
done
[[ ${has_entry} == false ]] && \
fail "Specified list argument to '${opt}' is empty: ${arg}"
[[ ${arg} == @(,*|*,,*|*,) ]] && \
log_warning "Ignoring empty elements in list argument to '${opt}': ${arg}"
}
function check_if_valid_nslist_arg {
local opt=$1 arg=$2 IFS=, __
for __ in ${arg}; do
if [[ ${arg} ]]; then
[[ ${arg} == @(ipc|mnt|net|pid|user|uts) ]] || \
fail "Invalid namespace argument to '${opt}': $__" \
"Expecting 'ipc', 'mnt', 'net', 'pid', 'user', or 'uts'."
has_entry=true
fi
done
[[ ${has_entry} == false ]] && \
fail "Specified list argument to '${opt}' is empty: ${arg}"
[[ ${arg} == @(,*|*,,*|*,) ]] && \
log_warning "Ignoring empty elements in list argument to '${opt}': ${arg}"
}
function check_if_valid_pid_arg {
[[ $2 == +([[:digit:]]) ]] || fail "Invalid PID argument to '$1': $2"
}
function check_if_not_empty_arg {
[[ $2 ]] || fail "Invalid empty argument to '$1'."
}
function warn_excluding_self {
if [[ ${VERBOSE} == true || ${EXCLUDED_SELF} == false ]]; then
log_warning "Excluding self ($__) from matches."
EXCLUDED_SELF=true
fi
}
function exclude_self {
__A0=()
local __
for __; do
[[ $__ != "${SELF}" ]] && __A0+=("$__") || warn_excluding_self
done
}
function get_opt_and_optarg {
OPT=$1 OPTARG= OPTSHIFT=0
if [[ $1 == -[!-]?* ]]; then
OPT=${1:0:2} OPTARG=${1:2}
elif [[ $1 == --*=* ]]; then
OPT=${1%%=*} OPTARG=${1#*=}
elif [[ ${2+.} ]]; then
OPTARG=$2 OPTSHIFT=1
else
fail "No argument specified for '$1'."
fi
return 0
}
function process_opt_with_arg {
local checker=$1 arg_is_list=$2
get_opt_and_optarg "${@:3}"
[[ ${arg_is_list} == true ]] && OPTARG=${OPTARG//+(,)/,} OPTARG=${OPTARG#,} OPTARG=${OPTARG%,}
"${checker}" "${OPT}" "${OPTARG}"
__I0=$(( OPTSHIFT + 1 ))
HAS_ARG=true
}
function parse_filter_opts {
local id=$1 HAS_ARG=false
shift
case $1 in
-e*|--euid?(=*))
process_opt_with_arg check_if_valid_name_or_id_list_arg true "$@"
FILTER_EUIDS[id]+=,${OPTARG}
;;
-g*|--group?(=*))
process_opt_with_arg check_if_valid_name_or_id_list_arg true "$@"
FILTER_GROUPS[id]+=,${OPTARG}
;;
-i|--ignore-case)
FILTER_IGNORE_CASE[id]=true
__I0=1
;;
-I|--no-ignore-case)
FILTER_IGNORE_CASE[id]=false
__I0=1
;;
-n*|--ns?(=*))
process_opt_with_arg check_if_valid_pid_arg false "$@"
FILTER_NS[id]=${OPTARG}
;;
-N*|--nslist?(=*))
process_opt_with_arg check_if_valid_nslist_arg true "$@"
FILTER_NSLIST[id]+=,${OPTARG}
;;
-p*|--pgroup?(=*))
process_opt_with_arg check_if_valid_id_list_arg true "$@"
FILTER_PGROUPS[id]+=,${OPTARG}
;;
-T*|--terminal?(=*))
process_opt_with_arg check_if_not_empty_arg true "$@"
FILTER_TERMINAL[id]+=,${OPTARG}
;;
-u*|--uid?(=*))
process_opt_with_arg check_if_valid_name_or_id_list_arg true "$@"
FILTER_UIDS[id]+=,${OPTARG}
;;
-x|--exact)
FILTER_EXACT[id]=true
__I0=1
;;
-X|--no-exact)
FILTER_EXACT[id]=false
__I0=1
;;
-z*|--session?(=*))
process_opt_with_arg check_if_valid_id_list_arg true "$@"
FILTER_SESSION[id]+=,${OPTARG}
;;
-[!-][!-]*)
parse_filter_opts "${id}" "-${1:0:2}" && parse_filter_opts "${id}" "-${1:2}" "${@:2}"
return
;;
*)
__I0=0
return 1
;;
esac
[[ SEC_GLOBAL_ID -eq 0 && ${HAS_ARG} == true ]] && HAS_GEN_FILTERS=true
return 0
}
function parse_target_expr {
local target opts
if [[ ${1//[!/]} == *//* ]]; then
fail "Unexpected use of too many '/' in argument: $1"
elif [[ $1 == */* ]]; then
target=${1%%/*} opts=${1#*/}
else
target=$1 opts=
fi
(( ++TARGET_ID ))
[[ ${target} ]] && TARGETS[TARGET_ID]=${target}
set -- ${opts}
while [[ $# -gt 0 ]]; do
parse_filter_opts "${TARGET_ID}" "${@:1:2}" || \
fail "Invalid or unexpected argument in options list of target '${target}': $1"
shift "$__I0"
done
}
function get_merged_list {
local var=$1 all= unique= IFS=,
shift
for __; do
__=${var}[$__]
[[ ${!__-} ]] && all+=,${!__}
done
for __ in ${all#,}; do
[[ $__ && ${unique}, != *,"$__",* ]] && unique+=,$__
done
__=${unique#,}
[[ $__ ]]
}
function is_effectively_true {
local IFS=,
[[ ,"$*" == *,true*(,) ]]
}
function get_pgrep_opts {
local id=$1 gid=0
PGREP_OPTS=() PGREP_MOD_OPTS=()
if [[ ${2-} == @sec ]]; then
gid=${SEC_GLOBAL_ID}
elif [[ ${2-} == @ter ]]; then
gid=${TER_GLOBAL_ID}
fi
if [[ id -ne gid ]]; then
set -- "${gid}" "${id}"
else
set -- "${id}"
fi
get_merged_list FILTER_EUIDS "$@" && PGREP_OPTS+=(--euid="$__")
get_merged_list FILTER_GROUPS "$@" && PGREP_OPTS+=(--group="$__")
get_merged_list FILTER_NSLIST "$@"&& PGREP_OPTS+=(--nslist="$__")
get_merged_list FILTER_NS "$@" && PGREP_OPTS+=(--ns="$__")
get_merged_list FILTER_PGROUPS "$@" && PGREP_OPTS+=(--pgroup="$__")
get_merged_list FILTER_SESSION "$@" && PGREP_OPTS+=(--session="$__")
get_merged_list FILTER_TERMINAL "$@" && PGREP_OPTS+=(--terminal="$__")
get_merged_list FILTER_UIDS "$@" && PGREP_OPTS+=(--uid="$__")
is_effectively_true "${FILTER_EXACT_DEFAULT}" "${FILTER_EXACT_SUPER}" "${FILTER_EXACT[gid]-}" \
"${FILTER_EXACT[id]-}" && PGREP_MOD_OPTS+=(--exact)
is_effectively_true "${FILTER_IGNORE_CASE_DEFAULT}" "${FILTER_IGNORE_CASE_SUPER}" \
"${FILTER_IGNORE_CASE[gid]-}" "${FILTER_IGNORE_CASE[id]-}" && \
PGREP_MOD_OPTS+=(--ignore-case)
}
function collect_initial_targets {
local id PGREP_OPTS phrase pids target target_pids=() reg=() opts=() pid
for (( id = 0; id <= LAST_PRI_TARGET_ID; ++id )); do
[[ ${TARGETS[id]+.} ]] && target=${TARGETS[id]} || target=()
get_pgrep_opts "${id}"
if [[ ${target-} == +([[:digit:]]) ]]; then
if [[ ${target} == "${SELF}" ]]; then
warn_excluding_self
elif [[ ${PGREP_OPTS+.} ]]; then
for pid in $(pgrep "${PGREP_OPTS[@]}"); do
if [[ ${target} == "${pid}" ]]; then
target_pids+=("${target}")
break
fi
done
else
target_pids+=("${target}")
fi
elif [[ ${target+.} || ${PGREP_OPTS+.} && (id -gt 0 || LAST_PRI_TARGET_ID -eq 0) ]]; then
opts=("${PGREP_OPTS[@]}" "${PGREP_MOD_OPTS[@]}")
pids=($(pgrep "${opts[@]}" -- "${target[@]}"))
exclude_self "${pids[@]}"
if [[ (${#__A0[@]} -eq 0 && ${quiet} == false) || ${VERBOSE} == true ]]; then
if [[ ${target+.} && ${opts+.} ]]; then
phrase="pattern '${target}' and pgrep options '${opts[*]}'"
elif [[ ${target+.} ]]; then
phrase="pattern '${target}'"
else
phrase="pgrep option(s) '${opts[*]}'"
fi
fi
if [[ ${#__A0[@]} -eq 0 ]]; then
log_info "No targets matched using ${phrase}."
else
[[ ${VERBOSE} == true ]] && log_verbose "Targets matching ${phrase}: ${__A0[*]}"
target_pids+=("${__A0[@]}")
fi
fi
done
if [[ ${#target_pids[@]} -eq 0 ]]; then
log_info 'No targets matched expressions.'
return 1
fi
for id in "${target_pids[@]}"; do
if [[ -z ${reg[id]+.} ]]; then
INITIAL_TARGET_PIDS+=("${id}")
reg[id]=.
fi
done
return 0
}
function prepare_secondary_filter {
if [[ SEC_GLOBAL_ID -gt 0 ]]; then
local id PGREP_OPTS target args index
for (( id = SEC_GLOBAL_ID; (id == SEC_GLOBAL_ID || id <= LAST_SEC_TARGET_ID); ++id )); do
[[ ${TARGETS[id]+.} ]] && target=${TARGETS[id]} || target=()
get_pgrep_opts "${id}" @sec
if [[ ${target-} == +([[:digit:]]) ]]; then
if [[ ${target} == "${SELF}" ]]; then
warn_excluding_self
else
args=("${PGREP_OPTS[@]}")
SEC_FILTER_INDICES[SEC_FILTER_ID]=${#SEC_FILTER_ARGS[@]}
SEC_FILTER_LENGTHS[SEC_FILTER_ID]=${#args[@]}
SEC_FILTER_PIDS[SEC_FILTER_ID++]=${target}
SEC_FILTER_ARGS+=("${args[@]}")
fi
elif [[ ${target+.} || ${PGREP_OPTS+.} && (id -gt SEC_GLOBAL_ID || \
LAST_SEC_TARGET_ID -eq 0) ]]; then
args=("${PGREP_OPTS[@]}" "${PGREP_MOD_OPTS[@]}" -- "${target[@]}")
SEC_FILTER_INDICES[SEC_FILTER_ID]=${#SEC_FILTER_ARGS[@]}
SEC_FILTER_LENGTHS[SEC_FILTER_ID++]=${#args[@]}
SEC_FILTER_ARGS+=("${args[@]}")
fi
done
if [[ ${#SEC_FILTER_INDICES[@]} -eq 0 ]]; then
function list_children {
CHILDREN=($(pgrep -P "$1"))
}
elif [[ ${#SEC_FILTER_INDICES[@]} -eq 1 ]]; then
function list_children {
local i=${!SEC_FILTER_INDICES[*]} args pid
args=("${SEC_FILTER_ARGS[@]:${SEC_FILTER_INDICES[i]}:${SEC_FILTER_LENGTHS[i]}}")
pid=${SEC_FILTER_PIDS[i]-}
declare -p args
CHILDREN=($(pgrep -P "$1" "${args[@]}"))
if [[ ${pid} ]]; then
[[ " ${CHILDREN[*]} " == *" ${pid} "* ]] && CHILDREN=("${pid}") || CHILDREN=()
fi
}
else
function do_secondary_filter {
__A0=()
if [[ $# -gt 0 ]]; then
local pids=() args pid i
for i in "${!SEC_FILTER_INDICES[@]}"; do
args=("${SEC_FILTER_ARGS[@]:${SEC_FILTER_INDICES[i]}:${SEC_FILTER_LENGTHS[i]}}")
pid=${SEC_FILTER_PIDS[i]-}
if [[ ${args+.} ]]; then
for i in $(pgrep "${args[@]}"); do
[[ -z ${pid} || ${pid} == "$i" ]] && pids[i]=.
done
elif [[ ${pid} ]]; then
pids[pid]=.
fi
done
for i; do
[[ ${pids[i]+.} ]] && __A0+=("$i")
done
fi
}
function list_children {
do_secondary_filter $(pgrep -P "$1")
CHILDREN=("${__A0[@]}")
}
fi
fi
}
function prepare_tertiary_filter {
if [[ TER_GLOBAL_ID -gt 0 ]]; then
local id PGREP_OPTS target args
for (( id = TER_GLOBAL_ID; id == TER_GLOBAL_ID || id <= LAST_TER_TARGET_ID; ++id )); do
[[ ${TARGETS[id]+.} ]] && target=${TARGETS[id]} || target=()
get_pgrep_opts "${id}" @ter
if [[ ${target-} == +([[:digit:]]) ]]; then
if [[ ${target} == "${SELF}" ]]; then
warn_excluding_self
else
args=("${PGREP_OPTS[@]}")
TER_FILTER_INDICES[TER_FILTER_ID]=${#TER_FILTER_ARGS[@]}
TER_FILTER_LENGTHS[TER_FILTER_ID]=${#args[@]}
TER_FILTER_PIDS[TER_FILTER_ID++]=${target}
TER_FILTER_ARGS+=("${args[@]}")
fi
elif [[ ${target+.} || ${PGREP_OPTS+.} && (id -gt TER_GLOBAL_ID || \
LAST_TER_TARGET_ID -eq 0) ]]; then
args=("${PGREP_OPTS[@]}" "${PGREP_MOD_OPTS[@]}" -- "${target[@]}")
TER_FILTER_INDICES[TER_FILTER_ID]=${#TER_FILTER_ARGS[@]}
TER_FILTER_LENGTHS[TER_FILTER_ID++]=${#args[@]}
TER_FILTER_ARGS+=("${args[@]}")
fi
done
fi
if [[ ${#TER_FILTER_INDICES[@]} -gt 0 ]]; then
function do_tertiary_filter {
__A0=()
if [[ $# -gt 0 ]]; then
local pids=() args pid i
for i in "${!TER_FILTER_INDICES[@]}"; do
args=("${TER_FILTER_ARGS[@]:${TER_FILTER_INDICES[i]}:${TER_FILTER_LENGTHS[i]}}")
pid=${TER_FILTER_PIDS[i]-}
if [[ ${args+.} ]]; then
for i in $(pgrep "${args[@]}"); do
[[ -z ${pid} || ${pid} == "$i" ]] && pids[i]=.
done
elif [[ ${pid} ]]; then
pids[pid]=.
fi
done
for i; do
[[ ${pids[i]+.} ]] && __A0+=("$i")
done
fi
}
else
function do_tertiary_filter {
__A0=("$@")
}
fi
}
function get_process_cmd {
CMD=
if [[ ${VERBOSE} == true && -r /proc/$1/cmdline ]]; then
local REPLY
while read -rd ''; do
CMD+="${REPLY} "
done < "/proc/$1/cmdline"
CMD=${CMD% }
elif [[ -r /proc/$1/comm ]]; then
IFS= read -r CMD < "/proc/$1/comm"
fi
}
function ask_for_yn {
for (( ;; )); do
IFS= read -n1 -d '' -p "$1"
[[ ${REPLY} != $'\n' ]] && echo
case ${REPLY} in
[yY])
return 0
;;
[nN])
return 1
;;
esac
echo "Please say Y or N."
done
}
function ask_send_sig {
local signal=$1 CMD __
shift
if [[ $# -eq 0 ]]; then
return 1
elif [[ $# -eq 1 ]]; then
get_process_cmd "$1"
ask_for_yn "Send ${signal} to $1${CMD:+" (${CMD})"}? "
else
local i=0 l __
for __; do
i=${#__}
[[ i -gt l ]] && l=$i
done
echo "Send ${signal} to these processes? " >&2
printf '%*s %s\n' "$l" PID CMD >&2
for __; do
get_process_cmd "$__"
printf '%*s %s\n' "$l" "$__" "${CMD}" >&2
done
ask_for_yn "> "
fi
}
function setup_kill_function {
if [[ ${VERBOSE} == true ]]; then
if [[ ${ASK} == true ]]; then
function kill {
local __
exclude_self "${@:3}"
do_tertiary_filter "${__A0[@]}"
for __ in "${__A0[@]}"; do
ask_send_sig "$2" "$__" || continue
log_verbose "Sending $2 to: $__"
[[ ${PRETEND} != true ]] && builtin kill -s "$2" "$__"
done
}
elif [[ ${ASK_ONCE} == true ]]; then
function kill {
exclude_self "${@:3}"
do_tertiary_filter "${__A0[@]}"
if [[ ${#__A0[@]} -gt 0 ]] && ask_send_sig "$2" "${__A0[@]}"; then
log_verbose "Sending $2 to: ${__A0[*]}"
[[ ${PRETEND} != true ]] && builtin kill -s "$2" "${__A0[@]}"
fi
}
else
function kill {
exclude_self "${@:3}"
do_tertiary_filter "${__A0[@]}"
if [[ ${#__A0[@]} -gt 0 ]]; then
log_verbose "Sending $2 to: ${__A0[*]}"
[[ ${PRETEND} != true ]] && builtin kill -s "$2" "${__A0[@]}"
fi
}
fi
else
if [[ ${ASK} == true ]]; then
function kill {
local __
exclude_self "${@:3}"
do_tertiary_filter "${__A0[@]}"
for __ in "${__A0[@]}"; do
ask_send_sig "$2" "$__" && [[ ${PRETEND} != true ]] && \
builtin kill -s "$2" "$__"
done
}
elif [[ ${ASK_ONCE} == true ]]; then
function kill {
exclude_self "${@:3}"
do_tertiary_filter "${__A0[@]}"
[[ ${#__A0[@]} -gt 0 ]] && ask_send_sig "$2" "${__A0[@]}" && \
[[ ${PRETEND} != true ]] && builtin kill -s "$2" "${__A0[@]}"
}
else
function kill {
exclude_self "${@:3}"
do_tertiary_filter "${__A0[@]}"
[[ ${#__A0[@]} -gt 0 && ${PRETEND} != true ]] && builtin kill -s "$2" "${__A0[@]}"
}
fi
fi
}
function parse_tertiary_args {
TER_GLOBAL_ID=$(( ++TARGET_ID ))
while [[ $# -gt 0 ]]; do
if parse_filter_opts "${TER_GLOBAL_ID}" "${@:1:2}"; then
shift "$__I0"
else
case $1 in
--)
while shift; [[ ${1+.} ]]; do
[[ $1 == // ]] && fail "Unexpected third use of '//'."
parse_target_expr "$1"
LAST_TER_TARGET_ID=${TARGET_ID}
done
;;
-?*)
fail "Invalid or unexpected option: $1"
;;
//)
fail "Unexpected third use of '//'."
;;
+(/))
fail "Invalid argument: $1"
;;
*)
parse_target_expr "$1"
LAST_TER_TARGET_ID=${TARGET_ID}
;;
esac
shift
fi
done
}
function parse_secondary_args {
SEC_GLOBAL_ID=$(( ++TARGET_ID ))
while [[ $# -gt 0 ]]; do
if [[ $1 == // ]]; then
parse_tertiary_args "${@:2}"
break
elif parse_filter_opts "${SEC_GLOBAL_ID}" "${@:1:2}"; then
shift "$__I0"
else
case $1 in
--)
while shift; [[ ${1+.} ]]; do
[[ $1 == // ]] && continue 2