|
|
#pragma once
|
|
|
|
|
|
#include "IpcChannel.h"
|
|
|
|
|
|
#include <fcntl.h>
|
|
|
#include <sys/stat.h>
|
|
|
#include <unistd.h>
|
|
|
|
|
|
// IPC‑канал поверх именованных pipe.
|
|
|
// Инкапсулирует работу с файловыми дескрипторами и обмен сообщениями IpcMessage.
|
|
|
// readPipe — тот FIFO, который этот endpoint читает; writePipe — тот, в который пишет.
|
|
|
|
|
|
class IpcPipeChannel : public IpcChannel {
|
|
|
public:
|
|
|
IpcPipeChannel(const char* readPipe, const char* writePipe) {
|
|
|
// Канал не создаёт FIFO, только открывает.
|
|
|
// Открываем оба конца как O_RDWR, чтобы избежать блокировок на open(O_RDONLY/O_WRONLY).
|
|
|
// При этом логически читаем только из readPipe, а пишем только в writePipe.
|
|
|
fdIn_ = ::open(readPipe, O_RDWR);
|
|
|
fdOut_ = ::open(writePipe, O_RDWR);
|
|
|
}
|
|
|
|
|
|
~IpcPipeChannel() override {
|
|
|
if (fdIn_ >= 0) {
|
|
|
::close(fdIn_);
|
|
|
}
|
|
|
if (fdOut_ >= 0) {
|
|
|
::close(fdOut_);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void send(const IpcMessage& msg) override {
|
|
|
if (fdOut_ < 0) {
|
|
|
return;
|
|
|
}
|
|
|
auto raw = msg.serialize(); // тип определяется сериализатором
|
|
|
|
|
|
// Для текстовых форматов (std::string):
|
|
|
if constexpr (std::is_same_v<typename IpcMessage::RawData, std::string>) {
|
|
|
const std::string& data = raw;
|
|
|
::write(fdOut_, data.c_str(), data.size());
|
|
|
::write(fdOut_, "\n", 1);
|
|
|
}
|
|
|
// Можно добавить другие форматы по мере необходимости
|
|
|
}
|
|
|
|
|
|
IpcMessage receive() override {
|
|
|
if (fdIn_ < 0) {
|
|
|
return IpcMessage{};
|
|
|
}
|
|
|
|
|
|
// Для текстовых форматов:
|
|
|
if constexpr (std::is_same_v<typename IpcMessage::RawData, std::string>) {
|
|
|
char buf[4096];
|
|
|
const int n = ::read(fdIn_, buf, sizeof(buf) - 1);
|
|
|
if (n <= 0) {
|
|
|
return IpcMessage{};
|
|
|
}
|
|
|
buf[n] = 0;
|
|
|
return IpcMessage(std::string(buf));
|
|
|
}
|
|
|
// Можно добавить другие форматы по мере необходимости
|
|
|
return IpcMessage{};
|
|
|
}
|
|
|
|
|
|
private:
|
|
|
int fdIn_{-1};
|
|
|
int fdOut_{-1};
|
|
|
};
|