首页 文章

在Perl中进行多处理任务时出现问题

提问于
浏览
1

我知道正确的方法将这个程序作为一个非阻塞进程,因为当我等待一个孩子的响应(使用 waitpid )时,其他进程也必须在队列中等待,但是,如果一些儿童过程在此之前死亡(我的意思是,这些过程在无序中死亡)?所以,我一直在寻找,我发现我可以获得刚刚死亡的过程的PID,因为我使用 waitpid(-1, WNOHANG) . 我总是得到一个警告 WNOHANG 不是一个数字,但是当我添加了lib sys_wait_h时,我没有得到那个错误但是脚本永远不会等待PID,可能是什么错误?

#!/usr/bin/perl
#use POSIX ":sys_wait_h"; #if I use this library, I dont get the error, but 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";
 }
}

在此先感谢,再见!

2 回答

  • 3

    如果您使用WNOHANG,如果没有孩子终止,该过程将不会阻止 . 这就是WNOHANG的观点;它确保waitpid()将快速返回 . 在您的情况下,看起来您只想使用wait()而不是waitpid() .

  • 0

    我发现POE很适合我处理所有这些东西 . 它必须处理所有低级别的东西,因为POE为你做了 .

相关问题