我的 Perl 程序有一个挂起进程的问题,我想我已经将它隔离到每当我向管道写入大量数据时。
以下是我认为与我的程序相关的所有代码。当程序挂起时,挂在ResponseConstructor.pm中的线路上:print { $self->{writer} } $data;
.
我已经用不同的数据大小进行了测试,并且它似乎没有以精确的大小挂起。不过,随着大小的增加,这种情况可能会变得更可能:32KB 左右的大小有时有效,有时无效。每次我尝试使用 110KB 的字符串时都会失败。
我相信我也排除了contents数据的原因,因为相同的数据有时会导致挂起,有时则不会。
这可能是我第一次在程序中使用管道,所以我不确定接下来要尝试什么。有任何想法吗?
use POSIX ":sys_wait_h";
STDOUT->autoflush(1);
pipe(my $pipe_reader, my $pipe_writer);
$pipe_writer->autoflush(1);
my $pid = fork;
if ($pid) {
#I am the parent
close $pipe_writer;
while (waitpid(-1, WNOHANG) <= 0){
#do some stuff while waiting for child to send data on pipe
}
#process the data it got
open(my $fh, '>', "myoutfile.txt");
while ( my $line = <$pipe_reader>){
print $fh $line;
}
close $pipe_reader;
close $fh;
else {
#I am the child
die "cannot fork: $!" unless defined $pid;
close $pipe_reader;
my $response = ResponseConstructor->new($pipe_writer);
if ([a condition where we want to return small data]){
$response->respond('small data');
exit;
}
elsif ([a condition where we want to return big data]){
$response->respond('imagine this is a really big string');
}
}
响应构造函数.pm:
package ResponseConstructor;
use strict;
use warnings;
sub new {
my $class = shift;
my $writer = shift;
my $self = {
writer => $writer
};
bless($self, $class);
return($self);
}
#Writes the response then closes the writer (pipe)
sub respond {
my $self = shift;
my $data = shift;
print { $self->{writer} } $data;
close $self->{writer};
}
1;