Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

bash - Check number of running scripts using ps

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

At the moment ps runs a process grep show_volume.sh is also running, so you always count the grep!

Simple solution, grep s[h]ow_volume.sh. The grep (not shell) will collapse the [h] to h and search for what you want, but your grep won't match itself because it will have [] in the parameter.

pgrep is also useful for this task and is smart enough to always exclude itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...