1

我想要执行通用命令的非阻塞方式,我想在它开始执行命令后检查进程的状态,但我注意到 WaitForSingleObject 返回的不是 WAIT_TIMEOUT,即使进程仍在执行命令. 我没有在 WaitForSingleObject() 中使用 INFINITE 标志,因为我需要执行与检查其他进程的状态相关的其他任务。

#include <stdio.h>
#include <process.h>
#include <errno.h>
#include <windows.h>
#include <warning.h>


void main() {
wchar_t* cmd = wcsdup(L"C:\\Users\\test_sample.bat");
STARTUPINFO si;
PROCESS_INFORMATION pi;

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

if (!CreateProcess(NULL,        /* No module name (use command line) */
    cmd,        /* 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("GetLastError: %d \t strerror: %s\n", GetLastError(), strerror(GetLastError()));
    return -1;
}

/* We are in the parent process. */
for (;;)
{
    int dev = WaitForSingleObject(pi.hProcess, 0);

    /* Check whether the child process is still alive.  */
    //IS THIS CODE CORRECT? FOR PROCESS COMPLETETION CHECK
    // sometimes we get WAIT_OBJECT_0 even when process is not finished.
    if (dev != WAIT_TIMEOUT) 
        break;

    Sleep(1000);
    printf("Command execution in progress");
}

    DWORD dwExitCode = 0;
    GetExitCodeProcess(pi.hProcess, &dwExitCode);
    printf("exit code : %d", dwExitCode);
}

以下是上述程序的代码,这是检查子进程是否完成的正确方法吗?

if (dev != WAIT_TIMEOUT) 
    break;

有时我们会从 WaitForSingleObject 获得 WAIT_OBJECT_0,即使进程没有完成。这是预期的吗?

test_sample.bat

timeout /t 100 /nobreak
exit 2
4

0 回答 0