在后台运行perl子例程

6
有没有一种方法可以在后台运行Perl子程序?我已经查看了一些关于线程的提及,但是看到一个示例或指向正确方向会很有帮助。谢谢。
想要在后台运行run_sleep
#!/usr/bin/perl

print "Start of script";
run_sleep();
print "End of script";

sub run_sleep {
    select(undef, undef, undef, 5);  #Sleep for 5 seconds then do whatever
}

在程序中,“后台运行”是指该程序在后台执行而不干扰用户当前操作的状态。如果你希望在等待警报时,同一脚本中的其他代码能够继续执行,那么你是想让它在后台运行吗? - perreal
我希望脚本不必等待自己完成。我希望子程序 run_sleep 在一个新的进程中运行。 - KingKongFrog
如果这只是为了计时器,您可以使用alarm:http://perldoc.perl.org/functions/alarm.html - perreal
不要认为它是这样的。更好的解释是我有一个网站,可以构建可下载文件。该文件需要很长时间,因此现在我希望它在后台运行。计划是让用户在请求下载时立即看到“正在处理您的下载,并在完成时通过电子邮件通知您”,并在后台构建文件。 - KingKongFrog
你可以先提示信息,然后开始构建。 - Karthik T
2个回答

10

我认为最简单的方法是通过fork出一个子进程来执行任务。由于Perl线程可能会带来麻烦,因此我尽可能避免使用它们。

这里是一个简单的示例:

use strict;
use warnings;

print "Start of script\n";
run_sleep();
print "End of script\n";

sub run_sleep { 
    my $pid = fork;
    return if $pid;     # in the parent process
    print "Running child process\n";
    select undef, undef, undef, 5;
    print "Done with child process\n";
    exit;  # end child process
}
如果你在你的shell中运行这个命令,你会看到类似下面的输出结果:
Start of script
End of script
Running child process

(等待五秒钟)

Done with child process

父进程将立即退出并将您返回到shell;子进程将在五秒钟后将其输出发送到您的shell。

如果您希望父进程保持活动状态直到子进程完成,那么可以使用waitpid


如果父进程死亡,子进程是否也会跟着死亡? - user1804599

6

使用线程:

use strict;
use warnings;
use threads;

my $thr = threads->new(\&sub1, "Param 1", "Param 2"); 

sub sub1 { 
  sleep 5;
  print "In the thread:".join(",", @_),"\n"; 
}

for (my $c = 0; $c < 10; $c++) {
  print "$c\n";
  sleep 1;
}

$thr->join();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接