2010-03-31 3 views
5

Win32 API로 프로그래밍하는 방법을 배우기 위해 프로세스를 만드는 프로그램을 작성했습니다. 내 프로세스가 새롭게 생성 과정을 기다리는 경우 은 그 때 나는 핸들을 닫고WaitForSingleObject 사용 방법

우선 처리 (두 번째 과정은 700   ms 동안 자고) 다시의 WaitForSingleObject를 점검, 확인하고 싶은 :

#include <iostream> 
#include <windows.h> 
#include <string> 

using namespace std; 

void main() 
{ 
    bool ret; 
    bool retwait; 

    STARTUPINFO startupinfo; 
    GetStartupInfo (&startupinfo); 

    PROCESS_INFORMATION pro2info; 

    wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA1PRO2.exe"; 

    ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL, 
         NULL, &startupinfo, &pro2info); 

    cout<<"hProcess: "<<pro2info.hProcess<<endl; 
    cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl; 

    if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true) 
     cout<<"waitprocess:true"<<endl; //The process is finished 
    else 
     cout<<"waitprocess:false"<<endl; 

    CloseHandle (pro2info.hProcess);//prozesshandle schließen, "verliert connection" 

    if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true) //When the process has finished 
     cout<<"waitprocess:true"<<endl; 
    else 
     cout<<"waitprocess:false"<<endl; 

    //cout<<GetLastError()<<endl; //Output the last error. 

    ExitProcess(0); 
} 

두 번째 프로세스 :

#include <iostream> 
#include <windows.h> 
#include <string> 

using namespace std; 

void main() 
{ 
    int b; 

    b = GetCurrentProcessId(); 

    cout << b << endl; 
    cout << "Druecken Sie Enter zum Beenden" << endl; 
    cin.get(); 
     //Wait until the user confirms 

    Sleep (700); 
    ExitProcess(0); 

    cout<<"test"; 
} 

첫 번째 프로세스는 false, false를 인쇄합니다. 그러나 true, false를 출력해야합니다.

//switch(WaitForSingleObject (pro2info.hProcess, INFINITE)){ 
    // case WAIT_OBJECT_0: cout << "ja"; 
    //  break; 
    // case WAIT_FAILED:cout << "nein"; 
    //  break; 
    // case WAIT_TIMEOUT: 
    //  break; 
    //} 
// cout<<"waitprocess:true"<<endl;//prozess ist fertig 
//else 
// cout<<"waitprocess:false"<<endl; 

그리고이 작동하는 것 같다 : 대신 IF-else 문의

, 나는이를 사용했다. 내 if-else 성명서에서 무엇이 잘못 되었습니까?

답변

16

당신 정말 API 함수의 반환 값의 의미에주의를 지불해야합니다. CreateProcess()로부터의 FALSE 리턴은 무시할 수 없습니다. WaitForSingleObject()는 여러 값을 반환 할 수 있으며 대기가 성공적으로 완료되면 0을 반환합니다. 그러면 "거짓"으로 인쇄하게됩니다.

5

에 따르면 MSDN, WaitForSingleObject은 대기가 중단되지 않은 경우 WAIT_OBJECT_0을 반환합니다. 문서를 확인하면 WAIT_OBJECT_0의 값은 0x00000000L이되며, 일반적으로 이 아닌 false으로 변환 된 값이됩니다. 따라서 비교가 실패합니다.

WaitForSingleObject에서 bool으로 반환 값을 올리는 것은 잠깐 만료 된 이유를 나타내는 몇 가지 잠재적 인 비 0 반환 코드를 얻는다고 생각하면 좋은 생각이 아닙니다.

여전히 부울 검사를 사용하여 위의 코드를 유지하려면 테스트를 !WaitForSingleObject(...)으로 변경하십시오.

2

귀하의 질문에 답변을 드렸습니다. 요점은 WaitForSingleObjecttrue 또는 false을 반환하지 않지만 WAIT_OBJECT_0 등을 반환한다는 것입니다.

그래서 대신

if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true) 

당신은

if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==WAIT_OBJECT_0)