There are two issues. First, the child process is buffering its output; and second, the parent process is using the <>
operator, which blocks until a complete line is available, or until end-of-file.
So, one way to get the result you were expecting is to have the child process close its output stream immediately after writing:
if ($pid == 0) {
print "$$";
close STDOUT;
sleep 5;
exit;
}
Another way is to add a newline to the child process's output, then flush the stream:
if ($pid == 0) {
print "$$
";
STDOUT->flush; # "close STDOUT;" will work too, of course
sleep 5;
exit;
}
The flush is necessary because pipes are (typically) unbuffered, rather than line-buffered as streams connected to the terminal usually are.
A third alternative is to set the child process's output stream to autoflush:
if ($pid == 0) {
$| = 1;
print "$$
";
sleep 5;
exit;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…