[英]Run perl subroutine in the background
有沒有辦法在后台運行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
}
最簡單的方法(恕我直言)是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。
使用線程:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.