Bash/Get children

From Attie's Wiki
Jump to: navigation, search

This recursive function will print out the process tree, starting with the process ID given.

function showChildren {
  PID=$1; shift
  local INDENT=$1; shift
  if [ -e /proc/${PID} ] && readlink /proc/${PID}/exe >/dev/null 2>&1 ; then
    echo "${INDENT}${PID} - $(cat /proc/${PID}/cmdline | tr '\000' ' ')"
  else
    echo "${INDENT}${PID} - $(ps -ef | awk "\$2==$PID {printf \$8}")"
  fi
  KIDS=0
  for pid in $(ps -ef | awk "\$3==$PID {printf \$2 \" \"}"); do
    showChildren ${pid} ":   ${INDENT}"
    KIDS=1
  done
  [ ${KIDS} -ne 0 ] && echo -e "${INDENT}"
}

Execute it like this:

# show all processes:
showChildren 1
 
# show all of this shell's children:
showChildren $$
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox