From: Patrick Spence Date: 2006-11-07T23:29:53+09:00 Subject: Re: The way to restrict a ruby program to just once occurrence on a windows box? Glenn Smith wrote: > I'm rewriting a vb app to ruby (in about a quarter of the code!). If I ran > the same ruby program twice in parallel, the second instance should exit. > > In VB6 I could do this: > > If App.PrevInstance Then Exit Sub > > > Any ideas how this is done in ruby? > > > Ta muchly > > ------=_Part_1672_14945421.1162889756916-- Though not very "elegant", here's one approach... When the script starts up, run the following line of code, within the BEGIN block of a BEGIN...RESCUE...ENSURE construct. def main() begin lockFile = File.new("semaphore.lck", File::CREAT|File::EXCL) rescue Errno::EEXIST puts("Script is already running") rescue Exception => ex puts(ex.message()) ensure unless lockFile.nil? lockFile.close() File.delete("semaphore.lck") end end end main() The first instance of the script will create and open the "semaphore.lck" file. Running another instance of the script will cause the preceeding line of code to throw a Errno::EEXIST error, which is easy enough to trap. In that case, display a message to the user. The ENSURE block will need to close and delete the semaphore file so that, in the case of an abend, the file is not left hanging out there. Otherwise, this will prevent the script from running again until someone manually deletes the file.