Class: Soba::Services::PidManager
- Inherits:
-
Object
- Object
- Soba::Services::PidManager
- Defined in:
- lib/soba/services/pid_manager.rb
Instance Attribute Summary collapse
-
#pid_file ⇒ Object
readonly
Returns the value of attribute pid_file.
Instance Method Summary collapse
- #cleanup_if_stale ⇒ Object
- #delete ⇒ Object
-
#initialize(pid_file) ⇒ PidManager
constructor
A new instance of PidManager.
- #lock(timeout: 5) ⇒ Object
- #read ⇒ Object
- #running? ⇒ Boolean
- #write(pid = Process.pid) ⇒ Object
Constructor Details
#initialize(pid_file) ⇒ PidManager
Returns a new instance of PidManager.
11 12 13 |
# File 'lib/soba/services/pid_manager.rb', line 11 def initialize(pid_file) @pid_file = pid_file end |
Instance Attribute Details
#pid_file ⇒ Object (readonly)
Returns the value of attribute pid_file.
9 10 11 |
# File 'lib/soba/services/pid_manager.rb', line 9 def pid_file @pid_file end |
Instance Method Details
#cleanup_if_stale ⇒ Object
58 59 60 61 62 63 64 65 66 67 |
# File 'lib/soba/services/pid_manager.rb', line 58 def cleanup_if_stale return false unless File.exist?(pid_file) if running? false else delete true end end |
#delete ⇒ Object
38 39 40 41 42 43 44 45 |
# File 'lib/soba/services/pid_manager.rb', line 38 def delete return false unless File.exist?(pid_file) File.delete(pid_file) true rescue StandardError false end |
#lock(timeout: 5) ⇒ Object
69 70 71 72 73 74 75 76 77 |
# File 'lib/soba/services/pid_manager.rb', line 69 def lock(timeout: 5) ensure_directory_exists Timeout.timeout(timeout) do File.open(pid_file, File::CREAT | File::WRONLY) do |f| f.flock(File::LOCK_EX) yield if block_given? end end end |
#read ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/soba/services/pid_manager.rb', line 24 def read return nil unless File.exist?(pid_file) content = File.read(pid_file).strip return nil if content.empty? pid = content.to_i return nil if pid <= 0 pid rescue StandardError nil end |
#running? ⇒ Boolean
47 48 49 50 51 52 53 54 55 56 |
# File 'lib/soba/services/pid_manager.rb', line 47 def running? pid = read return false unless pid # Check if process exists Process.kill(0, pid) true rescue Errno::ESRCH, Errno::EPERM false end |
#write(pid = Process.pid) ⇒ Object
15 16 17 18 19 20 21 22 |
# File 'lib/soba/services/pid_manager.rb', line 15 def write(pid = Process.pid) ensure_directory_exists File.open(pid_file, 'w') do |f| f.flock(File::LOCK_EX) f.write(pid.to_s) f.flush end end |