Child Processes

The following code snipplet defines two functions:

function childrenOf() {
  PARENT_PID="${1}"

  CHILDREN_PIDS=""
  TEST_PIDS="$(cd /proc; ls -d * | perl -ne 'print if m/^\d+$/')"
  for CHILD_PID in ${TEST_PIDS}
  do
    if test -f /proc/${CHILD_PID}/status
    then
      CHILD_PPID="$(cat /proc/${CHILD_PID}/status | grep PPid | perl -pe 's/^PPid:\s+//g')"
      if test ${CHILD_PPID} -eq ${PARENT_PID}
      then
        CHILDREN_PIDS="${CHILDREN_PIDS} ${CHILD_PID}"
      fi
    fi
  done

  echo "${CHILDREN_PIDS/# /}"
}

function allChildrenOf() {
  PARENT_PID="${1}"

  ALL_PIDS="$(childrenOf ${PARENT_PID})"

  CHECK_PIDS="${ALL_PIDS}"
  NEW_PIDS=""
  while test "${CHECK_PIDS}x" != "x"
  do
    for CHILD_PID in "${CHECK_PIDS}"
    do
      NEW_PIDS="${NEW_PIDS} $(childrenOf ${CHILD_PID})"
    done
    NEW_PIDS="${NEW_PIDS/# /}"

    CHECK_PIDS="${NEW_PIDS}"
    ALL_PIDS="${ALL_PIDS} ${NEW_PIDS}"
    NEW_PIDS=""
  done

  echo "${ALL_PIDS}"
}
Feedback is always welcome! If you'd like to get in touch with me concerning the contents of this article, please use Twitter.