How can I check from Ruby whether a process with a certain pid is running?

前端 未结 9 1890
眼角桃花
眼角桃花 2021-01-30 16:18

If there is more than one way, please list them. I only know of one, but I\'m wondering if there is a cleaner, in-Ruby way.

相关标签:
9条回答
  • 2021-01-30 17:09

    A *nix-only approach would be to shell-out to ps and check if a \n (new line) delimiter exists in the returned string.

    Example IRB Output

    1.9.3p448 :067 > `ps -p 56718`                                                          
    "  PID TTY           TIME CMD\n56718 ttys007    0:03.38 zeus slave: default_bundle   \n"
    

    Packaged as a Method

    def process?(pid)  
      !!`ps -p #{pid.to_i}`["\n"]
    end
    
    0 讨论(0)
  • 2021-01-30 17:11

    This is how I've been doing it:

    def alive?(pid)
      !!Process.kill(0, pid) rescue false
    end
    
    0 讨论(0)
  • 2021-01-30 17:12

    The difference between the Process.getpgid and Process::kill approaches seems to be what happens when the pid exists but is owned by another user. Process.getpgid will return an answer, Process::kill will throw an exception (Errno::EPERM).

    Based on that, I recommend Process.getpgid, if just for the reason that it saves you from having to catch two different exceptions.

    Here's the code I use:

    begin
      Process.getpgid( pid )
      true
    rescue Errno::ESRCH
      false
    end
    
    0 讨论(0)
提交回复
热议问题