Kernel Korner - Easy I/O with IO Channels

IO Channels, a feature of the Glib library, make portable I/O simple and efficient. In this article, Robert shows how.
Seeking Around an IO Channel

As a file is written to or read from, Glib automatically updates the application's position within the file. When a file is first opened, the position is set to the start. Read four bytes, and the position is subsequently set to the fifth byte. This is the file I/O behavior nearly all developers are familiar with.

Sometimes, however, an application wants to seek around the file on its own. For that, Glib provides a single function:

GIOStatus
g_io_channel_seek_position (GIOChannel *channel,
                            gint64 offset,
                            GSeekType type,
                            GError **error);

A successful call will change the current position in the file as described by offset and type.

The type parameter is one of G_SEEK_CUR, G_SEEK_SET or G_SEEK_END. G_SEEK_CUR asks that the file's position be updated to offset bytes from the current position. G_SEEK_SET asks that the file's position be set to offset. Thus, the following code sets the file position to the start of the file:


GIOStatus ret;
GError err;

ret = g_io_channel_seek_position (gio,
                                  0,
                                  G_SEEK_SET,
                                  &err);
if (ret)
        g_error ("Error seeking: %s\n",
                 err->message);

Finally, G_SEEK_END asks that the file's position be set to offset bytes from the end of the file.

We do not use g_io_channel_seek_position() in our sample application, because even if we had a reason to, pipes are not seekable.

Closing an IO Channel

When done with an IO Channel, it is destroyed and the file is closed via a call to g_io_channel_shutdown:

GIOStatus
g_io_channel_shutdown (GIOChannel *channel,
                       gboolean flush,
                       GError **err);

If flush is TRUE, any pending I/O is first flushed.

Deprecated Functions

Several older IO Channel functions are provided by Glib: g_io_channel_read(), g_io_channel_write() and g_io_channel_seek(). The functions discussed in this article have replaced these older, deprecated functions and should be used instead. Particularly, never mix these old functions with the other functions on the same IO Channel.

Putting It All Together

We have now covered all of the IO Channel interfaces used in Listing 1. Only two details go unexplained. First, in our example program, we create a pipe in the usual manner:

int fd[2], ret;

ret = pipe (fd);
if (ret)
        g_error ("Creating pipe failed: %s\n",
                 strerror (errno));

Second, our main() function initializes the Glib main loop, calls our function to initialize the IO Channels and then runs the main loop:

int
main (void)
{
        GMainLoop *loop;

        loop = g_main_loop_new (NULL, FALSE);
        init_channels ();
        g_main_loop_run (loop);    /* Wheee! */
        return 0;
}

The g_main_loop_new() function creates a new main loop and returns a pointer to a new GMainLoop structure. Once ready to start the main loop running, we call g_main_loop_run() and let Glib handle the rest.

Conclusion

Applications that use IO Channels combine a portable multiplexed I/O solution with smart buffering and Glib main loop integration. The result is a solution that allows applications to juggle I/O among hundreds of file descriptors. A graphical network client can manage all of its open sockets, handle new connections seamlessly, juggle a dozen open files and respond to numerous GUI events from a single place and with a single thread.

Glib's IO Channels make I/O easy, efficient, and—gasp—even fun!

Resources for this article: /article/8632.

Robert Love is a senior kernel hacker in Novell's Ximian Desktop group and the author of Linux Kernel Development (SAMS 2005), now in its second edition. He holds degrees in CS and Mathematics from the University of Florida. Robert lives in Cambridge, Massachusetts.

______________________

White Paper
Fabric-Based Computing Enables Optimized Hyperscale Data Centers

Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.

Learn More

Sponsored by AMD

White Paper
Red Hat White Paper: Using an Open Source Framework to Catch the Bad Guy

Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6

Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.

Learn more about catching the bad guy in this free white paper.

Learn More

Sponsored by DLT Solutions