3

I am writing a Lua script in Linux that can only have one instance running. To accomplish this in Bash I would use mkdir to create a lock file, and then return from the script immediately if the file exists; if no previous instance is running, allow the script to continue and remove the lock file once it completes.

Is there a way to atomically "check if a file exists or create it if it does not exist" in Lua? I cannot find any such functionality in the Lua documentation, but I'm new to the language. io.open("filename","w") does not look like it fulfills these requirements. If there is no native analog to mkdir, is there a better way to accomplish this type of script locking in Lua? Thanks!

Joe Stech
  • 218
  • 5
  • 12
  • This seems like a duplicate of http://stackoverflow.com/questions/4990990/lua-check-if-a-file-exists... Please try one of the solutions for checking if a file exists in LUA posted there – renab Jan 07 '13 at 21:17
  • @renab I saw those; none of the answers atomically check and/or create a file, which is what I'm specifically asking about. – Joe Stech Jan 07 '13 at 21:41
  • This sounds more like single process execution, which is not the same thing as thread-safety. – Nicol Bolas Jan 07 '13 at 22:13
  • @NicolBolas That's true. I've edited the question for clarity. – Joe Stech Jan 07 '13 at 22:45

1 Answers1

1

Just transcribing the answer you ended up with:

if not os.execute("mkdir lockfile >/dev/null 2>&1") then 
  return 
end 

--do protected stuff 

os.execute("rmdir lockfile")
Lyn Headley
  • 11,368
  • 3
  • 33
  • 35
  • Thanks, but this does not appear to be atomic; if the file check operation (`io.open ("filename", "r")`) is executed by one script instance, and then executed again by another script instance before the file creation operation happens in the first instance (`io.open("filename", "w")`) then both instances will think they're OK to execute simultaneously. – Joe Stech Jan 07 '13 at 22:55
  • 1
    you'll probably want to invoke mkdir using os.execute then – Lyn Headley Jan 07 '13 at 23:22
  • Yes, this is what I ended up with this afternoon: `if not os.execute("mkdir lockfile >/dev/null 2>&1") then; return; end; --do protected stuff; os.execute("rmdir lockfile")`. It looks like Lua does not have a native way to do this without a system call since it's based on ANSI C. If you want to edit your post for posterity I'll accept it. I'd upvote your comment, but because this is my first question I don't have the necessary reputation. – Joe Stech Jan 08 '13 at 06:14