Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

report grandchild process id to parent bash

Tags:

bash

I would like to report the grand child process id to the parent either by storing it in a variable and exporting it or some other means. How is it possible? Below a small example.

example .

parent.sh
    ./child.sh &
     wait
     sleep 10
     echo $grandchild_pid

child.sh
    ./grandchild.sh &
     export grandchild_pid=$!
like image 347
infoclogged Avatar asked Jan 28 '26 04:01

infoclogged


1 Answers

One approach is to use a FIFO:

tempdir=$(mktemp -t -d fifodir.XXXXXX) # tempdir for our named pipe
trap 'rm -rf "$tempdir"' EXIT          # ...arrange for it to be deleted on exit

mkfifo "$tempdir/child"                # create our temporary FIFO
./child.sh 3>"$tempdir/child" &        # start our background process, FD 3 to the FIFO

sleep 10                               # do whatever
read grandchild_pid <"$tempdir/child"  # read from the FIFO

echo "Our grandchild's PID is $grandchild_pid"

...and, in child.sh:

./grandchild.sh 3>&- &  # start the grandchild in the background
(echo "$!" >&3 &)       # write PID to FD3 in background so we don't block on the parent
exec 3>&-               # close the FD from the child, so only the backgrounded echo has it
like image 138
Charles Duffy Avatar answered Jan 29 '26 20:01

Charles Duffy