Question

I need to develop a shell script that would not be started if another instance of them self is running.

If I build a test.sh that monitors itself I need to know if it is already running and then abort, otherwise (if it not previously running) I can run

#!/bin/bash

loop() {
    while [ 1 ]; do
        echo "run";
        #-- (... omissis ...)
        sleep 30
      done
 }

 daemon="`/bin/basename $0`"

 pidlist=`/usr/bin/pgrep $daemon | grep -v $$`
 echo "1:[ $pidlist ]"

 pidlist=$(/usr/bin/pgrep $daemon | grep -v $$)
 echo "2:[ $pidlist ]"

 echo "3:[ `/usr/bin/pgrep $daemon | grep -v $$` ]"

 echo "4:["
 /usr/bin/pgrep $daemon | grep -v $$
 echo "]"

 if [ -z "$pidlist" ]; then
      loop &
 else
      echo "Process $daemon is already running with pid [ $pidlist ]"
 fi

 exit 0;

When I run the above script for the first time (no previous instances running) I get this output:

1:[ 20341 ]
2:[ 20344 ]
3:[ 20347 ]
4:[
]

I cannot understand why only 4th attempt does not return anything (as expected). What's wrong in my script? Do I have to redirect output of 4th command on a temporary file and then query that file in order to decide if I can run (or not) the loop function?

Thanks anyone would help me!

Was it helpful?

Solution

Sub-shells...the first three are run in sub-shells and hence $$ has changed to the PID of the sub-shell.

Try using:

PID=$$
pidlist=`/usr/bin/pgrep $daemon | grep -v $PID`
echo "1:[ $pidlist ]"

Etc. Since the value of $PID is established before the sub-shell is run, it should be the same for all of the commands.

Is this process going to be popular enough that other people want to run the same daemon on the machine? Maybe you never have multiple users on the machine, but remember that someone else might be wanting to run the command too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top