I have a problem with the following kind of script:
#!/bin/sh long_running_script.sh & while [ `pidof long_running_script.sh` ] do echo "." sleep 1 done
The sript will start a new script to background, and it should print dots until the backgroud script will exit. It works when CPU load is not high.
But, when there is high CPU load, it won’t work: long_running_script.sh will start, but the ‘parent’ script will exit from while loop before the long_running_script.sh exits.
pidof is executed before the long_running_script.sh is really started (execved).
What is the best way to solve this problem?
1 seconds sleep before the while statement didn’t help. So I don’t want to use any magic delays, because it may be unreliable.
pidof won’t find scripts, since it only looks at the first part of the process name (
You could use
pidof -m, but that will find any
long_running_script.sh, not just the one started by this script.
A better way is to use the
$! variable, which holds the PID of the most recent background job.
#!/bin/bash long_running_script.sh & pid=$! while ps -p $pid >/dev/null do echo "." sleep 1 done