Search code examples
linuxbashpid

PID of all child processes of a command


In a bash script, I want to launch a process in the foreground, then print a list of all the process names and PIDs that were started as children of that process. For example, suppose I have the following scripts, but I can only modify the first one:

A.sh:

#!/bin/bash
B.sh

B.sh:

#!/bin/bash
C.sh

C.sh:

#!/bin/bash
echo "Running C.sh"

Without modifying B.sh, C.sh or the echo command, and without starting any of the child processes in the background, I would like A.sh to print the following:

B.sh 1208
C.sh 1210
echo 1211

Can A.sh fork a process that records this information while the child processes are running in the foreground of A.sh?


Solution

  • Update: In the comments below my answer it turned out that:

    I need something that observes the creation of all child processes during a span of time. Given that, filtering to isolate my subtree will not be difficult.

    ... was the intention behind the question and it was for debugging purposes.

    In that case I'd recommend to use strace like this:

    strace -f command
    

    -f will track child processes - recursively. Since forking and exec-ing requires system calls, strace will list any child creation plus the pids.


    Original answer:

    You can use pgrep for that:

    run_process &
    pid=${!}
    pgrep --parent "${pid}"
    wait # wait for run_process to finish
    

    Btw, you may want to use the pstree command, it is nice to use:

    run_process &
    pid=${!}
    pstree -p "${pid}"
    wait # wait for run_process to finish
    

    Anyhow, you'll need to install pstree.