From: Daniel Berger Date: 2008-05-29T03:33:04+09:00 Subject: Re: Ensuring only one instance of a script is running On May 25, 7:46 am, "Sean O'Halpin" wrote: > On Wed, May 21, 2008 at 5:25 AM, DanielBerger wrote: > > Hi all, > > > I'm probably late to the game on this, but I stumbled across an > > interesting use for DATA. You can use it to ensure only one instance > > of a given script is running by using flock: > > > class Foo > >   def self.mainloop > >      while true > >         puts "Looping..." > >         sleep 3 > >      end > >   end > > end > > > DATA.flock(File::LOCK_EX) > > > if $0 == __FILE__ > >   Foo.mainloop > > end > > > __END_ > > > The first run will work, but trying to start the program up again will > > fail instantly because of the lock on DATA. I should probably do some > > cleanup there, too, but I thought I'd toss this out there and see if > > this is of interest to anyone. > > > Or was I was recovering from a hangover in college when they mentioned > > this trick in class? Anyway, there you go. > > > Regards, > > > Dan > > Nice one! However, I don't get a failure (on Linux) - instead the > second instance blocks waiting for the first instance to terminate at > which point it executes. Also, needing to specify __END__ is a little > awkward IMHO. > > I wonder, does the following work on Windows? > > if $0 == __FILE__ >   if File.open($0).flock(File::LOCK_EX|File::LOCK_NB) >     Foo.mainloop >   end > end > > Wrapped up in a method: > > $ cat single_instance.rb > def single_instance(&block) >   if File.open($0).flock(File::LOCK_EX|File::LOCK_NB) >     block.call >   else >     warn "Script #{ $0 } is already running" >   end > end > > $ cat self_locking.rb > require 'single_instance' > if __FILE__ == $0 >   single_instance do >     Foo.mainloop >   end > end Yep, that's definitely cleaner, thanks. > I think I'll use this :) Excellent. Good to know someone found it useful. :) Regards, Dan