Gracefully terminating a program

Suppose I have a Scala program that iterates through a long sequence of tests and then computes and prints statistical results. The full sequence of tests may take a long time to run, so I want to be able to terminate it early and still have the results printed out. Control-C terminates the entire program immediately, which is not what I want. When I send the signal, I want the current test to run to completion (or perhaps terminate immediately), then I want to break out of the loop and print the results for the completed tests. What are the options for doing something like that? Thanks.

Example of sbt using jline for console and handling ctl-c is at this source.

JLine3 exception is this one.

Thanks for that information. This graceful termination capability is not something that I need, but it would be nice to have.

I came up with a scheme using the presence of a particular file to signal that the program should be terminated gracefully at the end of the current test in the sequence. To use it, I go to another terminal and “touch” (create) the file.

The file signalling method works well enough, but it would be more convenient to be able to use control-C or something like it. However, I am concerned about using control-C because then I won’t have a way to abort the program immediately if I need it. Is it possible to define another signal, such as control-x or something like that to terminate gracefully?