Paul Stewart | f0aae10 | 2011-10-19 12:11:44 -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 | |
| 5 | #include "shill/glib_io_ready_handler.h" |
| 6 | |
| 7 | #include <base/logging.h> |
| 8 | #include <glib.h> |
| 9 | #include <stdio.h> |
| 10 | #include <sys/socket.h> |
| 11 | |
| 12 | namespace shill { |
| 13 | |
| 14 | static gboolean DispatchIOHandler(GIOChannel *chan, |
| 15 | GIOCondition cond, |
| 16 | gpointer data) { |
| 17 | Callback1<int>::Type *callback = static_cast<Callback1<int>::Type *>(data); |
| 18 | |
| 19 | if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) |
| 20 | return FALSE; |
| 21 | |
| 22 | callback->Run(g_io_channel_unix_get_fd(chan)); |
| 23 | |
| 24 | return TRUE; |
| 25 | } |
| 26 | |
| 27 | GlibIOReadyHandler::GlibIOReadyHandler(int fd, |
| 28 | IOHandler::ReadyMode mode, |
| 29 | Callback1<int>::Type *callback) |
| 30 | : channel_(NULL), |
| 31 | callback_(callback), |
| 32 | source_id_(G_MAXUINT) { |
| 33 | if (mode == kModeInput) { |
| 34 | condition_ = static_cast<GIOCondition>( |
| 35 | G_IO_IN | G_IO_NVAL | G_IO_HUP | G_IO_ERR); |
| 36 | } else if (mode == kModeOutput) { |
| 37 | condition_ = static_cast<GIOCondition>( |
| 38 | G_IO_OUT | G_IO_NVAL | G_IO_HUP | G_IO_ERR); |
| 39 | } else { |
| 40 | NOTREACHED() << "Unknown IO ready mode: " << mode; |
| 41 | } |
| 42 | |
| 43 | channel_ = g_io_channel_unix_new(fd); |
| 44 | g_io_channel_set_close_on_unref(channel_, FALSE); |
| 45 | } |
| 46 | |
| 47 | GlibIOReadyHandler::~GlibIOReadyHandler() { |
| 48 | g_source_remove(source_id_); |
Paul Stewart | c2350ee | 2011-10-19 12:28:40 -0700 | [diff] [blame^] | 49 | // NB: We don't shut down the channel since we don't own it |
Paul Stewart | f0aae10 | 2011-10-19 12:11:44 -0700 | [diff] [blame] | 50 | g_io_channel_unref(channel_); |
| 51 | } |
| 52 | |
| 53 | void GlibIOReadyHandler::Start() { |
| 54 | if (source_id_ == G_MAXUINT) { |
| 55 | source_id_ = g_io_add_watch(channel_, condition_, DispatchIOHandler, |
| 56 | callback_); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | void GlibIOReadyHandler::Stop() { |
| 61 | if (source_id_ != G_MAXUINT) { |
| 62 | g_source_remove(source_id_); |
| 63 | source_id_ = G_MAXUINT; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | } // namespace shill |