本文介绍了CreateProcess 可以启动一个进程,但 QProcess 不能......为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要启动其他应用程序的 Windows QT 应用程序.如果我使用以下窗口调用一切正常:

I am writing a windows QT app that needs to launch other apps. If I use the following windows calls everything works fine:

QString qsExePath = "C:\\Program Files (x86)\\Some Company\\SomeApp.exe";
QString qsCommandLine = "";


DWORD dwLastError = 0;
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = (WORD)1;

PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo, sizeof(processInfo));

if (CreateProcess((TCHAR*)(qsExePath.utf16()), (TCHAR*)(qsCommandLine.utf16()),
    NULL, NULL, FALSE, 0, NULL, NULL,
    &startupInfo, &processInfo))
{
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}
else
{
    dwLastError = GetLastError();
}

但是,如果我使用以下 QT 调用,它就不起作用,并且会因 QProcess::Unknown 错误而失败.

However, if I use the following QT calls it does not work and fails with QProcess::Unknown Error.

QProcess process;
bool bStarted = process.startDetached(qsExePath);
qDebug()  << process.error();

如果将 SomeApp.exe 复制到我的 %TMP% 目录并相应地更改 qsExePath,我可以让 QProcess 工作,所以这显然是某种权限错误.我不明白为什么......如果真的是权限,我的 CreateProcess 窗口调用不应该失败吗?

I can get QProcess to work if copy SomeApp.exe to my %TMP% directory and change the qsExePath accordingly, so it is obviously some kind of permissions error. I don't understand why though... if it were really permissions, shouldn't my CreateProcess windows call fail?

推荐答案

您的路径中有空格.您正在调用带有单个参数的 QProcess.startDetached() 的重载版本,因此它会将其解释为要执行的完整命令行.因此,尝试将路径用引号括起来,否则它会认为C:\Program"是要执行的程序,而其他一切都是参数,这是错误的:

Your path has spaces in it. You are calling the overloaded version of QProcess.startDetached() that takes a single parameter, so it interprets that as the complete command line to execute. As such, try wrapping the path in quotes, otherwise it will think that "C:\Program" is the program to execute and everything else are arguments, which would be wrong:

QString qsExePath = "\"C:\\Program Files (x86)\\Some Company\\SomeApp.exe\"";
bool bStarted = process.startDetached(qsExePath);

或者,调用 startDetached() 的其他重载版本之一,让它在内部为您计算出必要的引用:

Alternatively, call one of the other overloaded versions of startDetached() and let it work out the necessary quoting internally for you:

QString qsExePath = "C:\\Program Files (x86)\\Some Company\\SomeApp.exe";
bool bStarted = process.startDetached(qsExePath, QStringList());

这篇关于CreateProcess 可以启动一个进程,但 QProcess 不能......为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 07:57