Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] forking off in perl

Expand Messages
  • Brad Lhotsky
    inside the while loop: my @cmds = ( $job1, $job2, $job3 ); my @kids = (); foreach my $cmd ( @cmds ) { my $pid = fork(); # if $pid if undefined the fork failed;
    Message 1 of 2 , Sep 30, 2004
    • 0 Attachment
      inside the while loop:

      my @cmds = ( $job1, $job2, $job3 );

      my @kids = ();
      foreach my $cmd ( @cmds ) {
      my $pid = fork();

      # if $pid if undefined the fork failed;
      die "unable to fork: $!" unless defined $pid;

      # greater than zero, we're the parent,
      # store the pid and continue;
      push @kids,$pid and next
      if $pid > 0;

      # we next'd out if we're the parent.
      # This code will be run in the child ONLY.
      exec $cmd;
      exit 0;
      }

      #
      # make a cheap wait loop;
      my $kidStillAlive=1;
      while($kidStillAlive){
      foreach my $kid (@kids) {
      # kill 0, PID
      # returns 1 if kid is still alive
      # returns undef if the pid is not alive
      last if $kidStillAlive = kill 0, $kid;
      }
      # select is going to block on the
      # following input, output, and error handle
      # for 0.5 seconds. sending undef means it
      # won't block on any filehandles, but will
      # return control to the program after 0.5
      # seconds. A poor man's use Time::HiRes;
      select undef, undef, undef, 0.5;
      }

      #
      # Use system here.. read more about that in
      # perldoc -f exec
      # and
      # perldoc -f system
      system $job4;

      Hope that helps.. Code is untested.

      You might also want to look into threading since you're post used the
      "join" terminology:

      perldoc perlthrtut

      Enjoy.

      On Thu, Sep 30, 2004 at 05:59:02PM -0000, Thomas George Simon wrote:
      > Hi Folks,
      > How do you fork off jobs in perl ?
      > This is my problem :
      >
      > while (1) {
      > fork
      > job1
      > job2
      > job3
      > join all
      > job4
      > sleep 100
      > }
      >
      > where all job* are unix programs.
      > I want the first three jobs to finish ( in parallel ) first and then
      > do job4. job4 uses results of the first three jobs.
      >
      > Thanks.
      > Thomas.
      >
      >
      >
      >
      >
      > Unsubscribing info is here: http://help.yahoo.com/help/us/groups/groups-32.html
      > Yahoo! Groups Links
      >
      >
      >
      >
      >

      --
      Brad Lhotsky <brad@...>
    Your message has been successfully submitted and would be delivered to recipients shortly.