We are writing an R package, the core of which is written in C++ and basically consists of one long-running loop:
void core_func(double* data)
{
while (!
Update: the easiest approach is to call C++ via Rcpp and check via Rcpp::checkUserInterrupt
. This automatically raises an exception if a interrupt is pending. See section 2.4 of rcpp attributes.
Original answer: R allows for checking for SIGINT via the C API:
R_CheckUserInterrupt();
However this function will immediately jump back to the console if an interruption is pending which can leave your C/C++ code in an undefined state.
A trick suggested by Simon Urbanek is to use the following wrapper code:
/* Check for interrupt without long jumping */
void check_interrupt_fn(void *dummy) {
R_CheckUserInterrupt();
}
int pending_interrupt() {
return !(R_ToplevelExec(check_interrupt_fn, NULL));
}
You can now call pending_interrupt()
to check if an interruption is pending and deal with it yourself, e.g. raise some special C++ exception or simply return intermediate results. Make sure you read Simon's comments in the post to understand the consequences of this approach.
I have personally only used this via C to interrupt downloads in the curl package. Perhaps you can search metacran for examples that use R_CheckUserInterrupt
from C++.