-
Notifications
You must be signed in to change notification settings - Fork 524
/
systemcommandexecutor.h
56 lines (43 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
#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 int executeCommand(const QString &command) {
QProcess process;
QEventLoop loop;
process.setReadChannel(QProcess::StandardOutput);
auto quitHandler = connect(&process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), &loop, &QEventLoop::quit);
auto errHandler = connect(&process, &QProcess::errorOccurred, &loop, &QEventLoop::quit);
auto stdOutHandler = connect(&process, &QProcess::readyReadStandardOutput, [&]() {
emit processStandardOutput(QString::fromUtf8(process.readAllStandardOutput()));
});
auto stdErrHandler = connect(&process, &QProcess::readyReadStandardError, [&]() {
emit processStandardError(QString::fromUtf8(process.readAllStandardError()));
});
process.start("sh", QStringList() << "-c" << command);
if (!process.waitForStarted()) {
disconnect(quitHandler);
disconnect(errHandler);
disconnect(stdOutHandler);
disconnect(stdErrHandler);
return -1;
}
loop.exec();
disconnect(quitHandler);
disconnect(errHandler);
disconnect(stdOutHandler);
disconnect(stdErrHandler);
return process.exitCode();
}
signals:
void processStandardOutput(QString);
void processStandardError(QString);
};
#endif // SYSTEMCOMMANDEXECUTOR_H