简体   繁体   English

如何在Perl中管理多个子进程?

[英]How do I manage multiple subprocesses in Perl?

I have a Perl program that needs to run about half a dozen programs at the same time in the background and wait for them all to finish before continuing. 我有一个Perl程序,需要在后台同时运行大约六个程序,并等待它们全部完成后再继续。 It is also very important that the exit status of each can be captured. 同样非常重要的是可以捕获每个的退出状态。

Is there a common idiom for doing this in Perl? 在Perl中有这个常见的习惯用法吗? I'm currently thinking of using threads. 我目前正在考虑使用线程。

Don't use threads. 不要使用线程。 Threads suck. 线程很糟糕。 The proper way is to fork multiple processes and wait for them to finish. 正确的方法是fork多个进程并wait它们完成。 If you use wait or waitpid , the exit status of the process in question will be available in $? 如果您使用waitwaitpid ,相关流程的退出状态将以$? .

See the perldocs for fork , wait , and waitpid , and also the examples in this SO thread. 请参阅forkwaitwaitpid的perldocs,以及 SO线程中的示例。

If all you need is to just manage a pool of subprocesses that doesn't exceed a certain size, check out the excellent Parallel::ForkManager . 如果您只需管理一个不超过一定大小的子进程池,请查看优秀的Parallel :: ForkManager

Normally you would fork + exec (on unix based systems, this is traditional) 通常你会fork + exec(在基于unix的系统上,这是传统的)

The fork call will duplicate the current process, and if you needed to you could then call exec in one of the children to do something different. fork调用将复制当前进程,如果需要,您可以在其中一个子进程中调用exec来执行不同的操作。 It sounds like you just want to fork and call a different method/function in your child process. 听起来你只想在子进程中分叉并调用不同的方法/函数。

If you want something more complex, check cpan for POE - that lets you manage all sorts of complex scenarios. 如果你想要更复杂的东西,请检查cpan for POE - 这可以让你管理各种复杂的场景。

Useful links: 有用的链接:

Google "perl cookbook forking server" too - only allowed to post one link unless I log in. 谷歌“perl cookbook forking server”也是 - 只允许发布一个链接,除非我登录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM