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.
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.
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.
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.
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.
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
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 >>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With