qt---主进程加载一个子进程的方法以及其中遇到“Calling a private constructor of class 'QString'”

发布时间 2023-11-04 15:56:24作者: 不会笑的孩子

.pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++17

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

FORMS += \
    mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

cpp

#include "mainwindow.h"
#include <QApplication>
#include <QProcess>
#include <QDebug>
#include <QMutex>
#include <QMessageBox>
#include <windows.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    // 创建互斥对象
//    QMutex mutex;
//    if (!mutex.tryLock())
//    {
//        QMessageBox::information(nullptr, "Info", "主程序已经在运行.");
//        return 1;
//    }
    MainWindow w;
    w.show();
    QProcess process;
    process.startDetached("xxxxxxx"); //

    if (process.waitForStarted())
    {
        qWarning()<<"另一个程序已启动";
        process.waitForFinished(-1); // 等待另一个程序运行结束
    }
    else
    {
        qWarning()<<"启动另一个程序时出错1"<< process.error();

        qWarning()<<"启动另一个程序时出错"<< process.errorString();
    }

   QObject::connect(&w, SIGNAL(destroyed()), &a, SLOT(quit()));


    return a.exec();
}

“Calling a private constructor of class 'QString'”

加上QStringLiteral

QString programPath = QStringLiteral("E:\\work\\exercise\\untitled4\\childprocess.exe");

process.startDetached(processpath); process.start(processpath); 的区别

process.startDetached(processpath)和process.start(processpath)是Qt中用于启动外部进程的两种不同的方法。

  • process.startDetached(processpath)启动一个外部进程并立即将其分离(Detached)。这意味着应用程序将继续执行而不是等待外部进程完成。这通常用于启动后台进程,例如在不阻止应用程序的情况下运行一个独立的工具。完成该函数不会等待外部进程。(子进程和父进程分开)

  • process.start(processpath)启动一个外部进程,但它会等待外部进程执行完成。这通常用于需要与外部进程进行交互或等待需要其执行结果的情况。(等待子进程完成以后父进程才执行)