Getting Process-id of a Child Process
Implementing parallel processing is possible in bash
. You can put a job in the background with the &
on the command line and in your script.
You can obtain the id of the child process, by referring to $!
and the parent process id using $$
.
I use this simple trick to play sounds for log running jobs providing audible feedback.
The basic prototype looks like the following, a script that will run for ever, emitting an alive beep, we call this alive.sh
.
#!/bin/bash
while [ 1 ]; do
/usr/bin/afplay $HOME/Sounds/alive.wav;
sleep 2;
done
exit 0
Our parent script doing stuff, which the child process beeps away.
#!/bin/bash
alive-beep.sh &
sleep 6;
kill $!
/usr/bin/afplay $HOME/Sounds/success.wav
exit 0
Do note that the scope of the $!
has to be watched closely, since forking more that one child results on more than one process-id, yes it sounds logical, but can be confusing and not quite obvious, when you are experimenting.