避免 QProcess 被杀死(QProcess: Destroyed while process is still 运行)

Avoid QProcess being killed (QProcess: Destroyed while process is still running)

我试过运行这个代码:

QProcess process;
process.setWorkingDirectory("D:\Programs\Qt\Units\MyJavaProjects\StackExp\target");
process.setProgram("java.exe");
process.setArguments({"-jar","StackExp-1.0-SNAPSHOT.jar"});
process.start();

cmd 打不开,也不执行。它只显示此消息:

QProcess: Destroyed while process ("java.exe") is still running

拜托,谁知道出了什么问题?我如何在 QProcess 中使用 cmd 运行 我的 .jar 文件?

您可能在 destructor of QProcess 完成之前调用它,这会终止文档中提到的进程。请注意,当 process 超出范围时调用析构函数。

存在不同的解决方案:

  1. 等待进程完成:waitForFinished

    process.waitForFinished (-1); // -1 = no time out
    
  2. 在栈上构造QProcess

    QProcess *process = new QProcess();
    ...
    

    请注意,您应该在完成后销毁进程以避免内存泄漏。在构造期间指定 parent 可能有助于自动管理 QProcess.

    的生命周期
  3. 以分离模式启动进程:startDetached

    ...
    process.startDetached ();
    

    If the calling process exits, the detached process will continue to run unaffected.

    也可以使用 QProcess::startDetached.

    的静态重载