使用简单的 Perl 脚本重置连接 [英] Connection resets with simple Perl script

查看:42
本文介绍了使用简单的 Perl 脚本重置连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个 Perl 脚本,其唯一目的是接收 HTTP 请求,并吐出503 Service Unavailable"和一条短消息.它工作正常,但在许多情况下,连接会重置,这会导致浏览器显示错误消息.这是在 Win32 上.我不知道它有什么问题.

Below is a Perl script whose sole purpose is to receive an HTTP request, and spit out "503 Service Unavailable" and a short message. It works fine, except in many cases, the connection resets, which causes the browser to show an error message. This is on Win32. I have no idea what's wrong with it.

#!/usr/local/bin/perl

use strict;
use IO::Socket::INET;
my $f = join('', <DATA>);

$SIG{CHLD} = 'IGNORE';
my $sock = IO::Socket::INET->new(ReuseAddr => 1, Listen => 512, LocalPort => 80, LocalHost => '0.0.0.0', Proto => 'tcp');
die "Cant't create a listening socket: $@" unless $sock;

while (my $connection = $sock->accept) {
    my $child;
    die "Can't fork: $!" unless defined ($child = fork());
    if ($child == 0) {
        #print "Child $$ running. ";
        $sock->close;
        do_it($connection);
        #print "Child $$ exiting.\n";
        exit 0;
    } else {
        print "Connection from ".$connection->peerhost."\n";
        $connection->close();
    }
}

sub do_it {
    my $socket = shift;
    my $pr = print $socket $f;
    if (!$pr) {
        $socket->close();
        exit(0);
    }
}

__DATA__
HTTP/1.1 503 Service Unavailable
Date: Mon, 12 Mar 2009 19:12:16 GMT
Server: Down
Connection: close
Content-Type: text/html


<html>
<head><title>Down for Maintenance</title></head>
<body>
<h2>Down for Maintenance</h2>
<p>The site is down for maintenance. It will be online again shortly.</p>
</body>
</html>

推荐答案

Win32 上的 fork 不是被称为 broken 吗?

Isn't fork on Win32 known as broken?

实际上,由于您的子进程正在做与您的父部分完全不同的事情,因此您最好使用 线程.

Really since your child process is doing something totally different from your parent section, you might be better off with threads.

在评论中回答您的问题时,只需考虑将所有分叉逻辑 (!!) 替换为

In answer to your question in the comments, just think about replacing all your forking logic (!!) with

$peer_name = $connection->peerhost();
threads->create( \&do_it, $connection );
say "Got connection from $peer_name";

(例如,参见 this.)并且不要担心关闭除服务器线程之外的任何其他地方的连接.

( See this for example. ) And don't worry about closing connection anywhere else but the server thread.

这篇关于使用简单的 Perl 脚本重置连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆