I found this interesting page that suggests several options:
- Create a lock file
- Create a PID file.
flocksolo
But what about his option:
Check ps to see if the executed command is currently running.
(A ps-check.sh script could even be included at the start of every cron job you create.)
I'm assuming that the reason I haven't come across this kind of solution is that it's a bad idea.
Why is this a bad idea?
ps-check.sh could return 1 if the command is already running. The cron script could call ps-check.sh like this:
#!/bin/bash
#some script
#get current script name into variable
#then use ps-check.sh to see if current script is already running
#by supplying it with 2 things: script name and current PID
me=`basename "$0"`
if (( $(ps-check.sh $me $$) == 1)); then
exit 1;
fi
# do more stuff
ps-check.sh would check to see if the script was already running under another PID.
Is there any case where a script would be running but not visible in ps? If sleeping?
EDIT - Conclusion:
I've decided to go with flock. Checking ps could work but I would probably have to handle a lot of conditions to make sure. I assume flock already handles most of those.
ps-check.shwould assume some standards are followed and/or enforced and/or there is something unique you key from. If you are implementing this yourself and those around you follow your documented standards, then it could work just fine. People forget rules, especially friday afternoon at beer-30, or at 3am. What I am saying is, build some safety/sanity checks into your script so you don't nuke something critical. :-) – Aaron Jun 27 '17 at 00:45