whimsical-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From s...@apache.org
Subject [whimsy] branch master updated: Initial implementation of file locking code
Date Tue, 03 Jul 2018 10:37:21 GMT
This is an automated email from the ASF dual-hosted git repository.

sebb pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/whimsy.git


The following commit(s) were added to refs/heads/master by this push:
     new 16bde91  Initial implementation of file locking code
16bde91 is described below

commit 16bde910775a4f50b1f05914d62edb5447335c36
Author: Sebb <sebb@apache.org>
AuthorDate: Tue Jul 3 11:37:20 2018 +0100

    Initial implementation of file locking code
---
 lib/whimsy/lockfile.rb | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 73 insertions(+)

diff --git a/lib/whimsy/lockfile.rb b/lib/whimsy/lockfile.rb
new file mode 100644
index 0000000..b8497fe
--- /dev/null
+++ b/lib/whimsy/lockfile.rb
@@ -0,0 +1,73 @@
+#!/usr/bin/env ruby
+
+#
+# File locking support
+#
+
+module LockFile
+
+  # create a new file and return an error if it already exists
+  def self.create_ex(filename, verbose=false)
+    err = nil
+    begin
+      File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file|
+        yield file
+      end
+    rescue => e
+      err = e
+    end
+    return verbose ?  [err==nil, err] :  err==nil
+  end
+
+  # lock a file and ensure it gets unlocked
+  def self.flock(file, mode)
+    ok = file.flock(mode)
+    if ok
+      begin
+        yield file
+      ensure
+        file.flock(File::LOCK_UN)
+      end
+    end
+    ok
+  end
+
+end
+
+
+
+
+if __FILE__ == $0
+  test = ARGV.shift || 'lockw'
+  name = ARGV.shift || '/tmp/lockfile1'
+  text = "#{Time.now}\n"
+  puts "#{Time.now} #{test} using #{name}"
+  case test
+  when 'create'
+    ret = LockFile.create_ex(name) {|f| f << text}
+  when 'createShow'
+    ret = LockFile.create_ex(name, true) {|f| f << text}
+  when 'locka'
+    open(name,'a') do |f|
+      puts "#{Time.now} Wait lock"
+      ret = LockFile.flock(f,File::LOCK_EX) do |g|
+        g << text
+        puts "#{Time.now} Sleep"
+        sleep(5)
+      end
+    end
+  when 'lockw'
+    open(name,'w') do |f|
+      puts "#{Time.now} Wait lock"
+      ret = LockFile.flock(f,File::LOCK_EX) do |g|
+        g << text
+        puts "#{Time.now} Sleep"
+        sleep(5)
+      end
+    end
+  else
+    raise "Unexpected test: #{test}"
+  end
+  puts ret.inspect
+  puts File.read(name)
+end


Mime
View raw message