English 中文(简体)
Why would waitpid in Perl return wrong exit code?
原标题:

I get wrong exit code from waitpid and I can t figure out why. Could someone give me some ideas?

Here what I do:

  1. I start my child process with open2
  2. then I wait for it to finish with waitpid
  3. get exit code using $?

It always returns with -1 no mater what I return from child process. I check with VS debugger that my program returns an exit code of 0. VS says something like this:

The program  [3256] Test.exe: Native  has exited with code 0 (0x0).

I made sure that pids match.

Any ideas?

最佳回答

I just figured it out. waitpid has 3 stages:

 1. process is running:    waitpid returns 0;   $? is -1
 2. process is exiting:    waitpid returns pid; $? is actual exit code
 3. process doesn t exist: waitpid returns -1;  $? is -1

so when doing something like while(waitpid($pid, WNOHANG) >= 0) exit code must be retrieved once cycle before that.

问题回答

From the waitpid man page:

Note that on some systems, a return value of "-1" could mean that child processes are being automatically reaped. See perlipc for details, and for other examples.

Rather than using waitpid, you should just close the filehandle. (I assume the "open2" in your question is a typo, and you meant "open")

Works for me (Windows):

use IPC::Open3;
use POSIX  :sys_wait_h ;
use Time::HiRes;

$|++;

my ($fin, $fh, $pid);
$pid = open3($fin, $fh, 0,  ping ,  8.8.8.8 ) or die( error );

my @lines = ();
while (1) {
    while (my $line = <$fh>) {
        push(@lines, $line);
        print( + );
    }
    print("
ret: `$?`
"), last if waitpid($pid, WNOHANG) <= 0;
    Time::HiRes::usleep(100000);
    $fh->clearerr();
}
waitpid($pid, 0);
print("
ret: `$?`
");

Will output:

++++++++++++
ret: `-1`

ret: `0`




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签