Files

86 lines
2.1 KiB
C++
Raw Permalink Normal View History

2021-05-18 23:10:33 +02:00
#include "RemoteRunner.h"
2021-05-19 12:08:57 +02:00
#include "Message.h"
2021-05-18 23:10:33 +02:00
#include <QCoreApplication>
#include <unistd.h>
RemoteRunner::RemoteRunner(int inputId, int outputId)
: m_thread(inputId),
m_outputId(outputId)
{
connect (&m_thread, SIGNAL(receivedMessage(QByteArray)),
this, SIGNAL(receivedMessage(QByteArray)), Qt::QueuedConnection);
m_thread.start();
}
RemoteRunner::~RemoteRunner()
{
m_thread.closeConnection();
m_thread.wait();
}
2024-05-17 11:39:44 +02:00
void RemoteRunner::runRemote(const Message &message) const
2021-05-19 12:08:57 +02:00
{
2021-08-14 17:13:41 +02:00
assert(message.size() > 0);
assert(message.size() < 0x7FFF);
char sizeIndicator[2];
2021-08-14 22:00:42 +02:00
uint32_t messageSize = message.size();
2024-02-17 21:14:03 +01:00
sizeIndicator[0] = messageSize;
2021-08-14 22:00:42 +02:00
sizeIndicator[1] = messageSize >> 8;
2021-08-14 17:13:41 +02:00
write(m_outputId, sizeIndicator, 2);
2021-05-19 12:08:57 +02:00
write(m_outputId, message.begin(), message.size());
}
2021-05-18 23:10:33 +02:00
// ///////////////////////////////////////////
RemoteRunnerPrivate::RemoteRunnerPrivate(int inputId)
: m_inputId(inputId)
{
}
void RemoteRunnerPrivate::closeConnection()
{
close (m_inputId);
}
void RemoteRunnerPrivate::run()
{
2024-02-25 19:22:08 +01:00
char buf[1000];
char *start = buf;
2026-04-11 14:54:32 +02:00
size_t offset = 0;
2021-05-18 23:10:33 +02:00
while (true) {
2024-02-25 19:22:08 +01:00
ssize_t amount = read(m_inputId, buf + offset, sizeof(buf) - offset);
2021-05-18 23:10:33 +02:00
if (amount <= 0) {
2021-08-14 17:13:41 +02:00
// printf("remote runner private got read: %ld, closing down\n", amount);
2021-05-18 23:10:33 +02:00
QCoreApplication::quit();
return;
}
2024-02-25 19:22:08 +01:00
offset += amount;
const char *end = buf + offset;
for (char *i = start; i < end; ++i) {
if (*i == 0) {
QByteArray bytes(start, i - start);
emit receivedMessage(bytes);
start = i + 1;
}
}
2026-04-11 14:54:32 +02:00
if (start >= end) {
2024-02-25 19:22:08 +01:00
start = buf;
offset = 0;
}
2026-04-11 14:54:32 +02:00
else if (start > buf) {
// compact: move unconsumed data to beginning
assert(end >= start); // don't let offset get negative
offset = end - start;
memmove(buf, start, offset);
start = buf;
}
2024-02-25 19:22:08 +01:00
else if (offset >= sizeof(buf))
throw std::runtime_error("Too long message on Pipe");
2021-05-18 23:10:33 +02:00
}
}