started implementation of System::Process
[god.git] / lib / god / system / process.rb
blobe2c0e72dd7c19945f7b2fbd2555b73142efd8405
1 module God
2   module System
3   
4     class Process
5       def initialize(pid)
6         @pid = pid.to_i
7       end
8       
9       # Return true if this process is running, false otherwise
10       def exists?
11         !ps_string('command').empty?
12       end
13       
14       # Memory usage in kilobytes (resident set size)
15       def memory
16         ps_int('rss')
17       end
18       
19       # Percentage memory usage
20       def percent_memory
21         ps_float('%mem')
22       end
23       
24       # Percentage CPU usage
25       def percent_cpu
26         ps_float('%cpu')
27       end
28       
29       # Seconds of CPU time (accumulated cpu time, user + system)
30       def cpu_time
31         time_string_to_seconds(ps_string('time'))
32       end
33       
34       private
35       
36       def ps_int(keyword)
37         `ps -o #{keyword}= -p #{@pid}`.to_i
38       end
39       
40       def ps_float(keyword)
41         `ps -o #{keyword}= -p #{@pid}`.to_f
42       end
43       
44       def ps_string(keyword)
45         `ps -o #{keyword}= -p #{@pid}`.strip
46       end
47       
48       def time_string_to_seconds(text)
49         _, minutes, seconds, useconds = *text.match(/(\d+):(\d{2}).(\d{2})/)
50         (minutes.to_i * 60) + seconds.to_i
51       end
52     end
53   
54   end
55 end