Popen得到新运行过程的pid [英] Popen getting pid of newly run process
问题描述
我想在后台运行一些应用程序,然后用pid杀死它。
I want to run some application in background and later kill it by pid.
pipe = IO.popen("firefox 'some_url' 2>&1 &")
pipe.pid
此代码启动firefox并返回一些pid,但不幸的是它不是firefox的pid。
This code starts firefox and return me some pid, but unfortunately it's not firefox's pid.
pipe = IO.popen("firefox")
pipe.pid
此代码启动firefox并返回mi一些pid,firefox的pid。
是否有任何解决方案可以启动外部应用程序并获得其pid? Firefox只是例如它可以是任何其他应用程序。我也试过像libs这样的:Open3和Open4,但似乎效果相同。
我也想知道'$!'bash变量是否是一个很好的解决方案?在后台运行并读取'$!',你觉得怎么样?
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?
推荐答案
因为你在后台运行它( 命令&
),您获得解释器的PID:
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
放弃 &
:
>> pipe = IO.popen("xcalc")
>> pipe.pid
=> 11206
$ ps awx | grep "pts/8"
11206 pts/8 S 0:00 xcalc
重定向的其他问题,请参阅@kares的回答
For the additional issue with the redirection, see @kares' answer
这篇关于Popen得到新运行过程的pid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!