Last active
November 28, 2018 09:45
-
-
Save didenko/a92beec14ce2ca1c98f3 to your computer and use it in GitHub Desktop.
Locking daemon in bash example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# As detailed at http://blog.didenko.com/2010/08/locking-for-daemons-in-bash.html | |
pidf=/tmp/$(basename ${0}).pid | |
exec 221>${pidf} | |
flock --exclusive --nonblock 221 || | |
{ | |
echo "Another instance is apparently running." | |
exit 1 | |
} | |
echo ${$}>&221 | |
echo "Running as process ID "${$} | |
echo "The process ID is stored in the file "${pidf} | |
echo "About to get buzy for about 20 seconds" | |
for (( i=0 ; i < 10; i=i+1 )) | |
do | |
echo -n "z-" | |
sleep 2 | |
done | |
echo "Oh!" | |
echo "Done all the hard work. Exiting." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As I understand it, line 6:
exec 221>${pidf}
clobbers the pid file, so if you run a second instance, the pid file is erased.I tried
exec 221>>${pidf}
instead, butecho ${$}>&221
did not erase the file as I thought it might, so I end up with a list of past pid's. Suggestions?