I'd like to define a class Lock < File which would act like this:
Lock.lock
# do stuff....
Lock.unlock
or even perhaps
Lock.lock {
# do stuff
}
or even
Lock.lock("myfile") {
# stuff
}
Designing my own iterators isn't a problem, but this lock class seems to be. I get many funny errors:
* Lock.new insisted on 1 parameter - but initialize method had NO parameters
* $0 was not being recognized in parameter default value expressions
* print "foo" would generate: in 'write': not open for writing (IOError)
* $stdio evaluates to nil
* flock appears to fail on non-existant files (?) and says in the documentation "advisory" lock....
I might just throw this back into the Korn shell (called from ruby of course)
set -o noclobber
cat /dev/null 2> /dev/null > $1 && set +o noclobber
Here's what I have tried (with comments)
#!/opt/ruby/bin/ruby
class Lock < File
attr_accessor :locked, :lockdir, :lockfile
def initialize
@locked = false
@lockdir = "/var/spool/locks"
@lockfile = @lockdir + "/" + File.basename($0) + ".lock"
end
def Lock.new
# raise "Lockdir not set!" if @lockdir == nil;
raise "\$0 not set?!" if $0 == nil;
super ("/var/spool/locks" + "/" + File.basename($0) + ".lock", "w")
end
def unlock
raise "Lockfile not set!" if @lockfile == nil;
raise "Could not unlock!" if (File.unlink(@lockfile) == 1);
@locked = false
end
def lock (lockf = lockfile)
raise "Lockfile not set!" if @lockfile == nil;
# -- generates error:
# ./lock.rb:26:in `lock': Lockfile not set! (RuntimeError)
# from ./lock.rb:63
#
# Even after initializing!! (self.initialize)
@lockfile = lockf;
raise "Could not lock!" if ! @lockfile.flock(LOCK_EX|LOCK_NB)
@locked = true
end
def display_lock
# print "Current lock:\n\n"
# -- generates this error:
#
# ./lock.rb:29:in `write': not opened for writing (IOError)
# from ./lock.rb:29:in `print'
# from ./lock.rb:29:in `display_lock'
# from ./lock.rb:39
p @locked;
p @lockfile;
p @lockdir;
end
end
# mylock = Lock.new;
# -- generates this error:
#
# ./lock.rb:43:in `new': wrong # of arguments (0 for 1) (ArgumentError)
# from ./lock.rb:43
#
# Even though Lock.initialize has no parameters!
# Yes, I know File.new has one.... but not calling File.new but Lock.new right?
# If I redefine Lock.new this problem goes away.... but
# what problems does it create?
mylock = Lock.new;
mylock.display_lock
mylock.lock
mylock.display_lock
mylock.unlock
[....snip!....]
Also:
# ruby -v
ruby 1.4.3 (1999-12-08) [hppa1.1-hpux10.20]
# uname -a
HP-UX oursys B.10.20 A 9000/861 2016701434 two-user license
#
Thanks for all the help!