Popen获取新运行进程的pid
我想在后台运行一些应用程序,然后通过 pid 杀死它。
pipe = IO.popen("firefox 'some_url' 2>&1 &")
pipe.pid
这段代码启动firefox并返回一些pid,但不幸的是它不是firefox的pid。
pipe = IO.popen("firefox")
pipe.pid
这段代码启动firefox并返回一些pid,firefox的pid。 有什么解决方案可以启动外部应用程序并获取其pid吗? Firefox 仅作为示例,它可以是任何其他应用程序。我也尝试过使用 Open3 和 Open4 等库,但效果似乎相同。 我还想知道是否“$!” bash 变量是解决这个问题的好方法吗?在后台运行一些东西并读取“$!”,你觉得怎么样?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您在后台运行它(
command &
),因此您可以获得解释器的 PID:删除
&
:有关重定向的其他问题,请参阅@kares ' 回答
Since you are running it in the background (
command &
), you get the interpreter's PID:Drop the
&
:For the additional issue with the redirection, see @kares' answer
这不仅仅是在后台运行它,而且由于
2>&1
重定向 err/out 会导致
IO.popen
将另一个进程放在实际进程前面(pipe.pid
不正确)这里有详细的见解:http://unethicalblogger.com/2011/11/12/popen-can-suck-it.html
可能的修复方法可以使用
exec
例如 <代码>IO.popen("执行 firefox 'some_url' 2>&1")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")