Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 &")
pipe.pid

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

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

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?

like image 510
Sebastian Avatar asked Dec 06 '10 11:12

Sebastian


People also ask

Does Popen start a new process?

To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.

Does Popen wait for process to finish?

Using Popen MethodThe Popen method does not wait to complete the process to return a value. This means that the information you get back will not be complete.

What is the command to get the PID of the most recent background command process?

The PID of the last executed command is in the $! shell variable: my-app & echo $!


2 Answers

Since you are running it in the background (command &), you get the interpreter's 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 the &:

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

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

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

like image 168
tokland Avatar answered Sep 23 '22 04:09

tokland


it's not just about running it in the background but also due 2>&1

redirecting err/out causes IO.popen to put another process in front of your actual process ( pipe.pid won't be correct)

here's a detailed insight: http://unethicalblogger.com/2011/11/12/popen-can-suck-it.html

possible fix for this could be using exec e.g. IO.popen("exec firefox 'some_url' 2>&1")

like image 28
kares Avatar answered Sep 21 '22 04:09

kares