blob: 1f456526bad1c1dd70ba1f15ba716013ba5bf714 [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
Paul Stewartf0aae102011-10-19 12:11:44 -07005#include "shill/glib_io_input_handler.h"
Paul Stewart26b327e2011-10-19 11:38:09 -07006
Paul Stewart25379f12011-05-26 06:41:38 -07007#include <stdio.h>
8#include <glib.h>
9
Paul Stewart25379f12011-05-26 06:41:38 -070010namespace shill {
11
12static gboolean DispatchIOHandler(GIOChannel *chan,
13 GIOCondition cond,
Paul Stewart25379f12011-05-26 06:41:38 -070014 gpointer data) {
Paul Stewartf0aae102011-10-19 12:11:44 -070015 Callback1<InputData*>::Type *callback =
16 static_cast<Callback1<InputData*>::Type *>(data);
Paul Stewart25379f12011-05-26 06:41:38 -070017 unsigned char buf[4096];
18 gsize len;
19 GIOError err;
20
21 if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR))
22 return FALSE;
23
24 err = g_io_channel_read(chan, reinterpret_cast<gchar *>(buf), sizeof(buf),
25 &len);
26 if (err) {
27 if (err == G_IO_ERROR_AGAIN)
28 return TRUE;
29 return FALSE;
30 }
31
Darin Petkov633ac6f2011-07-08 13:56:13 -070032 InputData input_data(buf, len);
Paul Stewartf0aae102011-10-19 12:11:44 -070033 callback->Run(&input_data);
Paul Stewart25379f12011-05-26 06:41:38 -070034
35 return TRUE;
36}
37
Paul Stewartf0aae102011-10-19 12:11:44 -070038GlibIOInputHandler::GlibIOInputHandler(int fd,
39 Callback1<InputData*>::Type *callback)
40 : channel_(g_io_channel_unix_new(fd)),
41 callback_(callback),
42 source_id_(G_MAXUINT) {
43 g_io_channel_set_close_on_unref(channel_, TRUE);
44}
45
46GlibIOInputHandler::~GlibIOInputHandler() {
47 g_source_remove(source_id_);
48 g_io_channel_shutdown(channel_, TRUE, NULL);
49 g_io_channel_unref(channel_);
50}
51
52void GlibIOInputHandler::Start() {
53 if (source_id_ == G_MAXUINT) {
54 source_id_ = g_io_add_watch(channel_,
55 static_cast<GIOCondition>(
56 G_IO_IN | G_IO_NVAL | G_IO_HUP | G_IO_ERR),
57 DispatchIOHandler, callback_);
58 }
59}
60
61void GlibIOInputHandler::Stop() {
62 if (source_id_ != G_MAXUINT) {
63 g_source_remove(source_id_);
64 source_id_ = G_MAXUINT;
65 }
66}
67
Paul Stewart25379f12011-05-26 06:41:38 -070068} // namespace shill