title: How to use WaitForSingleObject
body: <p>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&nbsp;ms)</p>
  
  <p>First process:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;windows.h&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  void main()
  {
      bool ret;
      bool retwait;
  
      STARTUPINFO startupinfo;
      GetStartupInfo (&amp;startupinfo);
  
      PROCESS_INFORMATION pro2info;
  
      wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA1PRO2.exe";
  
      ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
                          NULL, &amp;startupinfo, &amp;pro2info);
  
      cout&lt;&lt;"hProcess: "&lt;&lt;pro2info.hProcess&lt;&lt;endl;
      cout&lt;&lt;"dwProcessId: "&lt;&lt;pro2info.dwProcessId &lt;&lt;endl;
  
      if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true)
          cout&lt;&lt;"waitprocess:true"&lt;&lt;endl; //The process is finished
      else
          cout&lt;&lt;"waitprocess:false"&lt;&lt;endl;
  
      CloseHandle (pro2info.hProcess);//prozesshandle schließen, "verliert connection"
  
      if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true) //When the process has finished
          cout&lt;&lt;"waitprocess:true"&lt;&lt;endl;
      else
          cout&lt;&lt;"waitprocess:false"&lt;&lt;endl;
  
      //cout&lt;&lt;GetLastError()&lt;&lt;endl; //Output the last error.
  
      ExitProcess(0);
  }
  </code></pre>
  
  <p>Second process:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;windows.h&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  void main()
  {
      int b;
  
      b = GetCurrentProcessId();
  
      cout &lt;&lt; b &lt;&lt; endl;
      cout &lt;&lt; "Druecken Sie Enter zum Beenden" &lt;&lt; endl;
      cin.get();
          //Wait until the user confirms
  
      Sleep (700);
      ExitProcess(0);
  
      cout&lt;&lt;"test";
  }
  </code></pre>
  
  <p>The first process prints false, false ; but it should print true, false.</p>
  
  <p>Instead of the if-else statement, I used this:</p>
  
  <pre><code>//switch(WaitForSingleObject (pro2info.hProcess, INFINITE)){
      //    case WAIT_OBJECT_0: cout &lt;&lt; "ja";
      //        break;
      //    case WAIT_FAILED:cout &lt;&lt; "nein";
      //        break;
      //    case WAIT_TIMEOUT:
      //        break;
      //}
  //    cout&lt;&lt;"waitprocess:true"&lt;&lt;endl;//prozess ist fertig
  //else
  //    cout&lt;&lt;"waitprocess:false"&lt;&lt;endl;
  </code></pre>
  
  <p>And this seems to work. What did I do wrong with my <code>if-else</code> statement?</p>