c++clinuxqtboost-process

Launching a second Linux program and exit current one from C/C++?


Is it possible from a C or C++ Linux program (say /usr/bin/foo), to programmatically launch another program (say /usr/bin/bar), and have foo exit normally and for bar to keep running?

system(3) isn't suitable as it blocks until the other program completes. I'd like something that returns immediately.

The programs are both GUI programs, but I suspect that isn't relevant.

Is there anything in Qt or boost::process that can help?

Is there any common Linux wrapper program I could run through system(3) to achieve this? I tried xdg-open but I don't think it's the right thing.

Basically I want the second program to "detach" from the first, and behave as if the user launched it via the system UI. (On MacOS, for example, there is an open command, so it would be like system("open /usr/bin/bar"))


Solution

  • With Qt, you can use bool QProcess::startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory = QString(), qint64 *pid = nullptr) as described here https://doc.qt.io/qt-5/qprocess.html#startDetached

    Here is a minimal example of how to use it :

    #include <QCoreApplication>
    #include <QProcess>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        /*
         * starting netstat with args
         * in case the main event loop is exited
         * netstat will be parented to init ( pid 1 ) and continue running
         */
        QProcess::startDetached("/bin/netstat", QStringList() << "-pla" << "-ntuc");
    
        return a.exec();
    }