packetie
packetie

Reputation: 5069

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;

Upvotes: 1

Views: 822

Answers (1)

user2404501
user2404501

Reputation:

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';

Upvotes: 7

Related Questions