7

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
}
5
  • what do you mean by running in the background? do you want other code from the same script to execute while waiting for alarm? Commented Dec 18, 2012 at 3:32
  • I want the script to not wait for itself to finish. I want the sub routine run_sleep to run in a new process. Commented Dec 18, 2012 at 3:34
  • if this is just for the timer you can use alarm: perldoc.perl.org/functions/alarm.html Commented Dec 18, 2012 at 3:35
  • Dont think it is. A better explanation is I have a site that builds a downloadable file. The file takes FOREVER so now I want it to run in the background. The plan is for the user to see "your download is processing and we'll email you when completed" as soon as they request the download, and have the file get built in the background. Commented Dec 18, 2012 at 3:40
  • You could certainly prompt the message and then start building. Commented Dec 18, 2012 at 3:48

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to have the children die if the parent dies?
6

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.