Monitoring I/O

A nifty feature of Glib (one of the libraries underlying gtkmm) is the ability to have it check for data on a file descriptor for you. This is especially useful for networking applications. The following method is used to do this:

sigc::connection Glib::SignalIO::connect(const sigc::slot<bool(Glib::IOCondition)>& slot,
                                 Glib::PollFD::fd_t fd, Glib::IOCondition condition,
                                 int priority = Glib::PRIORITY_DEFAULT);

The first argument is a slot you wish to have called when the specified event (see argument 3) occurs on the file descriptor you specify using argument two. Argument three may be one or more (using |) of:

  • Glib::IOCondition::IO_IN - Call your method when there is data ready for reading on your file descriptor.

  • Glib::IOCondition::IO_OUT - Call your method when the file descriptor is ready for writing.

  • Glib::IOCondition::IO_PRI - Call your method when the file descriptor has urgent data to be read.

  • Glib::IOCondition::IO_ERR - Call your method when an error has occurred on the file descriptor.

  • Glib::IOCondition::IO_HUP - Call your method when hung up (the connection has been broken usually for pipes and sockets).

The return value is a sigc::connection that may be used to stop monitoring this file descriptor using its disconnect() method. The slot signal handler should be declared as follows:

bool input_callback(Glib::IOCondition condition);

where condition is as specified above. As usual the slot is created with sigc::mem_fun() (for a member method of an object), or sigc::ptr_fun() (for a function). A lambda expression can be used, if you don't need the automatic disconnection that sigc::mem_fun() provides when the object goes out of scope.

A little example follows. To use the example just execute it from a terminal; it doesn't create a window. It will create a pipe named testfifo in the current directory. Then start another shell and execute echo "Hello" > testfifo. The example will print each line you enter until you execute echo "Q" > testfifo.

Källkod