summaryrefslogtreecommitdiff
path: root/examples/iochannel_stream/main.cc
blob: 45a7721cbd4f6efc88c31a87e2191c47d580b074 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* Copyright (C) 2004 The glibmm Development Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <fcntl.h>
#include <glibmm.h>
#include <iostream>
#include <limits.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "fdstream.h"

fdstream input_stream;
Glib::RefPtr<Glib::MainLoop> mainloop;

/*
  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, 'Q'
bool
MyCallback(Glib::IOCondition io_condition)
{
  if ((io_condition & Glib::IO_IN) == 0)
  {
    std::cerr << "Invalid fifo response" << std::endl;
  }
  else
  {
    // stream for stdout (does the same as std::cout
    // - this is an example of using fdstream for output)
    fdstream out(1, false);
    std::string text;
    input_stream >> text;
    out << text << std::endl;

    if (text[0] == 'Q')
      mainloop->quit();
  }

  return true;
}

int main(/* int argc, char *argv[] */)
{
  Glib::init();

  // the usual Glib::Main object
  mainloop = Glib::MainLoop::create();

  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;
    }
  }

  const auto read_fd = open("testfifo", O_RDONLY);
  if (read_fd == -1)
  {
    std::cerr << "error opening fifo" << std::endl;
    return -1;
  }

  input_stream.attach(read_fd);
  input_stream.connect(sigc::ptr_fun(MyCallback), Glib::IO_IN);

  // and last but not least - run the application main loop
  mainloop->run();

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

  return 0;
}