Files
GUI/src/utilities/StdOutRedirector.cpp

68 lines
1.4 KiB
C++
Raw Normal View History

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