Waiting for QProcess to finish or duration to exce

2019-06-07 13:49发布

This question already has an answer here:

I am trying to find a solution to the following situation:

A QProcess should run a command and stop executing it when a desired duration is reached or the command is finished. This QProcess is started by a QThread Worker.

This could easily be done by using this:

QProcess task("executedTool -parameters");
task.start();
task.waitForFinished(desired_max_duration_in_ms);

But there must also be a function to pause the hole thing. I can easily pause the QProcess via pthread signals:

kill(task_.pid(), SIGSTOP);

and

kill(task_.pid(), SIGCONT);

But then the waitForFinished-duration continues running and exceeds while the QProcess is paused.

Does anybody have an idea how to do this? When I could pause the hole QThread, which runs the QProcess and the wait Command, the wait duration would also be paused. But how can I get the pid of a QThread? Is there a nicer Qt solution to do the QProcess pausing?

1条回答
相关推荐>>
2楼-- · 2019-06-07 14:44

An easy and simple solution are Spinlocks. I replaced the waitForFinished(desired_duration) with a while loop, sleeping 100ms each loop. The condition for this loop is that the system time is less then the system time at the start, plus the desired duration. When the paused_ variable is set 100ms will be added to the desired duration, so it keeps pushing the measured time, but also the desired duration.

qint64 ms_start = QDateTime::currentMSecsSinceEpoch();
qint64 ms_end = ms_start + (bag_list_->at(i)->getDuration() * 1000) + 1500;

while (QDateTime::currentMSecsSinceEpoch() < ms_end && worker_thread_->isRunning())
{
  SleepThread::msleep(100);
  if (paused_)
  {
    qDebug() << "add 100";
    ms_end += 100;
  }
}

That probably isn't a nice solution, but it's working for the moment.

If somebody has other ideas I would be happy to hear them.

查看更多
登录 后发表回答