61

I'm putting in a reaper line into a rake task to kill some additionally spawned ruby tasks as they somehow creep up on occasion.

system "ps aux | grep 'namespace:taskname' | grep ruby | grep -v grep | awk '{print $2}' | xargs kill -9; echo 'Reaped old namespace:taskname processes.'"

I'd like to add grep -v $PID_OF_CURRENT_TASK in that just to be sure I don't kill the current task that's running as well.

How do I get that PID?

1
  • You may be able to replace the whole pipeline with a well-drafted call of pkill or killall, or at least replace the first part of this pipeline with pgrep. These commands are more secure and much more understandable to a reader.
    – hagello
    Jul 20, 2015 at 9:25

1 Answer 1

123

You get the current PID in Ruby with Process.pid

10
  • 13
    There's also $$ (which came from Perl which got it from /bin/sh). Mar 1, 2012 at 3:39
  • 4
    I forgot about that. It is more cryptic, but simpler. If you require "english", then there is also $PID or something like that.
    – Linuxios
    Mar 1, 2012 at 13:52
  • 1
    Out of curiosity, what is the difference between pid, ppid, uid, euid, gid and egid? May 27, 2015 at 21:21
  • 12
    @JoshPinter: pid is the ID of the running process, ppid is the PID of the parent process (for example, in the command ruby test.rb in bash, that would be bash), gid is group id, or the UNIX group as which the process is running, uid is the UNIX user id under which the process is running (this determines privileges), and euid and egid are effective user and group IDs (which have something to do with running things as root on UNIX that I'll admit I've never really completely understood).
    – Linuxios
    May 27, 2015 at 21:24
  • Well, that was a fantastic answer @Linuxios. And in 2 1/2 minutes no less. Thanks! May 27, 2015 at 21:26

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.