【Perl】【IO::Socket】fork 之后 socket 连接不正常,望高人解答。
我用 perlipc 中的两个例子程序:Interactive Client with IO::Socket 和 TCP Servers with IO::Socket 来进行 Socket 编程,自己做了部分修改,但是连接不通。如果我把 client 改成单线程发送,则服务端可以收到信息。请问是怎么回事?我的系统 WinXP + ActivePerl 5.8。是不是 fork 的某些问题?
另外:无论输入什么,Server side 都没有正确匹配。是正则表达式写错了?那可是示例代码呵。。。
代码如下(只有修改的部分。未修改的部分见 perlipc 文档。)
#Client Side:
# split the program into two processes, identical twins
die "can't fork: $!" unless defined($kidpid = fork());
# the if{} block runs only in the parent process
if ($kidpid) {
print STDOUT "Chile process started now.\n";
# copy the socket to standard output
while (defined ($line = <$handle>)) {
print STDOUT $line;
}
print STDOUT "Chile process died now.\n";
kill("TERM", $kidpid); # send SIGTERM to child
}
# the else{} block runs only in the child process
else {
SendCommand(\$handle);
}
# 不通过 fork,单独调用 SendCommand 可以发送成功
sub SendCommand (\$sock_handle)
{
print STDOUT "Main process started now.\n";
# copy standard input to the socket
while (defined ($line = <STDIN>)) {
print STDOUT "Writing to socket: $line";
print $handle $line;
}
print STDOUT "Main process died now.\n";
}
#Server Side
while (<$client>) {
print "Got Msg $_"; # 加上这个,收到的时候可以直接打印
chomp $_;
next unless /\S/; # blank line
if (/\s/) { print "Space"; next;}
# ... 下同。
} continue {
print $client "Command? ";
}
close $client;