[Tutor] Using Select

Sean 'Shaleh' Perry shalehperry@attbi.com
Tue, 26 Mar 2002 13:23:13 -0800 (PST)


> 
> I don't know of a walkthrough other than the manpage and "Linux
> Programming Unleashed".  (the book isn't in-depth at all, though)
> 
> I just learned how to use select myself :-).  Basically you make a
> list of files that you want to read from or write to.  Then you hand
> it to select and wait for it to give you back a list of the files that
> are ready to be read from or written to.  Kinda like this, but I only
> had one file to read from :
> 
>     f = open( "/dev/ttyS0" , "r" )
>     r , _ , e = select.select( [f] , [] , [f] )
>     if r :
>         # the file is ready for reading
>         print os.read( r , 1 ) # you may need to call r.fileno() here
>     if e :
>         # an exceptional condition occurred,
>         # I'm really not sure what that means because neither manpage
>         # nor the book explained what exceptional conditions are.
>         pass
> 

another use of select is "timeout after waiting N amount of time".  X Window
applications often use this for their event loop.  We wait on a file descriptor
the X server gives us.  But say this is a clock.  If we wait for events the
clock never updates.

// C++ code
select(xfd + 1, &rfds, 0, 0, timeout);

when select returns either the file descriptor has data or the timeout occured.
 This way we can update the clock face every second as well as handle the X
events.  All in one nice clean loop.

As I mentioned in my post, W. Richard Stevens books are THE source of knowledge
on networking and daemons.  He is clear, thorough and precise.  Yes it is C
code.  But what he says applies to most any other language.  His book "Advanced
Programming in the UNIX environment" is still very much alive and valid as
well.  If you write UNIX code, you should read the book.  I know colleges which
use it for their textbooks.  I often see new linux/bsd coders fighting with
things that are very clearly explained in one of these two books.