开发者

4-Argument-Select-Question

From SELECT_TUT:

"... is used to efficiently monitor multiple file descriptors, to see if any of them is, or becomes, "ready"; that is, to see whether I/O becomes possible, or an "exceptional condition" has occurred on any of the descriptors. ...

So what is the point of select()? Can't I just read and write to my descriptors whenever I want? The point of select() is that it watches multiple descriptors at the same time and properly puts the process to sleep if there is no activity. Unix programmers often find themselves in a position where they have to handle I/O from more than one file descriptor where the data flow may be intermittent. If you were to merely create a sequence of read(2) and write(2) calls, you would find that one of your calls may block waiting for data from/to a file descriptor, while another file descriptor is unused though ready 开发者_如何学编程for I/O. select() efficiently copes with this situation."

Could someone explain me, what this means and how this works, maybe with a little example.

For example here is selected only one file-handle, why would I need a monitoring?

my $timeout = 10;
my ( $in, $out ) = ( '', '' );
vec( $in, fileno( STDIN ), 1 ) = 1;
select( $out = $in, undef, undef, $timeout );


Reading from a filehandle is a blocking operation. If you try to read from STDIN and there is no input your program will wait until there is input. The effect can be illustrated by running a filter program like grep with no input:

$ grep foo
_

grep waits for input. If you type something and press Ctl-d to close STDIN grep's read will fetch your input, check for a match, print the match if there is one and exit.

Now imagine that you're writing a network application like an IRC client that has to read from several different connections while running a GUI main loop. This is the problem select() solves.

Here's an article that should give you a thorough explanation: http://www.perlfect.com/articles/select.shtml

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜