我考虑使用QProcess多次调用命令行应用程序(http://plnkr.co/edit/RxTte5njdS8GfTiD73LA?p=preview)。每次用户单击按钮,都会发出命令。
将监控应用输出并重定向到屏幕。代码如下所示。
void Gpio::command(QString argument)
{
// if(process)
// delete process;
process = new QProcess(this);
connect(process, SIGNAL(started()), this, SLOT(onStart()));
connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(onFinish(int,QProcess::ExitStatus)));
connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readGpio()));
QString program("gpio");
QStringList list = argument.split(" ");
process->start(program, list);
}
问题:我应delete process
吗?这样做我得到了:
QProcess: Destroyed while process is still running.
监控exitCode
和exitStatus
我发现它们总是0
。
此问题更多地涉及正确使用QProcess,gpio关注特定错误。
答案 0 :(得分:0)
由于您不希望同时运行多个进程(根据注释),因此您无需多次创建/删除QProcess
。
gpio.h
QProcess* m_gpioProcess;
gpio.cpp文件
Gpio::Gpio(.....),
.....(),
m_gpioProcess(new QProcess(this))
{
m_gpioProcess->setProgram("gpio");
connect(m_gpioProcess, SIGNAL(started()), this, SLOT(onStart()));
connect(m_gpioProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(onFinish(int,QProcess::ExitStatus)));
connect(m_gpioProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readGpio()));
}
void Gpio::command(const QString& args)
{
if (m_gpioProcess->state() != QProcess::NotRunning) {
qDebug() << "Process already running, ignoring the request";
return;
}
m_gpioProcess->setArguments(args.split(" "));
m_gpioProcess->start();
if (m_gpioProcess->waitForStarted()) {
qDebug() << "Process started with arguments:" << m_gpioProcess->arguments();
}
}
如果您想阻止用户多次点击该按钮,请考虑按m_gpioProcess
状态启用/禁用该按钮。
对于Qt
4.8,只需删除此行
m_gpioProcess->setProgram("gpio");
和这一行
m_gpioProcess->setArguments(args.split(" "));
并更改此行
m_gpioProcess->start();
到
m_gpioProcess->start("gpio", args.split(" "));
答案 1 :(得分:0)
好吧,在调用process->waitForFinished();
之后,我似乎忘记了start
。这似乎解决了这个问题。
答案 2 :(得分:-1)
添加以下代码可能会有帮助:
process->close();