Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detaching a started process

Tags:

c++

qt

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).

like image 342
Guy Avatar asked Jul 06 '13 09:07

Guy


People also ask

How do you detach a 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.

How do you detach a process in Linux?

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.

What command can you use to stop a running process?

There are two commands used to kill a process: kill – Kill a process by ID. killall – Kill a process by name.

How do you stop BG process?

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.


2 Answers

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();
like image 146
ZHANG Zikai Avatar answered Sep 20 '22 20:09

ZHANG Zikai


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.

like image 25
peppe Avatar answered Sep 19 '22 20:09

peppe