【问题标题】:WaitForSingleObject doesn't wait the end of the process [duplicate]WaitForSingleObject 不等待进程结束[重复]
【发布时间】:2018-11-25 16:59:43
【问题描述】:

我想等待进程执行结束 (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;
}

【问题讨论】:

  • 好的,我看到你从 MSDN docs.microsoft.com/en-gb/windows/desktop/ProcThread/… 解除了这个问题,所以它无法创建进程吗? getlasterror 返回什么,retWAIT_OBJECT_0 是什么?
  • 这当然是工作。 calc.exe 已退出。但在此之前它执行Calculator.exe
  • WaitForSingleObjectWAIT_OBJECT_0 返回pi.hProcess - 进程真的退出了。你没有考虑到你查看了另一个进程
  • 要等待一系列进程,请使用Job object。默认情况下,当父进程产生子进程时,子进程会被添加到父进程所属的同一个 Job 中。因此,创建一个 Job,将 calc.exe 进程添加到其中,然后等待 Job。当calc.exeCalculator.exe 都退出时,作业将发出信号。见How do I wait until all processes in a job have exited?

标签: c++ winapi process win32-process waitforsingleobject


【解决方案1】:

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

【讨论】:

  • calc.exe 不需要一分钟就可以生成一个新的自身实例。无论如何,您的“解决方案”不是一个好的解决方案,而是一个逃避问题的解决方案。 Remy 在 cmets 中给了你一个很好的解决方法。
猜你喜欢
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
相关资源
最近更新 更多