Sebastian Sebastian - 8 months ago 74
Ruby Question

Popen getting pid of newly run process

I want to run some application in background and later kill it by pid.

pipe = IO.popen("firefox 'some_url' 2>&1 &")

This code starts firefox and return me some pid, but unfortunately it's not firefox's pid.

pipe = IO.popen("firefox")

This code starts firefox and return mi some pid, firefox's pid.
Is there any solution to start external application and get its pid? Firefox is only for example it could be any other application. I also tried with libs like: Open3 and Open4 but seems to be the same effect.
I also wonder if '$!' bash variable is good solution for this? Run something in background and read '$!', what do you think?


Since you are running it in the background (command &), you get the interpreter's PID:

>> pipe = IO.popen("xcalc &")
=> 11204

$ ps awx | grep "pts/8"
11204 pts/8    Z+     0:00 [sh] <defunct>
11205 pts/8    S+     0:00 xcalc

Drop the &:

>> pipe = IO.popen("xcalc")
=> 11206

$ ps awx | grep "pts/8"
11206 pts/8    S      0:00 xcalc

For the additional issue with the redirection, see @kares' answer