title: GenerateConsoleCtrlEvent crashes when child process is cmd
body: <p>I'm trying to wrap basic windows process functionalities in a Process Class.
  I want the processes to run in the same process group and same console of the parent, and I want to kill them gently when I call Process::Kill();</p>
  
  <p>Reading from various sources I've ended up with this code, which first checks if the process is a GUI, if so sends a WM_CLOSE (the EnumChildWindowsHandler does it), if not, and the process has a console, sends a CTRL_C event. It works, but when the child Process is the "cmd.exe" the procedure crashes on the GenerateConsoleCtrlEvent function and the debugger says an access violation on write happened.</p>
  
  <p>What's the point? What didn't I understand in my readings?</p>
  
  <pre><code>bool Process::Kill( ) {  
    // Here I check if the process is a GUI app  
    if (!EnumThreadWindows(mChildInfo-&gt;dwThreadId, EnumChildWindowsHandler,  mChildInfo-&gt;dwProcessId)) {
      if (WaitForSingleObject(mChildInfo-&gt;hProcess, 2000) == WAIT_TIMEOUT) {
        { TerminateProcess(mChildInfo-&gt;hProcess, 0); }  }
  
    //If not, test if it's a CUI then send CTRL_C
    else { 
      int minPid = 10;
      int els;
      unsigned long *pids = new unsigned long(minPid);
      els =  GetConsoleProcessList( pids, minPid );
      if (els &gt; minPid) {
        free (pids);
        pids = new unsigned long(els);
        els = GetConsoleProcessList(pids, els);
      }
  
      if (find(pids, pids+els, mChildInfo-&gt;dwProcessId)) {
        cout &lt;&lt; "Sending CTRL_C_EVENT.." &lt;&lt; endl;
  
        SetConsoleCtrlHandler(NULL, TRUE);
        GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
        if (WaitForSingleObject(mChildInfo-&gt;hProcess, 2000) == WAIT_TIMEOUT) { TerminateProcess(mChildInfo-&gt;hProcess, 0); }
        SetConsoleCtrlHandler(NULL, FALSE);  
  
        CloseHandle(mChildInfo-&gt;hProcess);
        CloseHandle(mChildInfo-&gt;hThread);
      } 
      return true;   
    }
  </code></pre>
  
  <p>EDIT: I've found the ReactOS cmd.exe source code which is gold for this sort of thing.  I'll post updates from what I eventually learn.
  Url: <a href="http://doxygen.reactos.org/db/d4f/base_2shell_2cmd_2cmd_8c_source.html" rel="nofollow">http://doxygen.reactos.org/db/d4f/base_2shell_2cmd_2cmd_8c_source.html</a></p>