@@ -265,12 +265,13 @@ TEST_F(ProgramEnvTest, TestExecuteNoWaitDetached) {
265265
266266 if (getenv (" LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED" )) {
267267 sleep_for (/* seconds=*/ 5 );
268-
268+ char *Detached = getenv ( " LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED_TRUE " );
269269#if _WIN32
270- HWND ConsoleWnd = GetConsoleWindow ();
271- if (ConsoleWnd == NULL )
270+ HANDLE StdHandle = GetStdHandle (STD_OUTPUT_HANDLE);
271+
272+ if (Detached && (StdHandle == INVALID_HANDLE_VALUE || StdHandle == NULL ))
272273 exit (100 );
273- else
274+ if (!Detached && (StdHandle != INVALID_HANDLE_VALUE && StdHandle != NULL ))
274275 exit (200 );
275276#else
276277 int ParentSID = std::stoi (
@@ -282,7 +283,6 @@ TEST_F(ProgramEnvTest, TestExecuteNoWaitDetached) {
282283 exit (1 );
283284 }
284285
285- char *Detached = getenv (" LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED_TRUE" );
286286 if (Detached && (ChildSID != ParentSID))
287287 exit (100 );
288288 if (!Detached && (ChildSID == ParentSID))
@@ -297,7 +297,16 @@ TEST_F(ProgramEnvTest, TestExecuteNoWaitDetached) {
297297 Executable, " --gtest_filter=ProgramEnvTest.TestExecuteNoWaitDetached" };
298298 addEnvVar (" LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED=1" );
299299
300- #ifndef _WIN32
300+ #if _WIN32
301+ // Depending on how the test is run it may already be detached from a
302+ // console. Temporarily allocate a new console. If a console already
303+ // exists AllocConsole will harmlessly fail and return false
304+ BOOL AllocConsoleSuccess = AllocConsole ();
305+
306+ // Confirm existence of console
307+ HANDLE StdHandle = GetStdHandle (STD_OUTPUT_HANDLE);
308+ ASSERT_TRUE (StdHandle != INVALID_HANDLE_VALUE && StdHandle != NULL );
309+ #else
301310 pid_t SID = ::getsid (0 );
302311 ASSERT_NE (SID, -1 );
303312 std::string SIDEnvVar =
@@ -332,6 +341,13 @@ TEST_F(ProgramEnvTest, TestExecuteNoWaitDetached) {
332341 ProcessInfo WaitResult = Wait (PI2, std::nullopt , &Error);
333342 ASSERT_EQ (WaitResult.ReturnCode , 200 );
334343 }
344+ #if _WIN32
345+ // If console was allocated then free the console
346+ if (AllocConsoleSuccess) {
347+ BOOL FreeConsoleSuccess = FreeConsole ();
348+ ASSERT_NE (FreeConsoleSuccess, 0 );
349+ }
350+ #endif
335351}
336352
337353TEST_F (ProgramEnvTest, TestExecuteAndWaitTimeout) {
0 commit comments