How to get PID of current rake task?

30,345

You get the current PID in Ruby with Process.pid

Share:
30,345
ylluminate
Author by

ylluminate

Updated on July 09, 2022

Comments

  • ylluminate
    ylluminate almost 2 years

    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?

  • mu is too short
    mu is too short about 12 years
    There's also $$ (which came from Perl which got it from /bin/sh).
  • Linuxios
    Linuxios about 12 years
    I forgot about that. It is more cryptic, but simpler. If you require "english", then there is also $PID or something like that.
  • Joshua Pinter
    Joshua Pinter almost 9 years
    Out of curiosity, what is the difference between pid, ppid, uid, euid, gid and egid?
  • Linuxios
    Linuxios almost 9 years
    @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).
  • Joshua Pinter
    Joshua Pinter almost 9 years
    Well, that was a fantastic answer @Linuxios. And in 2 1/2 minutes no less. Thanks!
  • Linuxios
    Linuxios almost 9 years
    @JoshPinter: My pleasure! Always happy to help.
  • Joshua Pinter
    Joshua Pinter almost 9 years
    @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.... stackoverflow.com/questions/30493424/…
  • Linuxios
    Linuxios almost 9 years
    @JoshPinter: writing an answer now.
  • hagello
    hagello almost 9 years
    @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.
  • Linuxios
    Linuxios almost 9 years
    @hagello: Thanks. I'd had to take out my old Linux book for that one.