forked from vedderb/vesc_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
systemcommandexecutor.h
57 lines (44 loc) · 1.68 KB
/
systemcommandexecutor.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#ifndef SYSTEMCOMMANDEXECUTOR_H
#define SYSTEMCOMMANDEXECUTOR_H
#include <QObject>
#include <QProcess>
#include <QEventLoop>
#include <QTimer>
class SystemCommandExecutor : public QObject
{
Q_OBJECT
public:
explicit SystemCommandExecutor(QObject *parent = nullptr) : QObject(parent) {}
Q_INVOKABLE QString executeCommand(const QString &command) {
QProcess process;
QEventLoop loop;
process.setReadChannel(QProcess::StandardOutput);
auto conn1 = connect(&process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), &loop, &QEventLoop::quit);
auto conn2 = connect(&process, &QProcess::errorOccurred, &loop, &QEventLoop::quit);
auto conn3 = connect(&process, &QProcess::readyReadStandardOutput, [&]() {
emit processOutput(QString::fromUtf8(process.readAllStandardOutput()));
});
auto conn4 = connect(&process, &QProcess::readyReadStandardError, [&]() {
emit processOutput(QString::fromUtf8(process.readAllStandardError()));
});
process.start("sh", QStringList() << "-c" << command);
if (!process.waitForStarted()) {
disconnect(conn1);
disconnect(conn2);
disconnect(conn3);
disconnect(conn4);
return "Failed to start process";
}
loop.exec();
disconnect(conn1);
disconnect(conn2);
disconnect(conn3);
disconnect(conn4);
QString output = process.readAllStandardOutput();
QString errorOutput = process.readAllStandardError();
return output + errorOutput;
}
signals:
void processOutput(QString);
};
#endif // SYSTEMCOMMANDEXECUTOR_H