简体   繁体   English

在后台运行perl子例程

[英]Run perl subroutine in the background

Is there a way to run a perl subroutine in the background? 有没有办法在后台运行perl子程序? I've looked around and seen some mentions in regards to threads but it would help to see an example, or point me in the right direction. 我环顾四周,看到一些关于线程的提及,但它会有助于看到一个例子,或指向我正确的方向。 Thanks. 谢谢。

Would like to run run_sleep in the background. 想在后台运行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
}

The easiest way (IMHO) is to fork a subprocess and let that do the work. 最简单的方法(恕我直言)是fork一个子进程让它做的工作。 Perl threads can be painful so I try to avoid them whenever possible. Perl线程可能会很痛苦,所以尽量避免使用它们。

Here's a simple example 这是一个简单的例子

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
}

If you run this in your shell, you'll see output that looks something like this: 如果你在shell中运行它,你会看到如下所示的输出:

Start of script
End of script
Running child process

(wait five seconds) (等五秒钟)

Done with child process

The parent process will exit immediately and return you to your shell; 父进程将立即退出并返回到您的shell; the child process will send its output to your shell five seconds later. 子进程将在五秒后将其输出发送到您的shell。

If you want the parent process to stay around until the child is done, then you can use waitpid . 如果您希望父进程在子进程完成之前保持waitpid ,那么您可以使用waitpid

Using threads: 使用线程:

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.

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