I'm writing a script (show_volume.sh) which may be called several times in short intervals. I need a way to determine whether there is more than just one running instance of this script. I figured I could use ps
, so I wrote this function in Bash:
is_only_process(){
PCOUNT=`ps -a | grep show_volume.sh | wc -l`
echo $PCOUNT
if (( PCOUNT==1 )); then
return 1
fi
return 0
}
So I added these 2 lines
is_only_process
sleep 4
and started this script once, but the output of echo $PCOUNT
does not make any sense to me. I always get the value 2, not 1, as expected. When I run this command
ps -a | grep show_volume.sh | wc -l
from another terminal while the script is running, I receive the value 1.
It's pretty much the same when I run this script several times in a row, e.g. 10 times using a for loop. The script itself determines values which are too high while I receive correct values when using another terminal.
Now, why does this script determine these odd values?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…