I want to press a key at any point, causing the simulation to stop without loosing data collected until that point. I don't know how to do the exit command. Can you give me some examples?
-
@WandMaker That does not save the data. – sawa Dec 01 '15 at 14:53
-
Catching an interrupt, as @user1934428 describes below, is easy. But we can't really help you beyond that that without seeing your actual code. – Jordan Running Dec 01 '15 at 15:38
1 Answers
I think, WandMaker's comment tells only half of the story.
First, there is no general rule, that Control-C will interrupt your program (see the for instance here), but assume that this works in your case (since it will work in many cases):
If I understand you write, you want to somehow "process" the data collected up to this point. This means that you need to intercept the effect of Control-C (which, IF it works as expected, will make the controlling shell deliver a SIGINT), or that you need to interecept the "exit" (since the default behaviour upon receiving a SIGINT would be to exit the program).
If you want to go along the first path, you need to catch the Interrupt
exception; see for example here.
If you want to follow the second route, you need to install an exit handler. Note that it will be called too when the program is exited in the normal way.
If you are unsure, which way is better - and I see no general way to recommend one over the other -, try the first one. There is less chance that you will accidentally ruin something.

- 1
- 1

- 19,864
- 7
- 42
- 87
-
ok, my code is for example this: def countdown(i) return if i.zero? puts i sleep 1 countdown(i-1) end countdown(25) and I want to be able to stop the program... have a one button (S or whatever) and when I press the "S" during the program, it wil stop running. – Jiří Hamr Dec 01 '15 at 17:58
-
`def countdown(i) return if i.zero? puts i sleep 1 countdown(i-1) end countdown(25)` – Jiří Hamr Dec 01 '15 at 18:04
-
If you don't want to intercept SIGINT, as I suggested, you can - inside your loop - check for whether a key has been pressed. There is a good discussion on this topic [here](http://stackoverflow.com/questions/946738/detect-key-press-non-blocking-w-o-getc-gets-in-ruby). Be sure to read the whole thread, because the details depend on which OS you are. – user1934428 Dec 02 '15 at 08:24