logoalt Hacker News

chasiltoday at 5:49 PM2 repliesview on HN

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.

Replies

acuozzotoday at 9:14 PM

Is this guaranteed to be atomic on all filesystems?

show 1 reply
jofla_nettoday at 6:54 PM

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.

show 3 replies