Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use WaitForSingleObject

Tags:

c++

windows

In order to try out how to program with the Win32 API, I wrote a program that creates a process. Then I want to check if my process waits for the newly created process, close the handle and then check WaitForSingleObject again (the second process is sleeping for 700 ms)

First process:

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

Second process:

#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";
}

The first process prints false, false ; but it should print true, false.

Instead of the if-else statement, I used this:

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

And this seems to work. What did I do wrong with my if-else statement?

like image 264
Tyzak Avatar asked Mar 31 '10 15:03

Tyzak


1 Answers

You really need to pay attention to the meaning for the return value of the API functions. You cannot ignore a FALSE return from CreateProcess(). WaitForSingleObject() can return several values, it returns 0 if the wait completed successfully. Which makes you print "false".

like image 101
Hans Passant Avatar answered Nov 08 '22 06:11

Hans Passant