packetie packetie -4 years ago 175
Perl Question

nonblocking waitpid() in perl

I am trying to do non-blocking waitpid, according to perl man page,

waitpid($pid, WNOHANG);
will do. But the following seems to be blocking. The result of the printf will take 2 seconds to show up.

$pid = fork;
if (!$pid) {
exec("sleep 2");
}
waitpid($pid, WNOHANG);
$retCode = $?;
printf "%04x\n", $retCode;

Answer Source

Mistake number 1: you didn't enable warnings.

Mistake number 2: you didn't declare WNOHANG. So it's a bareword, which becomes the string 'WNOHANG'. The string then becomes 0 with no warning when interpreted as a number, because it doesn't look like a number. So you called waitpid with flags=0, instead of the WNOHANG flag you intended.

use warnings;
use POSIX 'WNOHANG';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download