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.
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.

Yes, but that is not a weakness in the locking.
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"

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.

So good in depth post. THANK YOU.