免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2150 | 回复: 3

$SIG{CHLD}, 怎么子进程退出时监听进程也退出了? [复制链接]

论坛徽章:
0
发表于 2006-10-18 15:28 |显示全部楼层
代码来自《perl高级编程〉

$SIG{CHLD} = sub {
        my $pid;
        do {  
                $pid = waitpid(-1, WNOHANG);
                print "Child Process $pid exit!\n";
        } until $pid == -1;
};

######MAIN#######

# open a socket to listen on or die with the error message
$server = IO::Socket::INET->new(LocalPort => $lport,
                                type => SOCK_STREAM,
                                Reuse => 1,
                                Listen => SOMAXCONN) || dielog("Couldn't bind to $lport: $!\n";

# begin accepting connections
print "Ready to serve requests, listening on port $lport ...\n";
while ($client = $server->accept) {

        # get the remote IP/port for logging
        ($rip, $rport) = ($client->peerhost, $client->peerport);

        # fork a child to handle the request
        if ($child = fork) {

                # close the parent's client connection
                close($client);

                # parent process logs to STROUT
                print "Serving $riprport with child $child.\n";
        }else{

                # warning if the fork was unsuccessful
                if (! defined $child) {
                        print "ERROR: Couldn't fork a process: $!\n";
                }else{

                        #close the child's listen port
                        close($server);

                        my $line;

                        print $client "EnterCommand:";

                        # get the request
                        do {
                                $line = <$client>;
                                sleep 1;
                                print $client "Echoline";
                                print $client "EnterCommand:";
                        }until (! defined $line || $line =~ /^\r\n$/);
                }

                close($client);

                exit 0;
        }
}

close($server);

dielog("byebye\n";

问题是:客户端telnet连上服务器后,只要客户端退出。主进程也byebye了。
测试好像客户端退出时,$SIG{CHLD}被调用。waitpid调用两次:一次返回推出的子进程ID,
第二次返回-1, 退出do-until循环时,主进程也退出了。

论坛徽章:
0
发表于 2006-10-18 17:17 |显示全部楼层
谢谢各位老大,搞定了!!

论坛徽章:
0
发表于 2006-10-18 17:24 |显示全部楼层
原帖由 liaozanxu 于 2006-10-18 17:17 发表
谢谢各位老大,搞定了!!


搞定了也把结果和解决方法帖出来啊

论坛徽章:
0
发表于 2006-10-18 19:19 |显示全部楼层
9494
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP