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!

4
  • This seems like a duplicate of 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 Commented Jan 7, 2013 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. Commented Jan 7, 2013 at 21:41
  • This sounds more like single process execution, which is not the same thing as thread-safety. Commented Jan 7, 2013 at 22:13
  • @NicolBolas That's true. I've edited the question for clarity. Commented Jan 7, 2013 at 22:45

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

3 Comments

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.
you'll probably want to invoke mkdir using os.execute then
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.