Paul Stewart | 25379f1 | 2011-05-26 06:41:38 -0700 | [diff] [blame] | 1 | // 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 Stewart | f0aae10 | 2011-10-19 12:11:44 -0700 | [diff] [blame] | 5 | #include "shill/glib_io_input_handler.h" |
Paul Stewart | 26b327e | 2011-10-19 11:38:09 -0700 | [diff] [blame] | 6 | |
Paul Stewart | 25379f1 | 2011-05-26 06:41:38 -0700 | [diff] [blame] | 7 | #include <stdio.h> |
| 8 | #include <glib.h> |
| 9 | |
Paul Stewart | 25379f1 | 2011-05-26 06:41:38 -0700 | [diff] [blame] | 10 | namespace shill { |
| 11 | |
| 12 | static gboolean DispatchIOHandler(GIOChannel *chan, |
| 13 | GIOCondition cond, |
Paul Stewart | 25379f1 | 2011-05-26 06:41:38 -0700 | [diff] [blame] | 14 | gpointer data) { |
Paul Stewart | f0aae10 | 2011-10-19 12:11:44 -0700 | [diff] [blame] | 15 | Callback1<InputData*>::Type *callback = |
| 16 | static_cast<Callback1<InputData*>::Type *>(data); |
Paul Stewart | 25379f1 | 2011-05-26 06:41:38 -0700 | [diff] [blame] | 17 | 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 Petkov | 633ac6f | 2011-07-08 13:56:13 -0700 | [diff] [blame] | 32 | InputData input_data(buf, len); |
Paul Stewart | f0aae10 | 2011-10-19 12:11:44 -0700 | [diff] [blame] | 33 | callback->Run(&input_data); |
Paul Stewart | 25379f1 | 2011-05-26 06:41:38 -0700 | [diff] [blame] | 34 | |
| 35 | return TRUE; |
| 36 | } |
| 37 | |
Paul Stewart | f0aae10 | 2011-10-19 12:11:44 -0700 | [diff] [blame] | 38 | GlibIOInputHandler::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 | |
| 46 | GlibIOInputHandler::~GlibIOInputHandler() { |
| 47 | g_source_remove(source_id_); |
| 48 | g_io_channel_shutdown(channel_, TRUE, NULL); |
| 49 | g_io_channel_unref(channel_); |
| 50 | } |
| 51 | |
| 52 | void 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 | |
| 61 | void GlibIOInputHandler::Stop() { |
| 62 | if (source_id_ != G_MAXUINT) { |
| 63 | g_source_remove(source_id_); |
| 64 | source_id_ = G_MAXUINT; |
| 65 | } |
| 66 | } |
| 67 | |
Paul Stewart | 25379f1 | 2011-05-26 06:41:38 -0700 | [diff] [blame] | 68 | } // namespace shill |