Home
  Software
    HowTo
      GTK+
        IOChannel

Language:
  Espaņol

On this page
  GUI
  Client code
  Server code
  Thanks

Temas
  GIOChannel
  FIFO chat
  Socket chat

GTK+ - GIOChannel

The GIOChannel tries to provide a portable method to manage the different communication channels: pipes, file descriptors, and sockets. Also, it integrates into the program main loop. At this time, only the Linux implementation is complete. Some functions are still missing from the Windows version.

To create a new GIOChannel, the function g_io_channel_unix_new() is used. It connects a new channel to an already existing file. This works for the three file types mentioned. Alternatively, it is possible to create a complete new file, in a system-independent way, using g_io_channel_new_file(). In the example a serial port is opened, then a channel is assigned.
GIOChannel *ioch;

fd = open(port, O_RDWR | O_NONBLOCK | O_NOCTTY);
if (fd == -1)
  <error message and exit>
  ...
ioch = g_io_channel_unix_new(fd);
Once the channel has been created, we can read ( g_io_channel_read_chars()), write ( g_io_channel_write_chars()), change position ( g_io_channel_seek_position()), and close it ( g_io_channel_close()).
g_io_channel_write_chars(ioch, &cmd, 1, &written, &error);
g_io_channel_flush(ioch, NULL);
    
To avoid having to poll the channel continuously, we can attach a watch function which will be called when the specified event occurs (using g_io_add_watch() or g_io_add_watch_full()).
int     iowatch = -1;

iowatch = g_io_add_watch(ioch, G_IO_IN, io_callback, NULL);
    
In this case it is necessary to write a function that will be called when if the event actually occurs (in this case, io_callback will be called whenever the event 'G_IO_IN' occurs, i.e. when characters come in through the channel.
gboolean
io_callback(GIOChannel *ioch, GIOCondition cond, gpointer data)
{
  int bytes_read;
  unsigned char chr;
  
  do {
    g_io_channel_read_chars(ioch, &chr, 1, &bytes_read, NULL);
    if (bytes_read) {
      process_char(chr);
      if (pref.diag_comm) printf("%02x\n", chr);
    }                                           
  } while (bytes_read);
  return TRUE;
}

Example code

The complete code for this example is here. But note that this is not a complete program - you'll still have to add a main program and some more code to do something with the data! This is not a C tutorial.

10763


(c) John Coppens ON6JC/LW3HAZ mail