Is there a ruby method to get process start time? Something like the following in shell:
$ ps -p $$ -o lstart
STARTED
Thu Oct 18 11:49:22 2012
I was hoping to avoid parsing ps output. Also, I know how to parse /proc/self/status on linux to get at the info, but I was hoping for a more portable solution.
Update:
A portable way to do this is exactly what I wanted. I used sys/proctable and use the following line to get what I wanted:
ProcTable.ps($$).starttime
Thanks, Koen.
Update:
I was playing around a bit with this and found that it’s not as portable as I thought. On Darwin, a Time object is returned. On Linux, an integer is returned that corresponds to the number of jiffies since boot. Unfortunately, you need to use the sysconf syscall to get the number of ms/jiffy. This syscall is not available directly on ruby. I used the following to get the proc start time on Linux:
module LinuxCLib
extend FFI::Library
ffi_lib 'c'
@@cg = FFI::ConstGenerator.new(nil, :required => true) do |gen|
gen.include('unistd.h')
gen.const(:_SC_CLK_TCK)
end
attach_function :sysconf, [:int], :long
def self.hz
self.sysconf(@@cg["_SC_CLK_TCK"].to_i)
end
end
def self.get_proc_starttime
proc_jiffies_since_boot_starttime = Sys::ProcTable.ps($$).starttime
stat_lines = File.open("/proc/stat").readlines
system_s_since_epoch_boottime = catch(:boottime) do
stat_lines.each do |line|
split_line = line.split
throw :boottime, split_line[1].to_i if split_line[0] == "btime"
end
nil
end
proc_s_since_epoch_starttime = (
proc_jiffies_since_boot_starttime/LinuxCLib::hz + system_s_since_epoch_boottime)
Time.at(proc_s_since_epoch_starttime)
end
There is a gem that could do that: sys-proctable
It parses the files in
/procInstall the gem
Require the gem
For all processes
For just a single process (like in your example)
And if you don’t want to use the gem, maybe you can extract the part of how they parse the
/procfiles from the sourceEDIT:
I misread the part that you do know how to parse the
/procfiles. But maybe the gem still can be of use to you, making it portable and so.