简体   繁体   English

ShellExecuteEx和GetExitCodeProcess - 处理无效或分段错误

[英]ShellExecuteEx & GetExitCodeProcess - Handle Invalid or Segmentation Fault

I'm trying to start an application and then monitor it until it closes. 我正在尝试启动一个应用程序,然后监视它直到它关闭。 I'm using ShellExecuteEX and GetExitCodeProcess and having several problems. 我正在使用ShellExecuteEX和GetExitCodeProcess并遇到一些问题。

The code below causes a segmentation fault when GetExitCodeProcess is Called. 调用GetExitCodeProcess时,下面的代码会导致分段错误。 If I change shellInfo.fMask = NULL, it will not seg fault but I recieve an error saying Invalid Handle. 如果我更改shellInfo.fMask = NULL,它将不会出现错误但我收到错误说无效句柄。

Notepad.exe does launch. Notepad.exe确实启动了。

QString executeFile("notepad.exe");

// Conversion QString to LPCTSTR
wchar_t* tempEF = new wchar_t[executeFile.size()+1];
int tempEFTerminator = executeFile.toWCharArray(tempEF);
tempEF[tempEFTerminator] = 0;


LPDWORD exitCode = 0;
SHELLEXECUTEINFO shellInfo;

shellInfo.cbSize = sizeof(SHELLEXECUTEINFO);

shellInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
shellInfo.hwnd = NULL;
shellInfo.lpVerb = NULL;

shellInfo.lpFile = tempEF;

shellInfo.lpParameters = NULL;
shellInfo.lpDirectory = NULL;
shellInfo.nShow = SW_MAXIMIZE;
shellInfo.hInstApp = NULL;

if(ShellExecuteEx(&shellInfo))
{
        if(!GetExitCodeProcess(shellInfo.hProcess, exitCode))
        {
            DWORD lastError = GetLastError();

            LPTSTR lpMsgBuf;

            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
            QString errorText = ("failed with error: " + QString::number(lastError) + QString::fromWCharArray(lpMsgBuf));
        }
}

I think, the problem is in exitCode argument. 我认为,问题在于exitCode参数。

MSND specifies it as LPDWORD that is pointer for DWORD . MSND将其指定为LPDWORD ,它是DWORD指针。 You should pass valid pointer to the function, so it could dereference it to save exit code here: 您应该将有效指针传递给该函数,因此它可以取消引用它以保存退出代码:

DWORD exitCode;
//....
if(!GetExitCodeProcess(shellInfo.hProcess, &exitCode))

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

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