kuanyui
kuanyui

Reputation: 781

Ruby + Curses: Non-blocking getch() + Trap for Ctrl+c?

I want to use Curses in Ruby:

  1. getch() cannot block/suspend the program.
  2. When pressing q , exit the program immediately.
  3. A trap for Ctrl-C to avoid interruption.

However, I just can done the first point:

  1. When press q, it would wait for a while (< 1 sec) before exit.
  2. It seems that Curses makes the trap for Ctrl-C not work at all...
# -*- coding: utf-8 -*-
require "curses"

Curses.init_screen
Curses.noecho()
Curses.curs_set(0)              #invisible cursor
Curses.timeout = 0
Curses.addstr("Press [q] to abort")
sec=0
while true

  # if place this outside the while loop, q key will be unable to work
  # at all...
  if Curses.getch == 'q'
    Curses.close_screen         #seems unnecessary
    exit
  end

  sec += 1
  hello = "Hello World #{sec}"
  Curses.setpos(Curses.lines / 2, Curses.cols / 2 - (hello.length / 2))
  Curses.addstr(hello)
  Curses.refresh
  sleep 1
end

# Avoid C-c interruption, but Curses seems to ignore it.
Signal.trap(:INT){
  return nil
}

Upvotes: 1

Views: 962

Answers (1)

user
user

Reputation: 25738

When press q, it would wait for a while (< 1 sec) before exit.

You should combine unresponsive sleep with blocking input:
Set timeout = 1000 and remove sleep 1.

If this is not what you want, then you need multithreading.

A trap for Ctrl-C to avoid interruption.

You can use Curses.raw() to switch to raw mode, where all input will be transfered to you directly, without automatic handling of Ctrl+C and such.

Upvotes: 1

Related Questions