Popen gets the pid of a new process

I want to run some kind of application in the background and kill its pid later.

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

This code starts firefox and returns me the pid, but unfortunately it is not firefox pid.

 pipe = IO.popen("firefox") pipe.pid 

This code starts firefox and returns mi pid, firefox pid. Is there a solution to start an external application and get its pid? Firefox, for example, can be any other application. I also tried with libs like: Open3 and Open4, but it seems to have the same effect. I also wonder, "$!" is a bash variable a good solution for this? Run something in the background and read "$!" What do you think?

+6
linux ruby io popen pid
source share
2 answers

Since you use it in the background ( command & ), you get the interpreter PID:

 >> pipe = IO.popen("xcalc &") >> pipe.pid => 11204 $ ps awx | grep "pts/8" 11204 pts/8 Z+ 0:00 [sh] <defunct> 11205 pts/8 S+ 0:00 xcalc 

Drop & :

 >> pipe = IO.popen("xcalc") >> pipe.pid => 11206 $ ps awx | grep "pts/8" 11206 pts/8 S 0:00 xcalc 

For additional redirection issue see @kares answer

+7
source share

it's not just running it in the background, but also because of 2>&1

redirecting errors / exits causes IO.popen to put another process in front of your actual process ( pipe.pid will be wrong)

here is the detailed information: http://unethicalblogger.com/2011/11/12/popen-can-suck-it.html

a possible fix for this could be used by exec , for example. IO.popen("exec firefox 'some_url' 2>&1")

+4
source share

All Articles