#1
  1. perl virgin
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    Seattle, WA
    Posts
    460
    Rep Power
    19

    help with fork logic


    what i am trying to do is basically do a number of jobs in parallel in buckets.. kind of like lets say i have 12 items, and i want them to do them in parallel in sets of 3..

    im trying to fork but i guess i can’t quite get the logic in place…

    Code:
    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    print "Starting main program\n";
    my @childs;
    
    my @item = ( "A","B","C","D","E","F","G","H","I","J" ) ;
    my $child_count = 3;
    my $count = 0 ;
    
    while ( @item ) {
            if ( scalar @childs < $child_count ) {
                    my $content = shift (@item) ;
                    my $pid = fork () ;
            if ($pid) {
            # parent
            print "pid is $pid, parent $$\n";
            push(@childs, $pid);
            } elsif ($pid == 0) {
                    # child
                    sub1($content);
                    exit 0;
            } else {
                    die "couldnt fork: $!\n";
            }
                    my $zz = scalar @childs ;
                    print "$zz\n";
            }
            foreach (@childs) {
            my $tmp = waitpid($_, 0);
             print "done with pid $tmp\n";
            }
    }
    
    print "End of main program\n";
    
    
    sub sub1 {
            my $item = shift;
            print "started child process for  $item\n";
            sleep 3 ;
            print "done with child process for $item\n";
            return $item;
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Apr 2009
    Posts
    2,233
    Rep Power
    1298
    Take a look at the Parallel::ForkManager module.

    Comments on this post

    • Laurent_R agrees
  4. #3
  5. perl virgin
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    Seattle, WA
    Posts
    460
    Rep Power
    19
    thanks..that is much easier than trying to come with my own logic

IMN logo majestic logo threadwatch logo seochat tools logo