Back (Current repo: scraps)

random scraps and notes that are useful to me
To clone this repository:
git clone https://git.viktor1993.net/scraps.git
Log | Download | Files | Refs

get_subprocesses.sh (1132B)


#!/bin/bash
function get_subprocesses() {

    if [[ -z "$1" ]]; then
        echo "Usage: $0 <PID>"
        return 1
    fi

    function getpids() {
        echo -n $1 " "
        for sub in $(ps -o pid --no-headers --ppid "$1"); do
            echo -n $sub $(getpids $sub) " "
        done;
    }
    ps f $(getpids "$1")
}


    # Explanation for those who wandered in here
    # $(ps -o pid --no-headers --ppid $1) -> get all child process id's of the process id given by $1
    # recursively call getpids() on each child until we run out of descendant process id's
    # finally, call ps f on the whole thing, to print a process family

    # This can be useful when a script might spawn many subprocesses, such as other scripts in parallel,
    # sql connections, etc. it can be a way to check the status of a script i.e. how far down towards the
    # script execution has reached
    # It can also be useful to kill processes without leaving orphaned sub-processes, e.g. killing a script
    # as well as any mysql connections it spawned -- in general, killing a bash script will not kill any
    # spawned mysql processes