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?

hagello
  • 2,843
  • 2
  • 27
  • 37
ylluminate
  • 12,102
  • 17
  • 78
  • 152
  • 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 '15 at 09:25

1 Answers1

123

You get the current PID in Ruby with Process.pid

Linuxios
  • 34,849
  • 13
  • 91
  • 116
  • 13
    There's also `$$` (which came from Perl which got it from `/bin/sh`). – mu is too short Mar 01 '12 at 03: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 01 '12 at 13:52
  • 1
    Out of curiosity, what is the difference between `pid`, `ppid`, `uid`, `euid`, `gid` and `egid`? – Joshua Pinter May 27 '15 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 '15 at 21:24
  • Well, that was a fantastic answer @Linuxios. And in 2 1/2 minutes no less. Thanks! – Joshua Pinter May 27 '15 at 21:26
  • @JoshPinter: My pleasure! Always happy to help. – Linuxios May 27 '15 at 21:26
  • @Linuxios I didn't think I'd get an answer at all, let alone that quickly, so I posted a question for it. Not sure if you want to post your comment on there as an answer. Probably would help others in the future.... http://stackoverflow.com/questions/30493424/what-is-the-difference-between-a-process-pid-ppid-uid-euid-gid-and-egid – Joshua Pinter May 27 '15 at 21:27
  • @JoshPinter: writing an answer now. – Linuxios May 27 '15 at 21:29
  • @Linuxios `euid` and `egid` determine the privileges, not `uid` or `gid`. They differ when you use `sudo` or other s-bit programs (`ls -l /usr/bin/sudo`) or `seteuid` / `setegid`. – hagello Jun 25 '15 at 10:29
  • @hagello: Thanks. I'd had to take out my old Linux book for that one. – Linuxios Jun 25 '15 at 15:43