Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a different process id is running using Java or JRuby on Linux?

I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution). It can be system dependent for Linux (specifically Debian and/or Ubuntu).

I already have the PID I am looking for, just need to see if it is currently running.


UPDATE:

Thanks for all the responses everyone! I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have.

like image 286
Mike Stone Avatar asked Aug 07 '26 20:08

Mike Stone


2 Answers

Darron's comment was spot on, but rather than calling the "kill" binary, you can just use Ruby's Process.kill method with the 0 signal:

#!/usr/bin/ruby 

pid = ARGV[0].to_i

begin
    Process.kill(0, pid)
    puts "#{pid} is running"
rescue Errno::EPERM                     # changed uid
    puts "No permission to query #{pid}!";
rescue Errno::ESRCH
    puts "#{pid} is NOT running.";      # or zombied
rescue
    puts "Unable to determine status for #{pid} : #{$!}"
end

[user@host user]$ ./is_running.rb 14302
14302 is running

[user@host user]$ ./is_running.rb 99999
99999 is NOT running.

[user@host user]$ ./is_running.rb 37
No permission to query 37!

[user@host user]$ sudo ./is_running.rb 37
37 is running

Reference: http://pleac.sourceforge.net/pleac_ruby/processmanagementetc.html

like image 62
Jay Avatar answered Aug 09 '26 10:08

Jay


Unix has a special feature of the kill system call around signal zero. Error checking is performed, but no signal is sent.

def pid_exists? (pid)
    system "kill -0 #{pid}"
    return $? == 0
end

One caveat: this won't detect processes with that pid that you don't have permission to signal.

like image 27
Darron Avatar answered Aug 09 '26 11:08

Darron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!