summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorbruvzg <7645683+bruvzg@users.noreply.github.com>2022-01-28 08:30:01 +0200
committerbruvzg <7645683+bruvzg@users.noreply.github.com>2022-01-28 08:30:01 +0200
commit99a1e552acebef5db9794fbc17e7658acc660e64 (patch)
tree14fdff01a2e97da8783b3d203baad2cd1b1a6b53
parente6caaf4c800912517af783e90519cc2a70001e85 (diff)
[Windows] Disable console I/O redirection, if it's already redirected to the pipe or file.
-rw-r--r--platform/windows/os_windows.cpp22
1 files changed, 15 insertions, 7 deletions
diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index 41ba1092db..d844531071 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -83,15 +83,23 @@ static String format_error_message(DWORD id) {
return msg;
}
+void RedirectStream(const char *p_file_name, const char *p_mode, FILE *p_cpp_stream, const DWORD p_std_handle) {
+ const HANDLE h_existing = GetStdHandle(p_std_handle);
+ if (h_existing != INVALID_HANDLE_VALUE) { // Redirect only if attached console have a valid handle.
+ const HANDLE h_cpp = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(p_cpp_stream)));
+ if (h_cpp == INVALID_HANDLE_VALUE) { // Redirect only if it's not already redirected to the pipe or file.
+ FILE *fp = p_cpp_stream;
+ freopen_s(&fp, p_file_name, p_mode, p_cpp_stream); // Redirect stream.
+ setvbuf(p_cpp_stream, nullptr, _IONBF, 0); // Disable stream buffering.
+ }
+ }
+}
+
void RedirectIOToConsole() {
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
- FILE *fpstdin = stdin;
- FILE *fpstdout = stdout;
- FILE *fpstderr = stderr;
-
- freopen_s(&fpstdin, "CONIN$", "r", stdin);
- freopen_s(&fpstdout, "CONOUT$", "w", stdout);
- freopen_s(&fpstderr, "CONOUT$", "w", stderr);
+ RedirectStream("CONIN$", "r", stdin, STD_INPUT_HANDLE);
+ RedirectStream("CONOUT$", "w", stdout, STD_OUTPUT_HANDLE);
+ RedirectStream("CONOUT$", "w", stderr, STD_ERROR_HANDLE);
printf("\n"); // Make sure our output is starting from the new line.
}