Class: Clicker::LaunchLock

Inherits:
Object
  • Object
show all
Defined in:
lib/clicker/launch_lock.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(program_name) ⇒ LaunchLock

Returns a new instance of LaunchLock.



8
9
10
11
12
# File 'lib/clicker/launch_lock.rb', line 8

def initialize(program_name)
  @config_dir = "#{ENV['HOME']}/.config/#{program_name}"
  @lock_file_path = "#{@config_dir}/#{program_name}.lock"
  FileUtils.mkdir_p(@config_dir)
end

Instance Attribute Details

#lock_file_pathObject (readonly)

Returns the value of attribute lock_file_path.



6
7
8
# File 'lib/clicker/launch_lock.rb', line 6

def lock_file_path
  @lock_file_path
end

Instance Method Details

#locked?Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/clicker/launch_lock.rb', line 29

def locked?
  File.open(@lock_file_path, 'r') do |f|
    rv =  f.flock(File::LOCK_EX | File::LOCK_NB)
    case rv
    when 0
	return false
    when false
	return true
    end
  end
rescue Errno::ENOENT
  return false
end

#ownerObject



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/clicker/launch_lock.rb', line 43

def owner
  File.open(@lock_file_path) do |f|
    success = f.flock(File::LOCK_EX | File::LOCK_NB)
    if success
      return nil # owner is not alive...
    else
      pid = f.gets.to_i
      return pid
    end
  end
rescue Errno::ENOENT
  return nil
end

#try_lockObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/clicker/launch_lock.rb', line 14

def try_lock
  File.open(@lock_file_path, 'r+') do |f|
    success = f.flock(File::LOCK_EX | File::LOCK_NB)
    if success
      f.puts Process.pid
      f.flush
	f.truncate(f.pos)
      yield
      return true
    else
      return false
    end
  end
end