Skip to content

Commit

Permalink
Don't clobber existing std handles when attaching to the parent console
Browse files Browse the repository at this point in the history
Fixes #1270
  • Loading branch information
cgutman committed May 12, 2024
1 parent aa33432 commit 9117f65
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions app/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
}

0 comments on commit 9117f65

Please sign in to comment.