first commit

This commit is contained in:
2023-01-26 13:56:18 +08:00
commit 4abe6bf738
17 changed files with 1105 additions and 0 deletions

75
src/ipc_nix.cpp Normal file
View File

@@ -0,0 +1,75 @@
// Copyright (c) 2023 - present, Anton Anikin <anton@anikin.xyz>
// All rights reserved.
#include <fcntl.h>
#include <fmt/core.h>
#include <sys/stat.h>
#include <unistd.h>
#include "ipc.hpp"
namespace ipc
{
std::string
default_name()
{
return fmt::format("/tmp/fifo_ipc_{}", getpid());
}
void
make_fifo(const std::string& name, unsigned int mode)
{
if (mkfifo(name.c_str(), mode) < 0)
{
auto message = fmt::format("mkfifo '{}' : {}", name, strerror(errno));
throw std::runtime_error(message);
}
}
void
init(const std::string& name, unsigned int mode)
{
make_fifo(name + "_s", mode);
make_fifo(name + "_c", mode);
}
Ipc::Ipc(const std::string& name, bool is_server, int verbose)
: m_verbose(verbose)
{
auto fifo_open = [](std::string name, int flags) -> int {
int fd = open(name.c_str(), flags);
if (fd == -1) {
auto message = fmt::format("open '{}' : {}", name, strerror(errno));
throw std::runtime_error(message);
}
return fd;
};
if (is_server) {
m_reader_fd = fifo_open(name + "_c", O_RDONLY);
m_writer_fd = fifo_open(name + "_s", O_WRONLY);
} else {
m_writer_fd = fifo_open(name + "_c", O_WRONLY);
m_reader_fd = fifo_open(name + "_s", O_RDONLY);
}
}
Ipc::~Ipc()
{
}
ssize_t
Ipc::_write(const void* buffer, size_t bytes)
{
return ::write(m_writer_fd, buffer, bytes);
}
ssize_t
Ipc::_read(void* buffer, size_t bytes)
{
return ::read(m_reader_fd, buffer, bytes);
}
}