Posts

Showing posts from March 24, 2019

How does this script ensure that only one instance of itself is running?

Image
4 1 On 19 Aug 2013, Randal L. Schwartz posted this shell script, which was intended to ensure, on Linux, "that only one instance of [the] script is running, without race conditions or having to clean up lock files": #!/bin/sh # randal_l_schwartz_001.sh ( if ! flock -n -x 0 then echo "$$ cannot get flock" exit 0 fi echo "$$ start" sleep 10 # for testing. put the real task here echo "$$ end" ) < $0 It seems to work as advertised: $ ./randal_l_schwartz_001.sh & ./randal_l_schwartz_001.sh [1] 11863 11863 start 11864 cannot get flock $ 11863 end [1]+ Done ./randal_l_schwartz_001.sh $ Here is what I do understand: The script redirects ( < ) a copy of its own contents (i.e. from $0 ) to t...