简体   繁体   中英

Run perl subroutine in the background

Is there a way to run a perl subroutine in the background? 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.

#!/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. Perl threads can be painful so I try to avoid them whenever possible.

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:

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; the child process will send its output to your shell five seconds later.

If you want the parent process to stay around until the child is done, then you can use 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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