1

我正在创建一个流程CreateProcess

  • 带旗帜CREATE_NO_WINDOW | CREATE_BREAKAWAY_FROM_JOB | CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
  • InheritHandles参数 =TRUE
  • startupinfo 标准输出和标准错误文件重定向 ( STARTF_USESTDHANDLES)
  • SECURITY_ATTRIBUTES.InheritHandle = TRUE

进程在继续执行时关闭的句柄。

然后我通过获取具有给定 PID 的进程的句柄来检查进程状态:

HANDLE HProcess = OpenProcess( 
       PROCESS_QUERY_INFORMATION , TRUE, task->taskPid);

编辑:是的,我正在检查返回的进程是否真的是我查询的进程:

if ( ( HProcess != NULL ) && ( GetProcessId(HProcess) != requestedPid ) )

无论创建的进程是否真的在运行,我都会得到该进程的有效句柄。如果我重新启动我的应用程序,检查代码将正常工作。我怀疑句柄以某种方式被缓冲,或者创建的进程在同一个组中 - 但我似乎无法在文档中找到任何关于它的信息。

4

2 回答 2

1

There is no guarantee that successfully opening a handle to a process means that the process is still running. So the behaviour you're describing is unsurprising.

Once you've opened a handle, you can easily check whether the process has finished:

DWORD dw = WaitForSingleObject(handle, 0);
if (dw == WAIT_OBJECT_0)
{
    // Process has exited
}

However, your approach is flawed to begin with, because you have no way of telling whether the process ID has been reused. Instead of storing the process ID, store the process handle returned from CreateProcess, and use it to test for process exit as shown.

于 2014-03-20T21:00:28.893 回答
0

虽然这不是一个答案,但它确实可以作为一种解决方法

拥有一个有效的句柄,可以检查该过程是否已完成:

DWORD exitCode = 0;
GetExitCodeProcess(HProcess, &exitCode);
if (exitCode == STILL_ACTIVE ) {
  //task alive (or exited with STILL_ACTIVE :( )
} else {
  //task exited with code exitCode
}
于 2014-03-20T08:56:15.717 回答