這作業正常:
#!/usr/bin/perl -w
#
#pipe2 - use pipe and fork so child can send to parent
use IO::Handle;
pipe(READER, WRITER);
WRITER->autoflush(1);
if ($pid = fork) {
close WRITER;
chomp($line = <READER>);
print "Parent Pid $$ just read this: `$line'\n";
close READER;
waitpid($pid,0);
} else {
die "cannot fork: $!" unless defined $pid;
close READER;
print WRITER "Child Pid $$ is sending this\n";
close WRITER; # this will happen anyway
exit;
}
但是當我試圖讓讀者不要像這樣被 fcntl 阻塞時:
use IO::Handle;
use Fcntl;
pipe(READER, WRITER);
WRITER->autoflush(1);
if ($pid = fork) {
close WRITER;
fcntl(fileno(READER),F_GETFL,$flags)
or die "Couldn't get flags for READER : $!\n";
$flags |= O_NONBLOCK;
fcntl(fileno(READER), F_SETFL, $flags)
or die "Couldn't set flags for READER $!\n";
chomp($line = <READER>);
print "Parent Pid $$ just read this: `$line'\n";
close READER;
waitpid($pid,0);
} else {
die "cannot fork: $!" unless defined $pid;
close READER;
print WRITER "Child Pid $$ is sending this\n";
close WRITER; # this will happen anyway
exit;
}
我得到:
fcntl() on unopened filehandle 3 at pip2.pl line 14.
Couldn't get flags for READER : Bad file descriptor
如果孩子在特定時間內沒有正確回應,我需要“觀察”孩子并做一些事情。我需要與孩子進行異步通信。
uj5u.com熱心網友回復:
fcntl(fileno(READER),F_GETFL,$flags)
fcntl獲取檔案句柄,而不是檔案編號。fcntl(READER,...不使用fcntl(fileno(READER), ...。
除此之外,建議不要對檔案句柄使用全域符號。更好地使用區域變數,即
pipe(my $reader, my $writer);
$writer->autoflush();
...
除了不會與其他全域符號發生潛在沖突并避免未捕獲拼寫錯誤的風險外,這還將關閉變數超出范圍的相應檔案句柄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425555.html
上一篇:Perl5.32定義陳述句語法
