Re: WIN32: Spawning a command-line process



Let me add also that before you do any of that AttachConsole() and
freopen() magic, you should of course make sure that stdout actually
is attached to an invalid file handle. (stdout normally is attached to
an invalid file handle in a "GUI".exe that has been started without
redirecting its stdout. Redirection can either be interactive on the
shell command line, or programmatical, for instance through
g_spawn_async_with_pipes().)

I.e., the logic goes something like this:

  if (_get_osfhandle (fileno (stdout)) != -1)
    printf ("Stdout is fine, apparently you have redirected to a file
or pipe.\n");
  else
    {
      int allocated_new_console = FALSE;

      if (!AttachConsole (ATTACH_PARENT_PROCESS))
        {
          if (!AllocConsole ())
            {
              MessageBox (NULL,
                          "Could not either attach to parent's console
or allocate a new console.",
                          "Error",
                          MB_ICONEXCLAMATION|MB_OK);
              exit (1);
            }
          allocated_new_console = TRUE;
        }
      freopen ("CONOUT$", "w", stdout);

      if (allocated_new_console)
        printf ("Could not attach to parent's console, had to allocate
a new one, sorry.\n");
    }

--tml



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]