我在 Windows 下使用 Perl 创建了一个服务器(ActivePerl 5.10.1 build 1006),该服务器在连接时进行 fork ,接受一些 JSON 数据,并将其写入数据库。在 64 个客户端连接到服务器后,我遇到了问题,尝试 fork 时出现错误消息“资源不可用”。
在 Linux 下运行此代码时,我发现许多已失效的子进程,这是通过在父进程上添加 wait()
调用来解决的。然而这并没有解决问题。在 Linux 下运行代码可以超过 Windows 中允许的 64 次调用。
我还启动了一个虚拟 Windows 服务器,以防服务器受到限制,但全新安装的 Perl 导致同样的 64 个连接限制。
任何想法都会受到赞赏。
use IO::Socket;
use Net::hostent;
use JSON;
use DBI;
use Data::Dumper;
my $port=shift || 9000;
my $clients_served = 0;
while(1){
my $server = IO::Socket::INET->new( Proto => 'tcp',
LocalPort => $port,
Listen => 1,
Reuse => 1);
die "can't setup server" unless $server;
print "[Server $0 is running]\n";
####
# wait for a client to connect
# once it has, fork to a seperate thread and
# retrieve the JSON data
####
while (my $client = $server->accept()) {
my $pid = fork();
if ($pid != 0) {
print ("Serving client " . $clients_served++ . "\n");
}else{
$client->autoflush(1);
my $JSONObject = JSON->new->ascii->pretty->allow_nonref();
my $hostinfo = gethostbyaddr($client->peeraddr);
my $client_hostname = ($hostinfo->name || $client->peerhost);
printf "connect from %s\n", $client_hostname;
print " $client_hostname connected..\n";
syswrite($client, "Reached Server\n", 2048);
if (sysread($client, my $buffer, 2048) > 0) {
foreach my $tasks($JSONObject->decode($buffer)){
foreach my $task (@$tasks){
insert_record($client_hostname, $task); #empty method, contents does not affect result
}
}
}
print " $client_hostname disconnected..\n";
close $client;
exit 0;
}
}
$server->close();
}
exit 0;
最佳答案
尝试从已完成的事务中获取僵尸进程。我可以让你的示例代码 如果我再添加几行,请继续运行:
use POSIX ':sys_wait_h';
if ($pid != 0) {
print ("Serving client " . $clients_served++ . "\n");
1 while waitpid -1, WNOHANG > 0;
如果您可能有 64 个同时 连接,您可能必须考虑其他措施 - 在 Windows 上安装 SIGCHLD
处理程序并不好。
关于windows - 为什么 Windows 上的 Perl IO::Socket 在 64 个连接后会提示 "Resource Not Available"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2284409/