Pidof -x $ 0 returns 2 instead of the expected 1, is there one alternative?

In a bash script, I'm trying to use the following line to determine if another process is executing the current script:

/sbin/pidof -x $0 |wc -w

But the answer is always 2, not the expected value of 1.

I tried the following calls:
/sbin/pidof -x $0

returns 1 pid
/sbin/pidof -x $0 |wc -w

returns 2
/sbin/pidof -x $0 |head

returns 2 pids
/sbin/pidof -x $0 |head |wc -w

returns 2
/sbin/pidof -x $0 |head |tail

returns 2 pids
/sbin/pidof -x $0 |head |tail |wc -w

returns 2

Can anyone suggest an alternative (or fix) to achieve what I am trying to do and explain why outputting data to anything makes the output of pidof "a little funny"?


This is how the script is currently using pidof, which works great:
RUNNING=`/sbin/pidof -x $0`
RUNNING=`echo -n ${RUNNING} | wc -w`
[[ ${RUNNING} -gt 1 ]] && return

      

+3


source to share


1 answer


If you're only trying to prevent the script from running a second time, the following will do the trick:

pid=/tmp/$(basename $0).pid
[ -e $pid ] && exit 0;
trap 'rm -f $pid >/dev/null 2>&1;' 0
trap 'exit 2' 1 2 3 15
touch $pid

      



Just run your script with these lines. It basically checks the file and stops execution if the file is present. Note, if you kill (-9) a running script, you are responsible for cleaning up the generated pid file. Kill (-9) bypasses a shell trap that will otherwise clear the pid file.

+1


source







All Articles