pidtree: Faster by running ps once.

This commit is contained in:
Ole Tange 2020-06-03 23:45:08 +02:00
parent c69ff84ae6
commit e2274764c4

92
pidtree/pidtree Executable file
View file

@ -0,0 +1,92 @@
#!/bin/bash
: <<=cut
=pod
=head1 NAME
pidtree - List children of process ID
=head1 SYNOPSIS
B<pidtree> I<pid> [I<pids>]
=head1 DESCRIPTION
B<pidtree> lists the process IDs of the (grand*)children of the I<pid>.
=head1 EXAMPLES
Show the tree for all processes on the system:
pidtree 1
Show the tree for this process:
pidtree $$
Kill process and all (grand*)children:
pidtree 12345 | xargs kill
=head1 AUTHOR
Copyright (C) 2020 Ole Tange,
http://ole.tange.dk and Free Software Foundation, Inc.
=head1 LICENSE
Copyright (C) 2012 Free Software Foundation, Inc.
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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
=head1 DEPENDENCIES
B<pidtree> uses B<ps>.
=head1 SEE ALSO
B<ps>, B<pstree>.
=cut
_pidtree() {
declare -A children
# Make table pid => child pids
# This way we only run 'ps' once
while read pid parent ; do
children[$parent]+=" $pid"
done < <(ps -e -o pid,ppid)
__pidtree() {
# Indent pid with spaces ($1)
echo "$1$2"
for child in ${children["$2"]} ; do
__pidtree " $1" "$child"
done
}
for pid in "$@" ; do
__pidtree '' "$pid"
done
}
_pidtree "$@"