Module: Procmon::System

Extended by:
System
Included in:
System
Defined in:
lib/procmon/system.rb

Overview

Copied from Bluepill code

Constant Summary collapse

IDX_MAP =

The position of each field in ps output

{
  :pid => 0,
  :ppid => 1,
  :pcpu => 2,
  :rss => 3
}

Instance Method Summary collapse

Instance Method Details

#cpu_usage(pid) ⇒ Object



31
32
33
# File 'lib/procmon/system.rb', line 31

def cpu_usage(pid)
  ps_axu[pid] && ps_axu[pid][IDX_MAP[:pcpu]].to_f
end

#memory_usage(pid) ⇒ Object



27
28
29
# File 'lib/procmon/system.rb', line 27

def memory_usage(pid)
  ps_axu[pid] && ps_axu[pid][IDX_MAP[:rss]].to_f
end

#pid_alive?(pid) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
# File 'lib/procmon/system.rb', line 18

def pid_alive?(pid)
  begin
    ::Process.kill(0, pid)
    true
  rescue Errno::ESRCH
    false
  end
end

#ps_axuObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/procmon/system.rb', line 35

def ps_axu
  # TODO: need a mutex here
  store[:ps_axu] ||= begin
    # BSD style ps invocation
    lines = `ps axo pid,ppid,pcpu,rss`.split("\n")

    lines.inject(Hash.new) do |mem, line|
      chunks = line.split(/\s+/)
      chunks.delete_if {|c| c.strip.empty? }
      pid = chunks[IDX_MAP[:pid]].strip.to_i
      mem[pid] = chunks
      mem
    end
  end
end

#storeObject



14
15
16
# File 'lib/procmon/system.rb', line 14

def store
  @store ||= Hash.new
end