Search code examples
bashshellforkpidchild-process

Get pids of all child/grandchild processes created from parent process


Say I have a process like so:

#!/usr/bin/env bash

node foo.js &
pid=$!

is there a way to listen to child processes that get created from pid? I want to create a list of pids that get created/forked from pid. That is, any child or grandchild of pid, I want to know about it, somehow.

Right, now I am logging the pid of each child process to stdout and capturing it that way, but there are couple problems with that. It is not that generic a solution especially if I don't control all the child procs, or if their stdout gets redirected.


Solution

  • I think the best solution to this problem is to use this methodology:

    #!/usr/bin/env bash
    
    node foo.js &
    pid=$!
    
    sleep 5;
    
    pgrep -P $pid | xargs kill -INT
    

    that will send the SIGINT signal to all the child procs of $pid.

    https://linux.die.net/man/1/pgrep