1 /* 2 * Copyright (C) 2008 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 #ifndef _SOCKETLISTENER_H 17 #define _SOCKETLISTENER_H 18 19 #include <pthread.h> 20 21 #include <unordered_map> 22 #include <vector> 23 24 #include <sysutils/SocketClient.h> 25 #include "SocketClientCommand.h" 26 27 class SocketListener { 28 bool mListen; 29 const char *mSocketName; 30 int mSock; 31 std::unordered_map<int, SocketClient*> mClients; 32 pthread_mutex_t mClientsLock; 33 int mCtrlPipe[2]; 34 pthread_t mThread; 35 bool mUseCmdNum; 36 37 public: 38 SocketListener(const char *socketName, bool listen); 39 SocketListener(const char *socketName, bool listen, bool useCmdNum); 40 SocketListener(int socketFd, bool listen); 41 42 virtual ~SocketListener(); 43 int startListener(); 44 int startListener(int backlog); 45 int stopListener(); 46 47 void sendBroadcast(int code, const char *msg, bool addErrno); 48 49 void runOnEachSocket(SocketClientCommand *command); 50 release(SocketClient * c)51 bool release(SocketClient *c) { return release(c, true); } 52 53 protected: 54 virtual bool onDataAvailable(SocketClient *c) = 0; 55 56 private: 57 static void *threadStart(void *obj); 58 59 // Add all clients to a separate list, so we don't have to hold the lock 60 // while processing it. 61 std::vector<SocketClient*> snapshotClients(); 62 63 bool release(SocketClient *c, bool wakeup); 64 void runListener(); 65 void init(const char *socketName, int socketFd, bool listen, bool useCmdNum); 66 }; 67 #endif 68