dude01 has asked for the wisdom of the Perl Monks concerning the following question:

I want to call a subroutine in the background from within another subroutine in my perl program. How do I do that. I have
sub getProc { #do some stuff } sub getInput { while(<FILE>) { # do some stuff # call getProc but run it in the background }

Replies are listed 'Best First'.
fork
by howard40 (Beadle) on Mar 01, 2001 at 10:19 UTC
    Here's an extremely simplistic example of how to fork a child process off and have it running alongside the parent... if you want to do something simple and non-vital, you could do it this way...

    beware though, there are many problems and pitfalls with forks. (perhaps in a future version of perl, there'll be a spork() function that will eliminate some of the problems with fork() :))

    To use this code, just replace the while() loops with whatever function calls you need to make... hope it helps
    #!/usr/bin/perl use strict; my $k_pid; die "Can't fork! ($!)" unless defined ($k_pid = fork()); my $i = 1; my $n = 1; if ($k_pid) { #parent code while (1==1) { $n++; print "Parent ($i)($n) \n"; sleep(1); } kill("TERM" => $k_pid); } else { #child code while (1==1) { $i++; print "Child: ($i)($n)\n"; sleep(1); } }
Re: How do run a subroutine in the background
by AgentM (Curate) on Mar 01, 2001 at 07:40 UTC
    You can find an explanation of the weakness inherent in PerlThreads AND a potential solution here. Keep in mind that on Winduz, fork is not supported well (minimal functionality).
    AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
Re: How do run a subroutine in the background
by rpc (Monk) on Mar 01, 2001 at 07:13 UTC
    One option is to use Thread, but this (probably) requires recompiling perl. Without threads, you can't run a single subroutine in the background; it has to be an entire process. For this, use fork.
Re: How do run a subroutine in the background
by enoch (Chaplain) on Mar 01, 2001 at 10:23 UTC
    Here is the basic code for forking another process. Have fun.
    sub getProc { #do some stuff } sub getInput { while(<FILE>) { # do some stuff up here... $childPid = fork(); #fork a process if($childPid == 0) { #okay, in the child #call getProc getProc(); } else { # okay, we are in the parent, # so, let's continuing doing what we do } } }

    Jeremy
Re: How do run a subroutine in the background
by tomhukins (Curate) on Mar 01, 2001 at 15:35 UTC
    If you don't want to get to grips with threads or IPC, POE can be a simple way of doing this.
Re: How do run a subroutine in the background
by Beatnik (Parson) on Mar 01, 2001 at 13:40 UTC
    If you're gonna use Threads (limits, requirements, pitfalls, etc mentioned above) , you might as well look at perlthrtut

    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.
perldoc ipc stuff
by howard40 (Beadle) on Mar 01, 2001 at 10:05 UTC