[PATCH] Cygwin: console: Fix undesired mode change at exit of non-cygwin apps

Takashi Yano <[email protected]> Tue, 14 Jul 2026 14:59:42 +0900
Newsgroups gmane.os.cygwin.patches
Message-ID <[email protected]>
Previously, if two non-cygwin apps are started and one of them
exits first, the other one loosed appropriate console mode, since
the first one restored it to tty::cygwin. This patch introduce a
counter `non_cygwin_cnt` that counts the number of non-cygwin apps
currently running, and restores console mode only when the last
non-cygwin app exits.

Fixes: 29d8a8300812 ("Cygwin: console: Rearrange set_(in|out)put_mode() calls.")
Signed-off-by: Takashi Yano <[email protected]>
Reviewed-by:
---
 winsup/cygwin/fhandler/console.cc       | 4 ++++
 winsup/cygwin/local_includes/fhandler.h | 1 +
 2 files changed, 5 insertions(+)

diff --git a/winsup/cygwin/fhandler/console.cc b/winsup/cygwin/fhandler/console.cc
index d4c87f29f..474e169ea 100644
--- a/winsup/cygwin/fhandler/console.cc
+++ b/winsup/cygwin/fhandler/console.cc
@@ -841,6 +841,7 @@ fhandler_console::setup ()
       con.num_processed = 0;
       con.curr_input_mode = tty::restore;
       con.curr_output_mode = tty::restore;
+      con.non_cygwin_cnt = 0;
     }
 }
 
@@ -975,6 +976,7 @@ fhandler_console::setup_for_non_cygwin_app ()
      in background, tty settings of the shell is reflected
      to the console mode of the app. So, do not change the
      console mode. */
+  InterlockedIncrement (&con.non_cygwin_cnt);
   if (get_ttyp ()->getpgid () == myself->pgid)
     {
       set_disable_master_thread (true, this);
@@ -987,6 +989,8 @@ void
 fhandler_console::cleanup_for_non_cygwin_app (handle_set_t *p)
 {
   const _minor_t unit = p->unit;
+  if (InterlockedDecrement (&con.non_cygwin_cnt) != 0)
+    return;
   termios dummy = {0, };
   termios *ti = shared_console_info[unit] ?
     &(shared_console_info[unit]->tty_min_state.ti) : &dummy;
diff --git a/winsup/cygwin/local_includes/fhandler.h b/winsup/cygwin/local_includes/fhandler.h
index d11b3ec4f..eafb7c581 100644
--- a/winsup/cygwin/local_includes/fhandler.h
+++ b/winsup/cygwin/local_includes/fhandler.h
@@ -2082,6 +2082,7 @@ class dev_console
   DWORD owner;
   bool is_legacy;
   bool orig_virtual_terminal_processing_mode;
+  LONG non_cygwin_cnt;
 
   WORD default_color, underline_color, dim_color;
 
-- 
2.51.0