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

前端 未结 9 1892
眼角桃花
眼角桃花 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: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.

提交回复
热议问题