blob: 4be7227548fa1ae685ec88850b6b6fac86557a0a [file] [log] [blame]
Paul Stewart25379f12011-05-26 06:41:38 -07001// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <stdio.h>
6#include <glib.h>
7
8#include "shill/glib_io_handler.h"
9
10namespace shill {
11
12static gboolean DispatchIOHandler(GIOChannel *chan,
13 GIOCondition cond,
14 gpointer data);
15
16GlibIOInputHandler::GlibIOInputHandler(int fd,
17 Callback1<InputData*>::Type *callback)
18 : callback_(callback) {
19 channel_ = g_io_channel_unix_new(fd);
20 g_io_channel_set_close_on_unref(channel_, TRUE);
21 source_id_ = g_io_add_watch(channel_,
22 (GIOCondition)(G_IO_IN | G_IO_NVAL |
23 G_IO_HUP | G_IO_ERR),
24 DispatchIOHandler, this);
25}
26
27GlibIOInputHandler::~GlibIOInputHandler() {
28 g_source_remove(source_id_);
29 g_io_channel_shutdown(channel_, TRUE, NULL);
30 g_io_channel_unref(channel_);
31}
32
33static gboolean DispatchIOHandler(GIOChannel *chan,
34 GIOCondition cond,
35 gpointer data) {
36 GlibIOInputHandler *handler = static_cast<GlibIOInputHandler *>(data);
37 unsigned char buf[4096];
38 gsize len;
39 GIOError err;
40
41 if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR))
42 return FALSE;
43
44 err = g_io_channel_read(chan, reinterpret_cast<gchar *>(buf), sizeof(buf),
45 &len);
46 if (err) {
47 if (err == G_IO_ERROR_AGAIN)
48 return TRUE;
49 return FALSE;
50 }
51
Darin Petkov633ac6f2011-07-08 13:56:13 -070052 InputData input_data(buf, len);
Paul Stewart25379f12011-05-26 06:41:38 -070053 handler->callback_->Run(&input_data);
54
55 return TRUE;
56}
57
58} // namespace shill