Fixed SDL_Log not working on windows if the output is being redirected.
authorOlli Kallioinen <olli.kallioinen@iki.fi>
Mon, 04 Dec 2017 19:28:03 +0200
changeset 1172119f948dc5620
parent 11720 9cbb45a5874f
child 11722 27dd67e1c5eb
Fixed SDL_Log not working on windows if the output is being redirected.
src/SDL_log.c
     1.1 --- a/src/SDL_log.c	Mon Dec 04 20:21:52 2017 -0800
     1.2 +++ b/src/SDL_log.c	Mon Dec 04 19:28:03 2017 +0200
     1.3 @@ -303,7 +303,7 @@
     1.4  }
     1.5  
     1.6  #if defined(__WIN32__) && !defined(HAVE_STDIO_H) && !defined(__WINRT__)
     1.7 -/* Flag tracking the attachment of the console: 0=unattached, 1=attached, -1=error */
     1.8 +/* Flag tracking the attachment of the console: 0=unattached, 1=attached to a console, 2=attached to a file, -1=error */
     1.9  static int consoleAttached = 0;
    1.10  
    1.11  /* Handle to stderr output of console. */
    1.12 @@ -326,6 +326,7 @@
    1.13          BOOL attachResult;
    1.14          DWORD attachError;
    1.15          unsigned long charsWritten; 
    1.16 +        DWORD consoleMode;
    1.17  
    1.18          /* Maybe attach console and get stderr handle */
    1.19          if (consoleAttached == 0) {
    1.20 @@ -350,9 +351,15 @@
    1.21                      /* Newly attached */
    1.22                      consoleAttached = 1;
    1.23                  }
    1.24 -			
    1.25 +
    1.26                  if (consoleAttached == 1) {
    1.27                          stderrHandle = GetStdHandle(STD_ERROR_HANDLE);
    1.28 +
    1.29 +                        if (GetConsoleMode(stderrHandle, &consoleMode) == 0) {
    1.30 +                            /* WriteConsole fails if the output is redirected to a file. Must use WriteFile instead. */
    1.31 +                            OutputDebugString(TEXT("Console ouput is being redirected\r\n"));
    1.32 +                            consoleAttached = 2;
    1.33 +                        }
    1.34                  }
    1.35          }
    1.36  #endif /* !defined(HAVE_STDIO_H) && !defined(__WINRT__) */
    1.37 @@ -374,6 +381,11 @@
    1.38                          OutputDebugString(TEXT("Insufficient heap memory to write message\r\n"));
    1.39                      }
    1.40                  }
    1.41 +
    1.42 +        } else if (consoleAttached == 2) {
    1.43 +            if (!WriteFile(stderrHandle, output, lstrlenA(output), &charsWritten, NULL)) {
    1.44 +                OutputDebugString(TEXT("Error calling WriteFile\r\n"));
    1.45 +            }
    1.46          }
    1.47  #endif /* !defined(HAVE_STDIO_H) && !defined(__WINRT__) */
    1.48