Skip to content

Instantly share code, notes, and snippets.

Last active November 28, 2018 09:45
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Locking daemon in bash example
# As detailed at
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 ))
echo -n "z-"
sleep 2
echo "Oh!"
echo "Done all the hard work. Exiting."
Copy link

Maybe I didn't fully understand it, but how do we avoid file descriptor collision with other scripts?

EDIT: Nevermind, just tried it :) The actual pid file still matters.

Copy link

drevicko commented Aug 8, 2016

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, but echo ${$}>&221 did not erase the file as I thought it might, so I end up with a list of past pid's. Suggestions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment