forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpid_file.rb
45 lines (37 loc) · 989 Bytes
/
pid_file.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'miq-process'
class PidFile
def initialize(fname)
@fname = fname
end
def self.create(fname, remove_on_exit = true)
new(fname).create(remove_on_exit)
end
def self.remove(fname)
new(fname).remove
end
def pid
return nil unless File.file?(@fname)
data = IO.read(@fname).strip
return nil if data.empty? || !/\d+/.match(data)
data.to_i
end
def remove
FileUtils.rm(@fname) if pid == Process.pid
end
def create(remove_on_exit = true)
FileUtils.mkdir_p(File.dirname(@fname))
File.open(@fname, "w") { |f| f.write(Process.pid) }
at_exit { PidFile.remove(@fname) } if remove_on_exit
end
def running?(regexp = nil)
pid = self.pid
return false if pid.nil?
command_line = MiqProcess.command_line(pid)
return false if command_line.blank?
unless regexp.nil?
regexp = Regexp.new(regexp) if regexp.kind_of?(String)
return false if regexp.match(command_line).nil?
end
true
end
end