Home > Articles > Programming > C/C++

  • Print
  • + Share This
From the author of Event Loops

Event Loops

The core of most graphical programs is an event loop. In a UNIX program, there is generally only one source of events: file descriptors. Everything, including network connections and the controlling terminal, is driven by a file-like interface. Somewhere near the top level, a graphical program typically has a while loop using either the BSD select() function or the SysV poll() function (or sometimes kevent() on newer BSD systems) to wait for data to be available on any of a set of file descriptors. When one is ready, the loop invokes an associated callback function to handle the new data.

Both Xlib and XCB make it possible to get the file descriptor that they use for communicating with the server and integrate this with a foreign event loop. Graphical applications are usually programmed in an event-driven style, where events are either some form of I/O or timers. At the core of the program is usually something like a while loop that calls select() (or equivalent) with a timeout value set to the next timer event. This then calls an event handler for the file descriptor with available data or a callback for the timer.

Most of the time, developers don't need to worry about this level of detail; it's hidden by the toolkit. This is especially true of events from the X server. An application developer wants to know something like “the user clicked in this view” or “the user typed into this view” rather than seeing the low-level message details.

  • + Share This
  • 🔖 Save To Your Account