SW 개발

[win32API] CreateProcess() 를 이용하여 프로세스 끝날때까지 기다리기

. . . 2009. 1. 15. 15:40
반응형
  • 기타사항 : EVC, winCE5 테스트완료. 예제소스코드는 인터넷에서 구한자료.

예제코드

아래의 소스코드로 프로세스가 끝날때까지 기다릴수있다.

STARTUPINFO            sui; 
PROCESS_INFORMATION    pi; 
DWORD                  Ret; 

memset(&sui, 0x00, sizeof(STARTUPINFO)); 
sui.cb = sizeof(STARTUPINFO); 
Ret = CreateProcess(buffer, NULL, NULL, NULL, FALSE, 0, NULL, NULL,&sui, &pi); 

if (Ret)  
{ 
        hProcess = pi.hProcess; 
        WaitForSingleObject(hProcess, 0xffffffff); 
        CloseHandle(hProcess); 
}

위의 소스코드를 이용한 예제소스코드..

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

int main(int argc, char **argv)
{    
    DWORD dwExitCode = 0, dwRet = 0;
    HANDLE hProc[2];
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

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

    //  Child Process 실행

    if( !CreateProcess(NULL, "notepad.exe", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        printf("fail to execute process \n");
        return-1;
    }

    if( GetExitCodeProcess(pi.hProcess, &dwExitCode))
    {
         //   process가 살아 있는 경우, dwExitCode의 값은 STILL_ACTIVE 입니다.

        if( dwExitCode == STILL_ACTIVE )
            printf("process is alive\n");
        else
            printf("exit status(code) : %d\n", dwExitCode);
    }
    else
    {
        printf("errcode : %d\n", GetLastError());
    }    

    hProc[0] = pi.hProcess;    
    dwRet = WaitForMultipleObjects(1, hProc, FALSE, INFINITE);

    //  WaitForMultipleObjects()의 반환값은 시그널된 객체(Process, Thread)의 ID 값이며,
    // 다음과 같은 형태로 어느 객체가 시그널 되어 있는지 확인이 가능합니다.

    if( dwRet == WAIT_OBJECT_0 + 0)
    {

        // 자~~ 이제 Child Process가 종료시에 반환한 값을 확인 !!

        if( GetExitCodeProcess( *(hProc+0), &dwExitCode))
        {            
            printf("exit status(code) : %d\n", dwExitCode);
        }
        else
        {
            printf("errcode : %d\n", GetLastError());
        }
    }

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    return0;
}
반응형