Joe Stech
Joe Stech

Reputation: 218

Preventing multiple executions of a Lua script

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!

Upvotes: 3

Views: 1579

Answers (1)

Lyn Headley
Lyn Headley

Reputation: 11588

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")

Upvotes: 1

Related Questions