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).
You can press ctrl-z to interrupt the process and then run bg to make it run in the background. You can show a numbered list all processes backgrounded in this manner with jobs . Then you can run disown %1 (replace 1 with the process number output by jobs ) to detach the process from the terminal.
We can use the & operator, and the nohup, disown, setsid, and screen commands to start a process detached from the terminal. However, to detach a process that has already started, we need to use the bg command after pausing the process using Ctrl+Z.
There are two commands used to kill a process: kill – Kill a process by ID. killall – Kill a process by name.
The command kill 21593 ends the background find process, and the second ps command returns no status information about PID 21593. The system does not display the termination message until you enter your next command, unless that command is cd. The kill command lets you cancel background processes.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With