Yesterday I wrote a multi-threads perl script, codes below is it.
#!perl use IO::Socket::INET; use threads; $server = IO::Socket::INET->new( LocalPort => 90, Type => SOCK_STREAM, Reus => 1, Listen => 10) or die "Server Failed.\n"; $thread_A = threads->new(\&server); $thread_B = threads->new(\&server); $thread_C = threads->new(\&server); @result = ($thread_A->join, $thread_B->join, $thread_C->join); print "All threads returned, with codes @result\n"; sub server { while ($client=$server->accept) { for ($second=60; $second>0; --$second) { sleep 1; print $client "$second\n"; } close $client; } print "Thread: loop while(\$client=\$server->accept) was broke +n with reason \"unknown\", going to return.\n"; return 1; }
Codes below is the client:
#!perl use IO::Socket::INET; $server = IO::Socket::INET->new("127.0.0.1:90"); while (<$server>) { print; } close $server;
It's a multi-threads server test, while I run it on my windows with active-perl 5.10.1, I make 3 clients connected to it, and it was working fine, just like what these codes means literally, but on my linux with perl 5.10.0, it's odd, while I interrupted one client with CTRL+C, the server process(I mean whole process with every thread) was quit with neither warning nor error.
This problem was SOLVED with handling $SIG{PIPE} like almut said. Server codes has changed to:
#!perl use IO::Socket::INET; use threads; $SIG{PIPE} = 'IGNORE"; $server = IO::Socket::INET->new( LocalPort => 90, Type => SOCK_STREAM, Reus => 1, Listen => 10) or die "Server Failed.\n"; $thread_A = threads->new(\&server); $thread_B = threads->new(\&server); $thread_C = threads->new(\&server); @result = ($thread_A->join, $thread_B->join, $thread_C->join); print "All threads returned, with codes @result\n"; sub server { while ($client=$server->accept) { for ($second=60; $second; --$second) { sleep 1; print $client "$second\n" or last; } close $client; } print "Thread: loop while(\$client=\$server->accept) was broke +n with reason \"unknown\", going to return.\n"; return 1; }
While we attempt to write things to read-side through socket, if the socket of read-side already closed, the write-side would got a signal SIGPIPE, that causes write-side killed by SIGPIPE.
strace is cool.
In reply to SOLVED: Is this a bug of perl threads? by Ray.Zachary
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |