如何在 Perl 中触发并忘记进程? [英] How can I fire and forget a process in Perl?

查看:30
本文介绍了如何在 Perl 中触发并忘记进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我如何在 Perl 中触发并忘记进程吗?我已经看过ruby:如何触发并忘记子流程? 在 Ruby 中做同样的事情.

Can somebody please tell me how to fire-and-forget a process in Perl? I've already looked at ruby: how to fire and forget a subprocess? for doing the same in Ruby.

推荐答案

来自 perlfaq8 的回答如何开始在后台处理?

几个模块可以启动其他不会阻塞你的 Perl 的进程程序.您可以使用 IPC::Open3、Parallel::Jobs、IPC::Run 和一些POE 模块.有关更多详细信息,请参阅 CPAN.

Several modules can start other processes that do not block your Perl program. You can use IPC::Open3, Parallel::Jobs, IPC::Run, and some of the POE modules. See CPAN for more details.

你也可以使用

system("cmd &")

或者您可以使用 perlfunc 中的fork"中记录的 fork,进一步perlipc 中的例子.如果您使用的是 Unix,则需要注意一些事项-喜欢系统:

or you could use fork as documented in "fork" in perlfunc, with further examples in perlipc. Some things to be aware of, if you're on a Unix- like system:

STDIN、STDOUT 和 STDERR 是共享的

主进程和后台进程(子进程"process) 共享相同的 STDIN、STDOUT 和 STDERR 文件句柄.如果两者都尝试同时访问它们,可能会发生奇怪的事情.你可能想为孩子关闭或重新打开这些.你可以得到通过打开"管道来解决这个问题(参见 perlfunc 中的打开")但是某些系统这意味着子进程不能超过父母.

Both the main process and the backgrounded one (the "child" process) share the same STDIN, STDOUT and STDERR filehandles. If both try to access them at once, strange things can happen. You may want to close or reopen these for the child. You can get around this with "open"ing a pipe (see "open" in perlfunc) but on some systems this means that the child process cannot outlive the parent.

信号

您必须捕获 SIGCHLD 信号,也可能捕获 SIGPIPE.SIGCHLD 在后台进程完成时发送.SIGPIPE 是当您写入其子进程已关闭的文件句柄时发送(未捕获的 SIGPIPE 可能会导致您的程序无声无息地死亡).这不是system(cmd&")"的问题.

You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too. SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is sent when you write to a filehandle whose child process has closed (an untrapped SIGPIPE can cause your program to silently die). This is not an issue with "system("cmd&")".

僵尸

你必须准备好收割"子进程结束.

You have to be prepared to "reap" the child process when it finishes.

   $SIG{CHLD} = sub { wait };

   $SIG{CHLD} = 'IGNORE';

您也可以使用双叉.您立即 wait() 等待您的第一个孩子,init 守护进程将为您的孙子等待()一旦它退出.

You can also use a double fork. You immediately wait() for your first child, and the init daemon will wait() for your grandchild once it exits.

   unless ($pid = fork) {
       unless (fork) {
           exec "what you really wanna do";
           die "exec failed!";
       }
       exit 0;
   }
   waitpid($pid, 0);

有关执行此操作的其他代码示例,请参阅 perlipc 中的信号".僵尸不是system(prog &")"的问题.

See "Signals" in perlipc for other examples of code to do this. Zombies are not an issue with "system("prog &")".

这篇关于如何在 Perl 中触发并忘记进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆