1// 2// Copyright (C) 2014 The Android Open Source Project 3// 4// Licensed under the Apache License, Version 2.0 (the "License"); 5// you may not use this file except in compliance with the License. 6// You may obtain a copy of the License at 7// 8// http://www.apache.org/licenses/LICENSE-2.0 9// 10// Unless required by applicable law or agreed to in writing, software 11// distributed under the License is distributed on an "AS IS" BASIS, 12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13// See the License for the specific language governing permissions and 14// limitations under the License. 15// 16 17#include "shill/net/io_ready_handler.h" 18 19#include <unistd.h> 20 21#include <base/logging.h> 22 23namespace shill { 24 25IOReadyHandler::IOReadyHandler(int fd, 26 ReadyMode mode, 27 const ReadyCallback& ready_callback) 28 : fd_(fd), 29 ready_mode_(mode), 30 ready_callback_(ready_callback) {} 31 32IOReadyHandler::~IOReadyHandler() { 33 Stop(); 34} 35 36void IOReadyHandler::Start() { 37 CHECK(ready_mode_ == kModeOutput || ready_mode_ == kModeInput); 38 base::MessageLoopForIO::Mode mode; 39 if (ready_mode_ == kModeOutput) { 40 mode = base::MessageLoopForIO::WATCH_WRITE; 41 } else { 42 mode = base::MessageLoopForIO::WATCH_READ; 43 } 44 45 if (!base::MessageLoopForIO::current()->WatchFileDescriptor( 46 fd_, true, mode, &fd_watcher_, this)) { 47 LOG(ERROR) << "WatchFileDescriptor failed on read"; 48 } 49} 50 51void IOReadyHandler::Stop() { 52 fd_watcher_.StopWatchingFileDescriptor(); 53} 54 55void IOReadyHandler::OnFileCanReadWithoutBlocking(int fd) { 56 CHECK_EQ(fd_, fd); 57 CHECK_EQ(ready_mode_, kModeInput); 58 59 ready_callback_.Run(fd_); 60} 61 62void IOReadyHandler::OnFileCanWriteWithoutBlocking(int fd) { 63 CHECK_EQ(fd_, fd); 64 CHECK_EQ(ready_mode_, kModeOutput); 65 66 ready_callback_.Run(fd_); 67} 68 69} // namespace shill 70