confucius_007
confucius_007

Reputation: 326

How to use CreateProcess and WaitForSingleObject without INFINITE flag?

I want the non-blocking way of executing a generic command, I want to check the status of the process after it starts execution of the command, But I am noticing that WaitForSingleObject returns other than WAIT_TIMEOUT, even though the process is still executing the command. I am not using the INFINITE flag in WaitForSingleObject() because I need to do other tasks related to checking the status for other processes.

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

Following is the code from the above program, is this a correct way to check if the child process is finished?

if (dev != WAIT_TIMEOUT) 
    break;

Sometimes we get WAIT_OBJECT_0 from WaitForSingleObject even when the process is not finished. Is that expected?

test_sample.bat

timeout /t 100 /nobreak
exit 2

Upvotes: 1

Views: 1781

Answers (0)

Related Questions