Module: ProcessMgt

Defined in:
lib/process_mgt.rb

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.children(parent_pid) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/process_mgt.rb', line 12

def self.children(parent_pid)
  pids=[]
  out=`ps -ef --cols=400`
  out.split(/\n/).grep(/#{parent_pid}/).each { |p|
    tmp = p.split(' ')
    pids << tmp[1] if p.split(' ')[2].strip == "#{parent_pid.strip}"
  }
  pids.join(' ')
end

.kill(params = {}) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/process_mgt.rb', line 63

def self.kill(params={})
  params[:signal] ||= 'TERM'
  params[:with_children] ||= 'false'
  params[:force] ||= 'false'
  if params.has_key?(:pid_list)
    `kill -#{params[:signal]} #{params[:pid_list]} >/dev/null 2>&1`
  else
    if params[:with_children].to_bool
      pids = pids_with_children(params)
    else
      if params.has_key?(:with_children)
        pids = pids_with_children(params)
      else
        pids = pids(params)
      end
    end
    if pids.strip != ''
      `kill -#{params[:signal]} #{pids} >/dev/null 2>&1`
      `kill -9 #{pids} >/dev/null 2>&1` if params[:force].to_bool
    end
  end
end

.parent_pid(child_pid) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/process_mgt.rb', line 22

def self.parent_pid(child_pid)
  out=`ps -ef --cols=400`
  pid = ''
  retry_ct = 0
  out.each_line { |line|
    line_split = line.split(' ')
    return line_split[2].strip if line_split[1].strip == child_pid.strip
  }
  pid
end

.pids(params = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/process_mgt.rb', line 33

def self.pids(params={})
  raise ArgumentError ":search not provided" unless params.has_key?(:search)
  params[:exclude] ||= ''
  out=`ps -ef --cols=400`
  pids = ''
  retry_ct = 0
  out.grep(/#{params[:search]}/m).each { |i|
    if params[:exclude] != ''
      next if i.grep(/#{params[:exclude]}/).nitems > 0
    end
    item = " #{i.split(' ')[1].gsub(/\n/, '')}"
    if params.has_key?(:parent)
      parent = " #{i.split(' ')[2].gsub(/\n/, '')}"
      pids += item if parent.strip == params[:parent].strip
    else
      pids += item
    end
  }
  pids
end

.pids_with_children(params = {}) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/process_mgt.rb', line 54

def self.pids_with_children(params={})
  pids = ProcessMgt.pids(params)
  all_pids = pids
  pids.each { |pid|
    all_pids += " #{ProcessMgt.children(pid)}"
  }
  all_pids
end