views:

798

answers:

3

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?

+3  A: 

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.

Paul Tomblin
A: 

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

William Pursell
open2 (see IPC::Open2) is a call that allows you to send input to and receive output from the same program
mobrule
+3  A: 

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.

Paulius Liekis
Or you could just call waitpid($pid, 0) and it will wait until the program has exited.
Paul Tomblin
Ah - yes waitpid only reports the result once.
Douglas Leeder
Paul: yes that would work, but I can't block on that, because I need to read log files while the process is running.
Paulius Liekis