From 8fe5bd0052949fbff1029b6b7d65c8aab0cce858 Mon Sep 17 00:00:00 2001 From: YO4 Date: Wed, 25 Sep 2024 22:24:59 +0900 Subject: [PATCH] Wait pty readable if there may be data to read --- lib/yamatanooroti/vterm.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/yamatanooroti/vterm.rb b/lib/yamatanooroti/vterm.rb index 7c29fe2..621f9b5 100644 --- a/lib/yamatanooroti/vterm.rb +++ b/lib/yamatanooroti/vterm.rb @@ -9,6 +9,7 @@ def start_terminal(height, width, command, wait: 0.01, timeout: 2, startup_messa @timeout = timeout @wait = wait @result = nil + @maybe_read = false @pty_output, @pty_input, @pid = PTY.spawn(*command) @pty_output.winsize = [height, width] @@ -41,6 +42,7 @@ def write(str) end end @pty_input.write(str_to_write) + @maybe_read = true # Write str (e.g. `exit`) to pty_input might terminate the process. try_sync end @@ -80,6 +82,7 @@ def close response = @vterm.read begin @pty_input.write(response) + @maybe_read = true if response != nil && response != "" rescue Errno::EIO # In case process terminates suddenly after writing "\e[6n" end @@ -89,7 +92,10 @@ def close private def sync(wait = @wait) sync_until = Time.now + @timeout while @pty_output.wait_readable(wait) - vterm_write(@pty_output.read_nonblock(65536)) + @pty_output.wait_readable(sync_until - Time.now) if @maybe_read + chunk = @pty_output.read_nonblock(65536) + @maybe_read = false + vterm_write(chunk) break if Time.now > sync_until end end