first commit
This commit is contained in:
75
src/ipc_nix.cpp
Normal file
75
src/ipc_nix.cpp
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user