4 comments

  • chasil 1 hour ago
    One sure way to get a lock is to make a directory.

      #!/bin/sh
    
      if mkdir /your/lockdir
      then trap "rmdir /your/lockdir" EXIT INT ABRT TERM
           ...code goes here...
      else echo somebody else has the lock
      fi
    
    No matter how many processes attempt to make the directory, only one will succeed. That works for my scripting, but I have never used it in C.
    • jofla_net 46 minutes ago
      this is great thanks,

      was just wondering, could something else remove the dir in between the if and then, before trap?

      Just wondering about the atomicity.

      • chasil 17 minutes ago
        The permissions on the parent and lock directory could restrict the access to a specific user and group, but yes, other processes could interfere with this locking if directed to do so.

        One condition where this interference is helpful is a crash, where a @reboot entry in the crontab could:

          [ -d /your/lockdir ] && rmdir /your/lockdir
        
        You would also not want to place the lock directory in /tmp or otherwise where other users could manipulate (or see) it. In Red Hat, there is a /var/run/lock directory that might be appropriate.

        My biggest use case for directory locking in scripts is handling inotify events.

      • formerly_proven 31 minutes ago
        Yes, but that is not a weakness in the locking.
  • Bratmon 1 hour ago
    Usually when I read these writeups, I walk away thinking "Wow, $foo was a more complicated problem than I thought".

    With this one, it was "Wow, $foo was a simpler problem than I thought and Unix (and thus Linux and OSX) just totally screwed it up for no reason"

  • pseudohadamard 3 days ago
    Another good read is the SQLite locking module, https://www.sqlite.org/src/artifact/0240c5b547b4cf585c8cac35..., since these guys have to deal with the insanity of locking across different systems in real life.

    You know things are bad when the least awful implementation of OS-level locking is the one from Microsoft.

  • Number-Six 4 days ago
    So good in depth post. THANK YOU.