perlprocessforkpidsigchld

perl, no child process w/ "open"


Hi I have this problem where the perl script spits back "No child process found at" ...

My script calls several different types of forks, so I tried implementing the perldoc's waitpid() implementation method to be able to use handle both fork & exec & system & qw.

 $SIG{CHLD} = sub {
    # don't change $! and $? outside handler
    local ($!, $?);
    my $pid = waitpid(-1, WNOHANG) > 0;
    return if $pid == -1;
    return unless defined $children{$pid};
    delete $children{$pid};
};

    my $pid = fork();
    die "cannot fork" unless defined $pid;
    if ($pid == 0) {
        # ...
        exit 0;
    } else {
        $children{$pid}=1;
        # ...
        exec($command);
   }

There is no problem with this part of the execution of the code, however the "No child processor found" occurs when I try to close the filehandle's CLOSE. Can someone explain to me how come this is happening, as I really want to understand this problem more in depth. Do I end up reaping the child process forked by the OPEN call, so that the close doesn't know how to handle the file handle? or maybe I'm 100% off. Any solutions would be appreciated

open(RESULTS, "-|", "find $dir\/ -maxdepth 1 -name RESULTS -print0 | xargs -0 cat ") or die $!;
while(<RESULTS>){
if($_ =~ /match/){
    print $_;
 }
  }
 close RESULTS;

Solution

  • close on a handle* opened thusly calls waitpid to reap the child created by open. However, your signal handler managed to reap the child before close did, so close could not find the child, so close returned an error.

    You could fix this by changing your signal handler to only reap the children you've created using fork (below), or you could ignore that error from close.

    $SIG{CHLD} = sub {
       local ($!, $?, $^E);
       for my $pid (keys(%children)) {
          if (waitpid($pid, WNOHANG) > 0) {
             delete $children{$pid};
          }
       }
    };
    

    * — The proper term is "file handle". It is named such since it allows you to hold onto a file. It's not handler as it performs no action.