1 // Copyright (c) 2009 The Chromium 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 #ifndef BASE_SYNC_SOCKET_H_ 6 #define BASE_SYNC_SOCKET_H_ 7 8 // A socket abstraction used for sending and receiving plain 9 // data. Because they are blocking, they can be used to perform 10 // rudimentary cross-process synchronization with low latency. 11 12 #include "base/basictypes.h" 13 #if defined(OS_WIN) 14 #include <windows.h> 15 #endif 16 #include <sys/types.h> 17 18 namespace base { 19 20 class SyncSocket { 21 public: 22 #if defined(OS_WIN) 23 typedef HANDLE Handle; 24 #else 25 typedef int Handle; 26 #endif 27 28 // Creates a SyncSocket from a Handle. Used in transport. 29 explicit SyncSocket(Handle handle) : handle_(handle) { } 30 ~SyncSocket() { Close(); } 31 32 // Creates an unnamed pair of connected sockets. 33 // pair is a pointer to an array of two SyncSockets in which connected socket 34 // descriptors are returned. Returns true on success, false on failure. 35 static bool CreatePair(SyncSocket* pair[2]); 36 37 // Closes the SyncSocket. Returns true on success, false on failure. 38 bool Close(); 39 40 // Sends the message to the remote peer of the SyncSocket. 41 // Note it is not safe to send messages from the same socket handle by 42 // multiple threads simultaneously. 43 // buffer is a pointer to the data to send. 44 // length is the length of the data to send (must be non-zero). 45 // Returns the number of bytes sent, or 0 upon failure. 46 size_t Send(const void* buffer, size_t length); 47 48 // Receives a message from an SyncSocket. 49 // buffer is a pointer to the buffer to receive data. 50 // length is the number of bytes of data to receive (must be non-zero). 51 // Returns the number of bytes received, or 0 upon failure. 52 size_t Receive(void* buffer, size_t length); 53 54 // Returns the number of bytes available. If non-zero, Receive() will not 55 // not block when called. NOTE: Some implementations cannot reliably 56 // determine the number of bytes available so avoid using the returned 57 // size as a promise and simply test against zero. 58 size_t Peek(); 59 60 // Extracts the contained handle. Used for transferring between 61 // processes. 62 Handle handle() const { return handle_; } 63 64 private: 65 Handle handle_; 66 67 DISALLOW_COPY_AND_ASSIGN(SyncSocket); 68 }; 69 70 } // namespace base 71 72 #endif // BASE_SYNC_SOCKET_H_ 73