开发者

Problems while making a multiprocessing task in Perl

I'm trying to make a basic multiprocessing task and this is what I have. First of all, I don't know the right way to make this program as a non-blocking process, because when I am waiting for the response of a child (with waitpid) the other processes also have to wait in the queue, but, what will happen if some child processes die before (I mean, the processes die in disorder)? So, I've been searching and I foud that I can get the PID of the process that just die, for that I use waitpid(-1, WNOHANG). I always get a warning that WNOHANG is not a number, but when I added the lib sys_wait_h, I didn't get that error but the script never waits for PID, what may be the error?


#!/usr/bin/perl
#use POSIX ":sys_wait_h"; #if I use this library, I dont get the error, b开发者_运维技巧ut it wont wait for the return of the child
use warnings;

main(@ARGV);

sub main{
 my $num = 3;
 for(1..$num){
  my $pid = fork();
  if ($pid) {
   print "Im going to wait (Im the parent); my child is: $pid\n";
   push(@childs, $pid);
  } 
  elsif ($pid == 0) {
   my $slp = 5 * $_;
   print "$_ : Im going to execute my code (Im a child) and Im going to wait like $slp seconds\n";
   sleep $slp;
   print "$_ : I finished my sleep\n";
   exit(0);
  } 
  else {
   die "couldn’t fork: $!\n";
  } 
 }

 foreach (@childs) {
  print "Im waiting for: $_\n";
  my $ret = waitpid(-1, WNOHANG);
  #waitpid($_, 0);
  print "Ive just finish waiting for: $_; the return: $ret \n";
 }
}

Thanks in advance, bye!


If you use WNOHANG, the process will not block if no children have terminated. That's the point of WNOHANG; it ensures that waitpid() will return quickly. In your case, it looks like you want to just use wait() instead of waitpid().


I find that POE handles all of this stuff for me quite nicely. It's asynchronous (non-blocking) control of all sorts of things, including external processes. You don't have to deal with all the low level stuff because POE does it for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜