Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>They're not everone's favourite, but I've always been a fan of symbolic links to make lockfiles, since they're atomic. For example:</p> <pre><code>lockfile=/var/run/`basename $0`.lock if ! ln -s "pid=$$ when=`date '+%s'` status=$something" "$lockfile"; then echo "Can't set lock." &gt;&amp;2 exit 1 fi </code></pre> <p>By encoding useful information directly into the link target, you eliminate the race condition introduced by writing to files.</p> <p>That said, the link that Dennis posted provides much more useful information that you should probably try to understand before writing much more of your script. My example above is sort of related to <a href="http://mywiki.wooledge.org/BashFAQ/045" rel="nofollow">BashFAQ/045</a> which suggests doing a similar thing with <code>mkdir</code>.</p> <p>If I understand your question correctly, then what you want to do might be achieved (slightly unreliably) by using two lock files. If setting the first lock fails, we try the second lock. If setting the second lock fails, we exit. The error exists if the first lock is delete after we check it but before check the second existant lock. If this level of error is acceptable to you, that's great.</p> <p>This is untested; but it looks reasonable to me.</p> <pre><code>#!/usr/local/bin/bash lockbase="/tmp/test.lock" setlock() { if ln -s "pid=$$" "$lockbase".$1 2&gt;/dev/null; then trap "rm \"$lockbase\".$1" 0 1 2 5 15 else return 1 fi } if setlock 1 || setlock 2; then echo "I'm in!" do_something_amazing else echo "No lock - aborting." fi </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload