Raffi
Raffi

Reputation: 107

Check if child process is alive (Windows, C++)

When I start a program (Windows, C++) using

intptr_t childHandle=_spawnvp( _P_NOWAIT, "program.exe", argv );

it returns an intptr_t. From the documentation:

"The return value from an asynchronous _spawnvp or _wspawnvp (_P_NOWAIT or _P_NOWAITO specified for mode) is the process handle."

But I can't find how to use intptr_t childHandle to check whether the process is still alive.

Upvotes: 0

Views: 617

Answers (1)

The Techel
The Techel

Reputation: 873

You can use the WinAPI function GetExitCodeProcess, because _spawnvp returns a native handle value:

#include <iostream>
#include <cassert>
#include <process.h>
#include <Windows.h>

int main()
{
    const char *argv[] = { "cmd.exe", "/C", "exit", nullptr };
    HANDLE handle = HANDLE(_spawnvp(_P_NOWAIT, "cmd.exe", argv));
    assert(handle != 0);

    DWORD exit_code;
    do
    {
        assert(GetExitCodeProcess(handle, &exit_code) != 0);
        if(exit_code == STATUS_PENDING)
            std::cout << "Alive ...\n";
        
        Sleep(1000);
    }
    while(exit_code == STATUS_PENDING);

    std::cout << "Done\n";
}

Upvotes: 1

Related Questions