50 lines
1.1 KiB
C++
50 lines
1.1 KiB
C++
// UnixIpcBridge.cxx
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
// Author: Unai Blazquez <unaibg2000@gmail.com>
|
|
#include "UnixIpcBridge.hpp"
|
|
|
|
#include <cstring>
|
|
#include <stdexcept>
|
|
|
|
UnixIpcBridge::UnixIpcBridge(const std::string& socket_path)
|
|
: m_socket_path(socket_path)
|
|
{
|
|
}
|
|
|
|
void UnixIpcBridge::send(int value)
|
|
{
|
|
connect_to_consumer();
|
|
|
|
ssize_t n = ::send(m_socket_fd, &value, sizeof(value), 0);
|
|
if (n != sizeof(value))
|
|
{
|
|
close(m_socket_fd);
|
|
m_socket_fd = -1;
|
|
throw std::runtime_error("UnixIpcBridge::send: failed to write value");
|
|
}
|
|
|
|
close(m_socket_fd);
|
|
m_socket_fd = -1;
|
|
}
|
|
|
|
void UnixIpcBridge::connect_to_consumer()
|
|
{
|
|
m_socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
|
if (m_socket_fd < 0)
|
|
{
|
|
throw std::runtime_error("UnixIpcBridge: socket() failed");
|
|
}
|
|
|
|
struct sockaddr_un addr = {};
|
|
addr.sun_family = AF_UNIX;
|
|
std::strncpy(addr.sun_path, m_socket_path.c_str(), sizeof(addr.sun_path) - 1);
|
|
|
|
if (connect(m_socket_fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) <
|
|
0)
|
|
{
|
|
close(m_socket_fd);
|
|
m_socket_fd = -1;
|
|
throw std::runtime_error("UnixIpcBridge: connect() failed");
|
|
}
|
|
}
|