共用方式為


建立進程

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 函式來建立進程。 這些函式可讓您指定進程執行所在的用戶帳戶安全性內容。