c++ - WaitForSingleObject 不等待进程结束

标签 c++ winapi process win32-process waitforsingleobject

我想等待进程执行(calc.exe)结束,但它不起作用。 我的程序很快完成,而我的进程(calc.exe)继续运行(我没有停止它)。

WaitForSingleObject 立即返回 WAIT_OBJECT_0。

ps:我禁用了我的防病毒软件 (AVIRA)

int main(int argc, char** arv)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

const char * calcPrgm = "C:\\\\Windows\\System32\\calc.exe";
LPSTR calcPrgmLpstr = const_cast<LPSTR>(calcPrgm);

// Start the child process. 
if (!CreateProcess(NULL,   // No module name (use command line)
    calcPrgmLpstr,        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory 
    &si,            // Pointer to STARTUPINFO structure
    &pi)           // Pointer to PROCESS_INFORMATION structure
    )
{
    printf("CreateProcess failed (%d).\n", GetLastError());
    return -1;
}

// Wait until child process exits.
auto ret = WaitForSingleObject(pi.hProcess, INFINITE);
printf("WaitForSingleObject ret = %x\n", ret);
if (ret == WAIT_OBJECT_0)
{
    printf("WaitForSingleObject ret ret == WAIT_OBJECT_0\n");
}
BOOL b = FALSE;
DWORD n = 0;
b = GetExitCodeProcess(pi.hProcess, &n);

// Close process and thread handles. 
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
printf("WaitForSingleObject end\n");
return 0;
}

最佳答案

我发现了错误。 “calc.exe”在退出之前创建另一个进程。我在主“Sleep(60 * 1000);”中使用 1 行代码创建/调用了自己的程序。现在好了:)

关于c++ - WaitForSingleObject 不等待进程结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51674939/

相关文章:

c++ - linux:有没有办法找出哪个进程生成了核心文件?

c# - visual C# 是否有可能比进程运行的进度条有更多的反馈?

c++ - 是否可以在不调用 QApplication::exec() 的情况下创建本地事件循环?

c++ - 格式良好的类定义示例,其中包含编译器删除的默认特殊成员函数

c++ - 对友好 URL 的 POST 请求失败

winapi - 何时(以及如何)布置 Win32 窗口的子窗口以响应大小调整?

c++ - 我如何转发声明已经过 typedef 的类?

c++ - 我在 C++11 中使用 atomic_compare_exchange_strong 还是 atomic_exchange?

c++ - 如何创建一个单选按钮并查看它是否被选中?

android - 在不同的进程中运行 Android 服务是否会导致相同的堆限制?