Skip to content

File server.h

File List > bindings > ipc > server.h

Go to the documentation of this file

#pragma once

#include <libcomm/msg.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include <atomic>
#include <string>
#include <thread>

#include "msg_queue.h"
#include "thread_safe_map.h"

namespace ipc {

class Server {
 public:
  Server(std::string socket_path, int timeout);
  ~Server();

  void Start();
  void Stop();

  MsgQueue<const msg_t*>* fw_queue;
  MsgQueue<msg_t>* bw_queue;

  // Function: SendSignal
  //   Sends a signal to client with the given client_fd
  // Parameters:
  //   client_fd - file descriptor of the client to send the signal to
  // Returns:
  //   true if the signal was sent successfully, false otherwise
  bool SendSignal(int client_fd);

  // Function: SendSignalToAllClients
  //   Sends a signal to all clients that registered a signal
  // Returns:
  //   true if the signal was sent successfully, false otherwise
  bool SendSignalToAllClients();

 private:
  void AcceptConnections();
  void HandleClient(int client_fd);
  bool ReceivePayload(int client_fd, msg_t* payload);
  bool Response(int client_fd, const msg_t& payload);
  void SendError(int client_fd, const uint32_t& id);
  void RegisterSignal(int client_fd, const msg_t& payload);

  std::string socket_path_;
  int socket_fd_;
  int timeout_;
  std::thread accept_thread_;
  std::vector<std::thread> client_threads_;
  std::atomic<bool> running_;

  using PidSignal = std::tuple<pid_t, int>;
  ThreadSafeMap<int, PidSignal> client_signal_map_;
};

}  // namespace ipc