简体   繁体   中英

How can I block waiting for either a read or write socket using IO::Select?

I'm using IO::Select .

It is an OOP wrapper for the normal select call , but it exposes can_read() and can_write() methods. Is there no way to block waiting for a read or write socket? Does this not (almost) defeat the purpose of having IO::Select in the first place?

Use IO::Select->select :

select ( READ, WRITE, EXCEPTION [, TIMEOUT ] )

select is a static method, that is you call it with the package name like new . READ , WRITE and EXCEPTION are either undef or IO::Select objects. TIMEOUT is optional and has the same effect as for the core select call.

The result will be an array of 3 elements, each a reference to an array which will hold the handles that are ready for reading, writing and have exceptions respectively. Upon error an empty list is returned.

For example:

my $rsel  = IO::Select->new($rfh);
my $wsel  = IO::Select->new($wfh);
my $esel  = IO::Select->new($rfh, $wfh);

my @ready = IO::Select->select($rsel, $wsel, $esel, undef);

If TIMEOUT is not given and any handles are registered then the call will block.

It looks like can_read and can_write will block if you don't pass a timeout. I'd suggest that this is rarely what is desired, though it might be under some circumstances.

Personally, I'd suggest using one of the many event modules (POE, AnyEvent, etc) instead. It's a bit more to get going, but handles more scenarios more cleanly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM