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

前端 未结 9 1889
眼角桃花
眼角桃花 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 16:56

    @John T, @Dustin: Actually, guys, I perused the Process rdocs, and it looks like

    Process.getpgid( pid )
    

    is a less violent means of applying the same technique.

    0 讨论(0)
  • 2021-01-30 16:57

    You can try using

    Process::kill 0, pid
    

    where pid is the pid number, if the pid is running it should return 1.

    0 讨论(0)
  • 2021-01-30 17:00

    If it's a process you expect to "own" (e.g. you're using this to validate a pid for a process you control), you can just send sig 0 to it.

    >> Process.kill 0, 370
    => 1
    >> Process.kill 0, 2
    Errno::ESRCH: No such process
        from (irb):5:in `kill'
        from (irb):5
    >> 
    
    0 讨论(0)
  • 2021-01-30 17:01

    I've dealt with this problem before and yesterday I compiled it into the "process_exists" gem.

    It sends the null signal (0) to the process with the given pid to check if it exists. It works even if the current user does not have permissions to send the signal to the receiving process.

    Usage:

    require 'process_exists'
    
    pid = 12
    pid_exists = Process.exists?(pid)
    
    0 讨论(0)
  • 2021-01-30 17:02

    For child processes, other solutions like sending a signal won't behave as expected: they will indicate that the process is still running when it actually exited.

    You can use Process.waitpid if you want to check on a process that you spawned yourself. The call won't block if you're using the Process::WNOHANG flag and nil is going to be returned as long as the child process didn't exit.

    Example:

    pid = Process.spawn('sleep 5')
    Process.waitpid(pid, Process::WNOHANG) # => nil
    sleep 5
    Process.waitpid(pid, Process::WNOHANG) # => pid
    

    If the pid doesn't belong to a child process, an exception will be thrown (Errno::ECHILD: No child processes).

    The same applies to Process.waitpid2.

    0 讨论(0)
  • 2021-01-30 17:04

    Under Linux you can obtain a lot of attributes of running programm using proc filesystem:

    File.read("/proc/#{pid}/cmdline")
    File.read("/proc/#{pid}/comm")
    
    0 讨论(0)
提交回复
热议问题