miniblog.

← Back to all posts
14
I'm implementing an interpreter, and wondering how often I should check for interruptions (e.g. Ctrl-C). I don't want to spend too much CPU time checking whether I've been interrupted, but I also want slow programs to stop promptly. It's tricky.

4 Comments

@wilfredh What does stopping mean? You want to return from the interpreter in an orderly way? If you have a signal handler which sets an atomic book then you can check that pretty cheaply but it depends on what your overall perf goals are.
@wilfredh You could use the setjmp()/longjmp() functions from the signal handler but according to the man page, these are tricky to use without accidentally invoking undefined behaviour. Other than that your best bet is probably to set a volatile sig_atomic_t to 1 in the signal handler and check this variable every 1000 to 1000000 interpreter instructions and hope that your processor is fast enough that this is near instant (which it probably is).