7

I've started a process using QProcess::start() and I need to detach it afterwards. How can I do it? I haven't found relevant info in the Qt docs.

I'm aware of QProcess::startDetached(), but due to other code in the program, I can't use it (I need to separate the starting and the detaching of the process).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
Guy
  • 1,984
  • 1
  • 16
  • 19
  • I remember this being a feature request a couple of years ago, but I don't think it was ever implemented. Then again, I haven't kept up to date in recent times, so I might have missed something. – Bart Jul 06 '13 at 09:54

2 Answers2

9

If you take a look into the implementation of QProcess::~QProcess(), you will know how QProcess terminates the process with its destruction. Also, note that QProcess::setProcessState() is protected, which means you could implement a QDetachableProcess inherited from QProcess with a method detach() to call setProcessState(QProcess::NotRunning); as a workaround.

For example:

class QDetachableProcess : public QProcess
{
public:
    QDetachableProcess(QObject *parent = 0) : QProcess(parent){}
    void detach()
    {
        this->waitForStarted();
        setProcessState(QProcess::NotRunning);
    }
};

Then you could do things like this:

QDetachableProcess process;
process.setEnvironment(QStringList() << "SOME_ENV=Value");

process.start();

process.detach();
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
ZHANG Zikai
  • 560
  • 6
  • 15
5

You can't as of 5.1, see here. There's also a suggestion in the comments, not sure if useful for your case):

Workaround proposal: write a helper process that starts detached processes, and terminates itself when all setting up is completed.

peppe
  • 21,934
  • 4
  • 55
  • 70