How write posix waitpid() analog for windows?

2020-07-25 03:54发布

I want to port my linux code to windows. I don't want use cygwin or mingw. I would like to do this via WinApi. So who can help me to write waitpid() analog under windows?

标签: c++ c winapi posix
2条回答
在下西门庆
2楼-- · 2020-07-25 04:05

You can use WaitForSingleObject if you have a process handle. You should have obtained that when creating the child process.

查看更多
Fickle 薄情
3楼-- · 2020-07-25 04:09

CreateProcess the way to create a new process. Its output is PROCESS_INFORMATION structure. WaitForSingleObject could wait for the end of the process.

Here is the example from MSDN library (GetExitCodeProcess was added.):

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    DWORD exit_code = 0;

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

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // 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( "CreateProcess failed (%d)\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Get exit code
    GetExitCodeProcess( pi.hProcess, &exit_code );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}
查看更多
登录 后发表回答