Adding file handles to the main select() loop

The KSirc Handbook
Prev | Chapter 5. Programming Your Sirc Client | Next

# 5.6. Adding file handles to the main select() loop

As of sirc 2.2, scripts can add file handles to the main loop, and set hooks on them to get control when data is available.

It is up to the script to first open the file handle, which can refer to a network connection, a tty, a pipe (as in `open(FH, "program |")`), etc.

When dealing with network sockets, it is strongly suggested to use the API provided by sirc (`&connect, &listen, &accept, &resolve, &newfh` and `$bindaddr`) rather than using the raw perl functions. This will have the effect of making these scripts work transparently over socks proxies, when the socks module is loaded. If you need some extra functionality, though (such as UDP sockets, or accepting multiple connections from the same listening socket), you can use perl's own functions.

To get control back when data is available over a filehandle, you add it to the set of fh's sirc `select()s` from, with

`&addsel($fh, "somename", flag);` where sel_somename is the sub that will get control back when there is something to read, and flag is 1 if you want sirc to buffer the connection and break it into lines for you, and 0 if you don't want sirc to touch the data at all.

The convention for `sel_somename` subs is different in the two cases:

- for buffered filehandles, it is passed a single argument containing a line that was read, including the final `\n`. if the connection is closed or broken, this argument is `''` and the filehandle has been already closed and removed from the set of fh's to `select()` on. if you close it yourself, you must use `&remsel` to tell sirc to remove it from the set.

- for unbuffered filehandles, no arguments are passed; the hook is called when `select()` indicates that the fh is ready for reading, and it is up to the hook to read from it (making sure not to block, so sysread should be used and not <>), and eventually close it and remove it with `&remsel`.

To remove a filehandle from the set of fh's being `select()ed` on, call `&remsel($fh);` where `$fh` is the filehandle.

Note that sirc never does any checking that a filehandle you give it is valid. Having a closed or invalid `fh` in the set of `select()able` ones, or not actually reading the data on an unbuffered `sel_* hook`, will cause sirc to hog the CPU by not blocking in `select()`.

For an example of a nontrivial use of all of this, see the script ftp.pl which implements an ftp client inside sirc (it can be found at the sirc webpage at http://www.eleves.ens.fr:8080/home/espel/sirc/sirc.html).

Prev | Home | Next
Timers | Up | Bots