recv blocking on Perl even though socket is non bl

2020-07-18 06:09发布

问题:

I have created a socket like this in perl in a daemon

IO::Socket::INET->new(LocalPort => $port,
                      Proto => 'udp',Blocking => '0') or die "socket: $@"; 

on a Linux machine

The socket behaves like non blocking socket as expected during a recv call as expected $sock->recv($message, 128);.

However, I am consistently observing that when the VIFs on eth0 are reconfigured while the daemon is running and receiving data, then the recv call starts blocking.

This is a very perplexing issue. I did $sock->recv($message, 128, MSG_DONTWAIT); and the recv call becomes non blocking.

I have googled but could not see what is the suggested way for using UDP non blocking sockets.

回答1:

First, the literal answer:

# Portable turn-off-blocking code, stolen from POE::Wheel::SocketFactory.
sub _stop_blocking {
    my $socket_handle = shift;

    # Do it the Win32 way.
    if ($^O eq 'MSWin32') {
        my $set_it = "1";
        # 126 is FIONBIO (some docs say 0x7F << 16)
        # (0x5421 on my Linux 2.4.25 ?!)
        ioctl($socket_handle,0x80000000 | (4 << 16) | (ord('f') << 8) | 126,$set_it) or die "can't ioctl(): $!\n";
    }

    # Do it the way everyone else does.
    else {
        my $flags = fcntl($socket_handle, F_GETFL, 0) or die "can't getfl(): $!\n";
        $flags = fcntl($socket_handle, F_SETFL, $flags | O_NONBLOCK) or die "can't setfl(): $!\n";
    }
}

However, I strongly suggest you to use AnyEvent::Handle!



标签: perl sockets