| >>> Clemens Hintze <c.hintze / gmx.net> 03/20/00 11:08PM >>>
| David Douthitt writes:
| 
| ...
| 
| Sorry for bothering you, but to prevent you from re-inventing the
| wheel again, there is a package 'filelock' in the contrib directory in
| 
|    ftp://ftp.netlab.co.jp/pub/lang/ruby/contrib/filelock.rb. 
| 
| Perhaps it is what you have searched?
| 
| But then, nobody has told me if you like to re-invent the wheel again
| ;-)

Only sometimes :-)

Yet, I don't think your script is what I had in mind.  I'm not looking
to "lock a file" - but to create a UNIX-style lockfile in
(typical example) /var/spool/locks/ - as it is under HP-UX 10.20 here.
This looks like your class LockFile but your code seems quite complex.
I'm not sure that all that is what I needed.  My class Lock turned out
to be much simpler I think.

That first line is a marvel!  "/bin/env ruby" ... hmmm!

Here's my code:

#!/opt/ruby/bin/ruby

class Lock
   attr_accessor :locked_up, :lockdir, :lockfile

   def initialize (lockf = nil)
      @locked_up = false
      @lockdir = "/var/spool/locks"
      if (lockf == nil)
         @lockfile = (@lockdir + "/" + File.basename($0) + ".lock")
      else
         @lockfile = (@lockdir + "/" + lockf + ".lock")
      end
   end

   def setlock (lockf = @lockfile)
      raise "Lockfile not set!" if lockf == nil;
      raise "Lock failed!" if
         ! system("set -o noclobber ; cat /dev/null 2> /dev/null > #{lockf}")

      at_exit { self.unlock }
      @locked_up = true
   end

   def locked?
      test(?e, @lockfile)
   end

   def Lock.locked? (lockf)
      test(?e, "/var/spool/locks/" + lockf)
   end

   def locked
      self.setlock
      yield
      self.unlock
   end

   def unlock
      test(?e, @lockfile) if
         raise "Unlock failed!" if
            ! system("rm -f #{@lockfile}");

      @locked_up = false
   end
end

>>> I use it this way:

mylock = Lock.new

mylock.locked {
#  ....do stuff....
   }

>>> or this way:

return if Lock.locked?("Oracle.lock")

>>>

What do you think?