Popen getting pid of newly run process

前端 未结 2 1458
不思量自难忘°
不思量自难忘° 2021-01-05 06:48

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

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

相关标签:
2条回答
  • 2021-01-05 07:36

    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

    0 讨论(0)
  • 2021-01-05 07:47

    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")

    0 讨论(0)
提交回复
热议问题