3 ms·
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 go
by chasil 9mo 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 9mo agothis 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.
- formerly_proven 9mo agoYes, but that is not a weakness in the locking.
- chasil 9mo agoThe 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.
- cryptonector 9mo agoThe problem with lock files and lock directories is that if the lock holder dies without cleaning up you now need to do something to clean up.
- mscdex 9mo agoOn Linux, this is why I always turn to using abstract sockets when I only need local locking. Only one process can bind and the kernel cleans up automatically on process exit. You could do the same thing with TCP/UDP, but abstract sockets give you more flexibility in naming with 108 characters vs. being forced to use a 16-bit integer. Also it means you aren't using up a port that could otherwise be used for actual network communication. Abstract sockets also make for a nice process existence monitoring mechanism since any processes connected to the bound socket are guaranteed to be immediately notified when the process dies.
- acuozzo 9mo agoIs this guaranteed to be atomic on all filesystems?
- chasil 9mo agoFor POSIX, yes. https://rcrowley.org/2010/01/06/things-unix-can-do-atomically.html https://rcrowley.org/2010/01/06/things-unix-can-do-atomicall... Windows has a deep well of POSIX in the kernel (plus hard file locks), and it appears to hold there. https://en.wikipedia.org/wiki/Microsoft_POSIX_subsystem https://en.wikipedia.org/wiki/Microsoft_POSIX_subsystem
- elteto 9mo agoIt’s even atomic on NFS. In fact, it’s probably the only reliable locking mechanism on NFS.