Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run perl subroutine in the background

Tags:

process

perl

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
}
like image 972
KingKongFrog Avatar asked Dec 18 '12 03:12

KingKongFrog


2 Answers

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.

like image 92
friedo Avatar answered Nov 15 '22 09:11

friedo


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();
like image 25
perreal Avatar answered Nov 15 '22 08:11

perreal