在后台运行perl子例程

Kin*_*rog 5 perl process

有没有办法在后台运行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
}
Run Code Online (Sandbox Code Playgroud)

fri*_*edo 8

最简单的方法(恕我直言)是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
}
Run Code Online (Sandbox Code Playgroud)

如果你在shell中运行它,你会看到如下所示的输出:

Start of script
End of script
Running child process
Run Code Online (Sandbox Code Playgroud)

(等五秒钟)

Done with child process
Run Code Online (Sandbox Code Playgroud)

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

如果您希望父进程在子进程完成之前保持不变,那么您可以使用waitpid.


per*_*eal 5

使用线程:

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();
Run Code Online (Sandbox Code Playgroud)