Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

process

ruby

pid

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.

like image 727
Pistos Avatar asked Nov 28 '08 05:11

Pistos


People also ask

How do I know if a process is running on PID?

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

How do I find the PID process?

The ps -p <PID> command is pretty straightforward to get the process information of a PID. Alternatively, we can also access the special /proc/PID directory to retrieve process information.

What is Server PID?

Short for process identifier, a PID is a unique number that identifies each running processes in an operating system, such as Linux, Unix, macOS, and Microsoft Windows.

What is a process in Ruby?

A Ruby Process is the instance of an application or a forked copy. In a traditional Rails application, each Process contains all the build up, initialization, and resource allocation the app will need.


2 Answers

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 
like image 107
tonystubblebine Avatar answered Sep 21 '22 04:09

tonystubblebine


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 >>  
like image 33
Dustin Avatar answered Sep 23 '22 04:09

Dustin