我有一个任务在等待一个线程中的连接并将其转发到另一个线程。也许我有些误解,但为什么我不能在主线程中重新打开文件描述符?
非常简化的代码:
sub inthread {
$socket = new IO::Socket::INET ( ... );
# ...
while ( my $client = $socket->accept() ) {
#if i print STDOUT, (fileno $client); # there i'll get 4
push ( @shared, fileno $client);
}
}
sub mainthread {
if ( scalar @shared ) {
$fd = shift @shared;
# if i print (fileno $fd); # there i'll get 4
open my $f, "<&=$fd" or die " error $!"; ### error here: Can't open 4: Bad file descriptor
while ( <$f> ) { ... }
}
}
threads->create(\&inthread);
while(1) { mainthread; }
完整的代码在那里http://dpaste.com/3381RKV
测试:
perl -w ./testcode.pl --port = 10102& wget -O-http://127.0.0.1:10102/
my $client
创建一个范围为循环主体的变量。在传递的最后,放弃了对所包含句柄的最后一个引用,从而释放了文件句柄,从而关闭了关联的文件描述符。[1]
这是在另一个线程到达之前发生的open <&=
,因此当您尝试为其创建新的文件句柄时,文件描述符不再有效。
独立演示:
#!/usr/bin/perl
use strict;
use warnings;
my $fd;
{
open(my $fh, '<', $0)
or die($!);
$fd = fileno($fh);
} # File handle closed here.
{
open(my $fh, '<&=', $fd)
or die($!); # Bad file descriptor
}
您必须确保不会过早关闭文件句柄。您可以将它们存储在以fd键控的数组或哈希中,另一个线程可以通过另一个共享结构让父线程知道不再需要它的处理程序。
close $client;
。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句