smackdab has asked for the wisdom of the Perl Monks concerning the following question:

Hola Monks!

Just bought Net Prog w/Perl...and wanted to use nonblocking accept...the example (pg407) says that you can set the Socket:: blocking off...and then you can tell which sockets you can accept() (w/o blocking). This is GOOD.

BUT, the call to can_read() (from Select) blocks...so what is the point? (this gets the list of sockets that are ready to accept().

Ultimately, all I want to do is spawn off a few programs and get the data back to my main program...I need nonblocking as it is from Tk, and I need to call it's messageloop() frequently...

I explored Pipes, but ran into other problems...and though sockets would be good...but now stuck...

thanks for any ideas on this problem and if there is a "standard" way of doing this network business...

Replies are listed 'Best First'.
Re: nonblocking io
by pjf (Curate) on Oct 11, 2001 at 12:33 UTC
    IO::Select's can_read method will (by default) block forever until something can be read. If passed an argument, it will only wait as many seconds (possibly fractional) as requested. If you call can_read with an argument of zero, it will return immediately, allowing you to do a non-blocking check to see if you have a readable socket.

    For example:

    use IO::Select; $s = IO::Select->new(); $s->add(\*STDIN); if ($s->can_read(0)) { # Non-blocking check. # Something to read! } else { # Nothing to read. }
    Hope you find this useful.

    Cheers,
    Paul

      Thanks!!!...got it working!!!
Re: nonblocking io
by Anarion (Hermit) on Oct 11, 2001 at 12:05 UTC
    If you want to use non-blocking in sockets, you can use select by yourself, or just use IO::Select.

    There are three solutions:
    - fork
    - multiplex the conections with just one process
    - use threads

    Here's an example of the multiplexion, that i read in advanced perl programing:

    use IO::Socket; use IO::Select; my $server = IO::Socket::INET->new ... my $select = IO::Select->new; my $time = 0.5; # How time it waits to check for a new conection $select->add($server); while(1) { my ($sockets_ready) = IO::Select->select($select, undef, undef, $time); foreach my $sock (@$sockets_ready) { if ($sock == $server) { # Accept a new conection my $new_sock = $sock->accept(); $select->add($new_sock); } else { # Its an old conection .... } }


    I dont test the code, hope it works.
    $anarion=\$anarion;

    s==q^QBY_^=,$_^=$[x7,print

Re: nonblocking io
by converter (Priest) on Oct 11, 2001 at 12:07 UTC

    Just a thought: try giving &IO::Select::can_read a timeout value. This should keep it from blocking. I'm not sure what the consequences would be if timeout occurs (I'm working my way slowly through NPwP myself), but it would be fun testing it.

Re: nonblocking io
by Fletch (Bishop) on Oct 11, 2001 at 19:17 UTC

    ObPOEPlug: POE may be worth looking into. POE makes non-blocking network programming a snap.