c++cwinapiprocess

Using return value of _spawnl() to get PID?


The documentation for the _spawn family of functions say they return a HANDLE when called with _P_NOWAIT.

I was hoping to use this handle with TerminateProcess(h, 1);

(In case the started process misbehaves.)

HANDLE h = (HANDLE) _spawnl(_P_NOWAIT, "C:\\temp\\hello.exe", NULL);

However, I don't understand the difference between these handles and the PID shown in the Task Manager.

The spawn function only ever returns very low values, like "248" and not what actually shows in Task Manager.

Can I use the return value of _spawn to kill a process and if so, how?


Solution

  • This did the trick:

    // _P_NOWAIT tells _wspawnv to return with a HANDLE
    HANDLE process_handle = (HANDLE)_wspawnv(_P_NOWAIT, argv[1], &argv[1]);
    
    if (-1 == process_handle)
    {
        printf("Could not start %s\n", argv[1]);
    
        return;
    }
    
    DWORD procID = GetProcessId(process_handle); // the number as seen in Task Manager
    

    thanks sj95126