Module: Ziltoid::System
- Defined in:
- lib/ziltoid/system.rb
Constant Summary collapse
- PS_FIELDS =
The position of each field in ps output
[:pid, :ppid, :cpu, :ram]
Class Method Summary collapse
- .cpu_usage(pid, include_children = true) ⇒ Object
- .get_children(parent_pid) ⇒ Object
- .pid_alive?(pid) ⇒ Boolean
- .ps_aux ⇒ Object
- .ram_usage(pid, include_children = true) ⇒ Object
Class Method Details
.cpu_usage(pid, include_children = true) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/ziltoid/system.rb', line 42 def cpu_usage(pid, include_children = true) ps = ps_aux return unless ps[pid] cpu_used = ps[pid][:cpu].to_f get_children(pid).each do |child_pid| cpu_used += ps[child_pid][:cpu].to_f if ps[child_pid] end if include_children cpu_used end |
.get_children(parent_pid) ⇒ Object
66 67 68 69 70 71 72 73 |
# File 'lib/ziltoid/system.rb', line 66 def get_children(parent_pid) child_pids = [] ps_aux.each_pair do |_pid, info| child_pids << info[:pid].to_i if info[:ppid].to_i == parent_pid.to_i end grand_children = child_pids.map { |pid| get_children(pid) }.flatten child_pids.concat grand_children end |
.pid_alive?(pid) ⇒ Boolean
10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/ziltoid/system.rb', line 10 def pid_alive?(pid) return false if pid.nil? begin ::Process.kill(0, pid) true rescue Errno::EPERM # no permission, but it is definitely alive true rescue Errno::ESRCH false end end |
.ps_aux ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/ziltoid/system.rb', line 22 def ps_aux # BSD style ps invocation processes = `ps axo pid,ppid,pcpu,rss`.split("\n") processes.inject({}) do |result, process| info = process.split(/\s+/) info.delete_if { |p_info| p_info.strip.empty? } info.map! { |p_info| p_info.gsub(",", ".") } info = PS_FIELDS.each_with_index.inject({}) do |info_hash, (field, field_index)| info_hash[field] = info[field_index] info_hash end pid = info[:pid].strip.to_i result[pid] = info result end end |
.ram_usage(pid, include_children = true) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/ziltoid/system.rb', line 54 def ram_usage(pid, include_children = true) ps = ps_aux return unless ps[pid] mem_used = ps[pid][:ram].to_i get_children(pid).each do |child_pid| mem_used += ps[child_pid][:ram].to_i if ps[child_pid] end if include_children mem_used end |