简体   繁体   English

使用qprocess运行.exe

[英]run .exe using qprocess

I want to open .exe file when qt application is started and terminate .exe when the qt application is closed. 我想在启动qt应用程序时打开.exe文件,并在关闭qt应用程序时终止.exe。

QProcess *proc;

Calculator::Calculator(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Calculator)
{
    ui->setupUi(this);
    proc = new QProcess(this);
    QString fileName = "/ingredient";
    proc->start(fileName);
}

Calculator::~Calculator()
{
    delete ui;
    proc->waitForFinished();
    proc->terminate();
}

When I run Qt application, .exe is running. 当我运行Qt应用程序时,.exe正在运行。 However, .exe is not terminated when I close the qt application, so what should i do? 但是,当我关闭qt应用程序时,.exe没有终止,那我该怎么办?

Try proc->kill(); 尝试proc->kill(); instead of proc->terminate(); 而不是proc->terminate();

According to the document , terminate() attempts to terminate the process, but may not exit the process. 根据该文档terminate()尝试终止该进程,但可能不会退出该进程。

It depends on how the .exe file handle the signal sent by terminate() . 这取决于.exe文件如何处理terminate()发送的信号。

Besides, I think proc->waitForFinished(); 此外,我认为proc->waitForFinished(); is redundant in your code. 在您的代码中是多余的。 It waits the process to finished, instead of telling the process to terminate. 它等待进程完成,而不是告诉进程终止。

On windows you can use the windows API to kill the application. 在Windows上,您可以使用Windows API终止应用程序。 Remember, Qt will try to kill, but won't make sure to kill/end it. 请记住,Qt会尝试杀死它,但不会确保杀死/结束它。 In the following code, change the with the name of your application and this will close it if you have enough privileges. 在以下代码中,使用您的应用程序名称更改,如果您具有足够的特权,则将其关闭。

#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
void YourClassName::killProcess()
{
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof (pEntry);
    BOOL hRes = Process32First(hSnapShot, &pEntry);
    while (hRes)
    {
        if (_wcsicmp(pEntry.szExeFile, L"<AppName>.exe") == 0) // strcmp changed to _wcsicmp
        {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
                                          (DWORD) pEntry.th32ProcessID);
            if (hProcess != NULL)
            {
                TerminateProcess(hProcess, 9);
                CloseHandle(hProcess);
            }
        }
        hRes = Process32Next(hSnapShot, &pEntry);
    }
    CloseHandle(hSnapShot);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM