Files
GUI/src/utilities/StdOutRedirector.cpp

64 lines
1.4 KiB
C++
Raw Normal View History

2021-11-19 13:20:17 +08:00
#include "StdOutRedirector.h"
2022-06-13 13:26:49 +08:00
2021-11-19 13:20:17 +08:00
#include <QTimer>
#include <QDebug>
2022-06-13 13:26:49 +08:00
2021-11-19 13:20:17 +08:00
StdOutRedirector::StdOutRedirector()
2022-06-13 13:26:49 +08:00
: QObject()
2021-11-19 13:20:17 +08:00
{
#ifdef __linux__
2022-06-13 13:26:49 +08:00
if (pipe(mFdguistd) == -1)
printf("failed!");
2021-11-19 13:20:17 +08:00
#else
2022-06-13 13:26:49 +08:00
// Redirect
if (_pipe(mFdguistd, 4096, _O_BINARY) == -1)
printf("failed!");
2021-11-19 13:20:17 +08:00
#endif
2022-06-13 13:26:49 +08:00
//int tr = fcntl(fdguistd, O_NONBLOCK);
// Duplicate stdout file descriptor (next line will close original)
mFdStdOut = dup(fileno(stdout));
// Duplicate write end of pipe to stdout file descriptor
if (dup2(mFdguistd[1], fileno(stdout)) != 0)
printf("failed!");
// Close original
close(1);
// Duplicate write end of original
dup2(mFdguistd[1], 1);
mBuffer = new char[mBufferSize];
2021-11-19 13:20:17 +08:00
}
StdOutRedirector::~StdOutRedirector()
{
2022-06-13 13:26:49 +08:00
delete[] mBuffer;
2021-11-19 13:20:17 +08:00
}
void StdOutRedirector::readOutsToTF()
{
2022-06-13 13:26:49 +08:00
size_t len;
char* copy;
int n_out;
QString str;
fflush(stdout);
//Perhaps there is a non-blocking version of _read() that you can call ?
memset(mBuffer, 0, mBufferSize);
n_out = read(mFdguistd[0], mBuffer, mBufferSize);
if (n_out <= 0)
{
return;
}
if (n_out >= 1)
{
str.append(QString(mBuffer));
int con = str.lastIndexOf('\n');
int remv = str.at(con - 1) == '\n' ? 1 : 0;
if (con > 0)
{
str = str.remove(con - remv, str.length());
mOutput->append(str);
}
}
return;
2021-11-19 13:20:17 +08:00
}