Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make Perl wait for child processes started in the background with system()?

I have some Perl code that executes a shell script for multiple parameters, to simplify, I'll just assume that I have code that looks like this:

for $p (@a){
    system("/path/to/file.sh $p&");
}

I'd like to do some more things after that, but I can't find a way to wait for all the child processes to finish before continuing.

Converting the code to use fork() would be difficult. Isn't there an easier way?

like image 272
Osama Al-Maadeed Avatar asked May 26 '09 16:05

Osama Al-Maadeed


1 Answers

Using fork/exec/wait isn't so bad:

my @a = (1, 2, 3);
for my $p (@a) {
   my $pid = fork();
   if ($pid == -1) {
       die;
   } elsif ($pid == 0) {
      exec '/bin/sleep', $p or die;
   }
}
while (wait() != -1) {}
print "Done\n";
like image 171
Dave Avatar answered Nov 02 '22 04:11

Dave