【发布时间】:2011-09-08 13:50:20
【问题描述】:
我正在使用 IO::Select 来跟踪可变数量的文件句柄以供读取。我遇到的文档强烈建议不要将 select 语句与 (readline)结合起来从文件句柄中读取。
我的情况:
I will only ever use each file handle once, i.e. when the select offers me the file handle, it will be completely used and then removed from the select.我将收到一个散列和可变数量的文件。我不介意这是否会阻塞一段时间。
关于更多上下文,我是发送信息以由我的服务器处理的客户端。每个文件句柄都是我正在与之交谈的不同服务器。服务器完成后,每个服务器都会将哈希结果发回给我。在该散列中是一个数字,指示要遵循的文件数。
我希望使用 readline 与现有项目代码集成以传输 Perl 对象和文件。
示例代码:
my $read_set = IO::Select()->new;
my $count = @agents_to_run; #array comes as an argument
for $agent ( @agents_to_run ) {
( $sock, my $peerhost, my $peerport )
= server($config_settings{ $agent }->
{ 'Host' },$config_settings{ $agent }->{ 'Port' };
$read_set->add( $sock );
}
while ( $count > 0) {
my @rh_set = IO::Select->can_read();
for my $rh ( @{ $rh_set } ) {
my %results = <$rh>;
my $num_files = $results{'numFiles'};
my @files = ();
for (my i; i < $num_files; i++) {
$files[i]=<$rh>;
}
#process results, close fh, decrement count, etc
}
}
【问题讨论】:
-
你有一些示例代码来展示你做了什么吗?
-
添加了我正在尝试做的示例。
-
{ my $oldfh = select $rh; $| = 1; select $oldfh; }对读取句柄毫无用处。这是一件好事,因为如果 Perl 在每次读取后都按照您的意愿清空缓冲区,您就会丢失数据!