Re: Help needed with IOChannel example



On Tuesday 16 November 2004 13:50, Murray Cumming wrote:
> I recently updated this example so that it builds. But it doesn't do
> anything, and I'm not very familiar with this part of the API:
> http://cvs.gnome.org/viewcvs/gtkmm/examples/book/input/main.cc?view=markup
>
> I think it's meant to show the use of Glib::signal_input(), which I think
> is a simple way to use IOChannels.
>
> This is the version that was in gtkmm 1.2:
> http://cvs.gnome.org/viewcvs/gtkmm-root/examples/input/input.cc?view=markup
>
> This is the relevant bug:
> http://bugzilla.gnome.org/show_bug.cgi?id=138259

Your use of IOChannels is correct, so the fault is elsewhere.  One problem 
with the code is that the following lines try to open the fifo for reading 
twice:

  // open the fifo
  input = std::auto_ptr<std::ifstream>( new std::ifstream("testfifo") );
  
  int fd = open("testfifo", 0);
  if (fd == -1)
  {
    std::cerr << "error opening fifo" << std::endl;
    return -1;
  }

To avoid the hack with filebuf (which doesn't work anyway with the version of 
libstdc++-3 which comes with gcc-3.4), why not just use the standard Unix 
read()?  The attached file works correctly.

Chris.
#include <gtkmm/main.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>

int read_fd;

/*
  send to the fifo with:
  echo "Hello" > testfifo

  quit the program with:
  echo "Q" > testfifo
*/

// this will be our signal handler for read operations
// it will print out the message sent to the fifo
// and quit the program if the message was, or began
// with, '*'
bool MyCallback(Glib::IOCondition io_condition)
{
  if ((io_condition & Glib::IO_IN) == 0) {
    std::cerr << "Invalid fifo response" << std::endl;
  }
  else {
    char buffer[PIPE_BUF];
    int result;
    while ((result = read(read_fd, buffer, PIPE_BUF)) > 0) {
      if (*buffer == 'Q') Gtk::Main::quit();
      else write(0, buffer, result);
    }
  }
  return true;
}


int main(int argc, char *argv[])
{
  // the usual Gtk::Main object
  Gtk::Main app(argc, argv);

  if (access("testfifo", F_OK) == -1) {
    // fifo doesn't exit - create it
    if (mkfifo("testfifo", 0666) != 0) {
      std::cerr << "error creating fifo" << std::endl;
      return -1;
    }
  }
 
  read_fd = open("testfifo", O_RDONLY | O_NONBLOCK);
  if (read_fd == -1)
  {
    std::cerr << "error opening fifo" << std::endl;
    return -1;
  }

  // connect the signal handler
  Glib::signal_io().connect(sigc::ptr_fun(MyCallback), read_fd, Glib::IO_IN);

  // and last but not least - run the application main loop
  app.run();

  // now remove the temporary fifo
  if(unlink("testfifo"))
    std::cerr << "error removing fifo" << std::endl;

  return 0;
}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]