default stop for auto-daemonized; bug fixes
[god.git] / lib / god / system / process.rb
blob6772f13e441d1eb659b3165d4eef739eb2ff21aa
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         system("kill -0 #{@pid} &> /dev/null")
12       end
13       
14       def kill
15         system("kill -9 `cat #{@pid}`")
16       end
17       
18       # Memory usage in kilobytes (resident set size)
19       def memory
20         ps_int('rss')
21       end
22       
23       # Percentage memory usage
24       def percent_memory
25         ps_float('%mem')
26       end
27       
28       # Percentage CPU usage
29       def percent_cpu
30         ps_float('%cpu')
31       end
32       
33       # Seconds of CPU time (accumulated cpu time, user + system)
34       def cpu_time
35         time_string_to_seconds(ps_string('time'))
36       end
37       
38       private
39       
40       def ps_int(keyword)
41         `ps -o #{keyword}= -p #{@pid}`.to_i
42       end
43       
44       def ps_float(keyword)
45         `ps -o #{keyword}= -p #{@pid}`.to_f
46       end
47       
48       def ps_string(keyword)
49         `ps -o #{keyword}= -p #{@pid}`.strip
50       end
51       
52       def time_string_to_seconds(text)
53         _, minutes, seconds, useconds = *text.match(/(\d+):(\d{2}).(\d{2})/)
54         (minutes.to_i * 60) + seconds.to_i
55       end
56     end
57   
58   end
59 end