From 2664a24e6a48f49ac81044e3a907a780c65ddaea Mon Sep 17 00:00:00 2001 From: rdb Date: Sun, 2 Dec 2018 20:22:07 +0100 Subject: [PATCH] deploy-ng: fix redirecting GUI app output to log in VC2015/UCRT Fixes #461 --- pandatool/src/deploy-stub/deploy-stub.c | 26 ++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/pandatool/src/deploy-stub/deploy-stub.c b/pandatool/src/deploy-stub/deploy-stub.c index 5ce429335f..12079da46d 100644 --- a/pandatool/src/deploy-stub/deploy-stub.c +++ b/pandatool/src/deploy-stub/deploy-stub.c @@ -264,17 +264,29 @@ static int setup_logging(const char *path, int append) { SetFilePointer(handle, 0, NULL, FILE_END); } - fflush(stdout); - fflush(stderr); - - int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | (append ? _O_APPEND : 0)); SetStdHandle(STD_OUTPUT_HANDLE, handle); - _dup2(fd, 1); - SetStdHandle(STD_ERROR_HANDLE, handle); - _dup2(fd, 2); + // If we are running under the UCRT in a GUI application, we can't be sure + // that we have valid fds for stdout and stderr, so we have to set them up. + // One way to do this is to reopen them to something silly (like NUL). + if (_fileno(stdout) < 0) { + _close(1); + _wfreopen(L"\\\\.\\NUL", L"w", stdout); + } + + if (_fileno(stderr) < 0) { + _close(2); + _wfreopen(L"\\\\.\\NUL", L"w", stderr); + } + + // Now replace the stdout and stderr file descriptors with one pointing to + // our desired handle. + int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | (append ? _O_APPEND : 0)); + _dup2(fd, _fileno(stdout)); + _dup2(fd, _fileno(stderr)); _close(fd); + return 1; #else // Does it start with a tilde? Perform tilde expansion if so.