This prevents client and server from being sent a SIGPIPE (and terminating) when the other side unexpectedly closes the connection. It's way easier to handle this condition when checking the write() return value, than to do anything smart in a SIGPIPE handler. More details: <http://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly> Change-Id: I1da5bf5ef79c8b7b00ede976e96ed4f1c560049d
51 lines
1.2 KiB
C++
51 lines
1.2 KiB
C++
/**
|
|
* \brief Socket based communication wrapper functions.
|
|
*/
|
|
|
|
#ifndef __SOCKET_COMM_HPP__
|
|
#define __SOCKET_COMM_HPP__
|
|
|
|
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <netdb.h>
|
|
#include <iostream>
|
|
#include <fstream>
|
|
#include <google/protobuf/message.h>
|
|
|
|
#define USE_SIZE_PREFIX
|
|
|
|
namespace fail {
|
|
|
|
class SocketComm {
|
|
public:
|
|
/**
|
|
* This allows us to ignore SIGPIPE.
|
|
*/
|
|
static void init();
|
|
/**
|
|
* Send Protobuf-generated message
|
|
* @param sockfd open socket descriptor to write to
|
|
* @param Msg Reference to Protobuf generated message type
|
|
* \return false if message sending failed
|
|
*/
|
|
static bool sendMsg(int sockfd, google::protobuf::Message& msg);
|
|
/**
|
|
* Receive Protobuf-generated message
|
|
* @param sockfd open socket descriptor to read from
|
|
* @param Msg Reference to Protobuf generated message type
|
|
* \return false if message reception failed
|
|
*/
|
|
static bool rcvMsg(int sockfd, google::protobuf::Message& msg);
|
|
|
|
private:
|
|
static ssize_t safe_write(int fd, const void *buf, size_t count);
|
|
static ssize_t safe_read(int fd, void *buf, size_t count);
|
|
};
|
|
|
|
} // end-of-namespace: fail
|
|
|
|
#endif // __SOCKET_COMM_HPP__
|