How to Check from Ruby Whether a Process with a Certain Pid Is Running

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

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
>>

How to check for a running process with Ruby?

unless `ps aux | grep ar_sendmai[l]` != ""

Find a process ID by name

A quick google search came up with sys_proctable, which should let you do this in a portable way.

Disclaimer: I don't use Ruby, can't confirm if this works.

How to ensure a process is running in Ruby

You can do something like this:

Thread.new do
begin
Process.wait Process.spawn 'find /oeinfsroif'
raise unless $?.exitstatus == 0
rescue
retry
end
end.join

To manage the number of attempts before the failing:

Thread.new do
max_attempts = 10
attempts = 0
begin
Process.wait Process.spawn 'find /oeinfsroif'
raise unless $?.exitstatus == 0
rescue
attempts += 1
attempts < max_attempts ? retry : raise
end
end.join

Output:

find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
find: `/oeinfsroif': No such file or directory
rb:6:in `block in <main>': unhandled exception

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

You can delete the server.pid file.

rm /your_project_path/tmp/pids/server.pid

Else:

try in OSX:

sudo lsof -iTCP -sTCP:LISTEN -P | grep :3000

or in linux:

ps -aef | grep rails

or

lsof -wni tcp:3000

kill the process using

kill -9 PID (eg,2786)

In Ruby telling if a system process is still alive?


$alive = true
Thread.new do
`some_app`
$alive = false
end

if $alive
...

Getting the parent id of a given process in Ruby

You can just remember it in a variable:

parent_pid = Process.pid

Process.fork do
child_pid = Process.pid
puts parent_pid, child_pid
# do stuff
exit
end

Process.wait

# 94791
# 94798

alternatively, if you need the information on the level of the parent process:

parent_pid = Process.pid

child_pid = Process.fork do
# do stuff
exit
end

Process.wait
puts parent_pid, child_pid

# 6361
# 6362


Related Topics



Leave a reply



Submit