You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.7 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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;
}
const std::string& data = msg.raw();
::write(fdOut_, data.c_str(), data.size());
::write(fdOut_, "\n", 1);
}
IpcMessage receive() override {
if (fdIn_ < 0) {
return IpcMessage{};
}
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));
}
private:
int fdIn_{-1};
int fdOut_{-1};
};