diff --git a/app/main.cpp b/app/main.cpp index f3d5360f4..fe10f949f 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -559,16 +559,19 @@ int main(int argc, char *argv[]) s_SuppressVerboseOutput = true; #endif #ifdef Q_OS_WIN32 - // Attach to the console to be able to print output. - // Since we're a /SUBSYSTEM:WINDOWS app, we won't be attached by default. + // If we don't have stdout or stderr handles (which will normally be the case + // since we're a /SUBSYSTEM:WINDOWS app), attach to our parent console and use + // that for stdout and stderr. + // + // If we do have stdout or stderr handles, that means the user has used standard + // handle redirection. In that case, we don't want to override those handles. if (AttachConsole(ATTACH_PARENT_PROCESS)) { - HANDLE conOut = GetStdHandle(STD_OUTPUT_HANDLE); - if (conOut != INVALID_HANDLE_VALUE && conOut != NULL) { + // If we didn't have an old stdout/stderr handle, use the new CONOUT$ handle + if (IS_UNSPECIFIED_HANDLE(oldConOut)) { freopen("CONOUT$", "w", stdout); setvbuf(stdout, NULL, _IONBF, 0); } - HANDLE conErr = GetStdHandle(STD_ERROR_HANDLE); - if (conErr != INVALID_HANDLE_VALUE && conErr != NULL) { + if (IS_UNSPECIFIED_HANDLE(oldConErr)) { freopen("CONOUT$", "w", stderr); setvbuf(stderr, NULL, _IONBF, 0); } @@ -762,5 +765,12 @@ int main(int argc, char *argv[]) // sometimes freezing and blocking process exit. QThreadPool::globalInstance()->waitForDone(30000); +#ifdef Q_OS_WIN32 + // Without an explicit flush, console redirection for the list command + // doesn't work reliably (sometimes the target file contains no text). + fflush(stderr); + fflush(stdout); +#endif + return err; }