c++ - ShellExecuteEx & GetExitCodeProcess - 处理无效或段错误

标签 c++ qt segmentation-fault shellexecuteex

我正在尝试启动一个应用程序,然后监视它直到它关闭。我在使用 ShellExecuteEX 和 GetExitCodeProcess 时遇到了几个问题。

下面的代码在调用 GetExitCodeProcess 时会导致段错误。如果我更改 shellInfo.fMask = NULL,它不会出现段错误,但我会收到一条错误消息,提示无效句柄。

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));
        }
}

最佳答案

我认为,问题出在 exitCode 参数中。

MSND 将其指定为 LPDWORD,即 DWORD 的指针。您应该将有效指针传递给该函数,以便它可以取消引用它以在此处保存退出代码:

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

关于c++ - ShellExecuteEx & GetExitCodeProcess - 处理无效或段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16572655/

相关文章:

c - Realloc 段错误 - 无效的旧大小

c - 从文件读取单词时出现段错误

c++ - 当对象被分配给一个新对象时,对象会调用它们的析构函数吗?

c++ - 在屏幕上绘制点

c++ - 如何将 boost 库链接到我的项目?

c++ - 如何在 QGraphicsScene 中放置 QFrame?

c - 加载文件时出现段错误(核心转储)

c++ - valgrind 是否检测到 OpenGL 内存泄漏?

c++ - 设置结构边界框值

xcode - 如何使用 ‘xcode-select’设置事件的开发人员目录以进行Qt安装?