admin管理员组

文章数量:1323730

Is there a Ruby module or class that gives information about a currently running process that is not the current process? For example, if I have pid 1234, I'd like to get information on the user of the process, time, etc. I could get this information by shelling out to ps, but I would prefer getting the info from Ruby. For example, something like this made-up code:

require 'process/info'
process = ProcessInfo.new(1234)
puts process.pid
puts process.user

Any help in appreciated.

Is there a Ruby module or class that gives information about a currently running process that is not the current process? For example, if I have pid 1234, I'd like to get information on the user of the process, time, etc. I could get this information by shelling out to ps, but I would prefer getting the info from Ruby. For example, something like this made-up code:

require 'process/info'
process = ProcessInfo.new(1234)
puts process.pid
puts process.user

Any help in appreciated.

Share Improve this question asked Jan 12 at 7:28 tscheingeldtscheingeld 88710 silver badges24 bronze badges 1
  • 1 Not built-in but there’s the sys-proctable – Stefan Commented Jan 12 at 9:34
Add a comment  | 

2 Answers 2

Reset to default 1

You could use the sys-proctable gem (which supports multiple OSs):

require 'sys/proctable'

process = ProcTable.ps(pid: 1234)
puts process.uid

Yes, you can achieve this using pure Ruby by reading from the proc filesystem, which is available on Linux systems. Here's an example of how you can get information about a process by its PID:

class ProcessInfo
  attr_reader :pid, :uid, :cmdline, :starttime

  def initialize(pid)
    @pid = pid
    fetch_process_info
  end

  def fetch_process_info
    proc_path = "/proc/#{pid}"

    begin
      @uid = File.stat(proc_path).uid
      @cmdline = File.read("#{proc_path}/cmdline").strip
      @starttime = File.read("#{proc_path}/stat").split[21].to_i
    rescue Errno::ENOENT
      puts "Process with PID #{pid} not found."
    rescue => e
      puts "An error occurred: #{e.message}"
    end
    true
  end

  def to_h
    {
      uid: @uid,
      cmdline: @cmdline,
      starttime: @starttime
    }
  end

  def display_info
    puts "User: #{@uid}"
    puts "Command: #{@cmdline}"
    puts "Start Time: #{@starttime}"
  end
end

process = ProcessInfo.new(133)
process.display_info
p process.to_h

This script reads the process information from the proc filesystem:

  • uid is obtained from the file status.
  • cmdline is read from the cmdline file.
  • starttime is read from the stat file.

Note that the starttime value is in clock ticks since boot time. You may need to convert it to a more human-readable format if necessary.

output:

➜  SO ruby main.rb
User: 0
Command: /bin/login-f
Start Time: 1399
{uid: 0, cmdline: "/bin/login\u0000-f", starttime: 1399}

本文标签: rubyHow to get information on a process (not the current process)Stack Overflow