建立進程

CreateProcess函式會建立與建立程式無關的新進程。 為了簡單起見,此關聯性稱為父子關聯性。

下列程式碼示範如何建立程式。

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

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

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

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

如果 CreateProcess 成功,它會傳回包含新進程及其主要執行緒控制碼和識別碼 的PROCESS_INFORMATION 結構。 執行緒和進程控制碼是使用完整存取權限所建立,不過,如果您指定安全性描述元,您可以限制存取。 當您不再需要這些控制碼時,請使用 CloseHandle 函式加以關閉

您也可以使用 CreateProcessAsUserCreateProcessWithLogonW 函式來建立進程。 這些函式可讓您指定執行進程之使用者帳戶的安全性內容。