Popen获取新运行进程的pid

发布于 2024-10-06 02:42:25 字数 427 浏览 0 评论 0原文

我想在后台运行一些应用程序,然后通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼前雾蒙蒙 2024-10-13 02:42:25

由于您在后台运行它(command &),因此您可以获得解释器的 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 ' 回答

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

不美如何 2024-10-13 02:42:25

这不仅仅是在后台运行它,而且由于 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")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文