Popen getting pid of newly run process

旧城冷巷雨未停 提交于 2019-11-30 05:19:08

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/4366071/popen-getting-pid-of-newly-run-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!