R interrupt call

I have a generic function to catch all the exceptions included in my package logR::tryCatch2 , defined as:

 tryCatch2 <- function(expr){ V=E=W=M=I=NULL e.handler = function(e){ E <<- e NULL } w.handler = function(w){ W <<- c(W, list(w)) invokeRestart("muffleWarning") } m.handler = function(m){ attributes(m$call) <- NULL M <<- c(M, list(m)) } i.handler = function(i){ I <<- i NULL } V = suppressMessages(withCallingHandlers( tryCatch(expr, error = e.handler, interrupt = i.handler), warning = w.handler, message = m.handler )) list(value=V, error=E, warning=W, message=M, interrupt=I) } 

As you can see in the last line, it returns a list that is more or less described independently.
This makes the real response to exceptions delayed after calling tryCatch2 simple !is.null :

 f = function(){ warning("warn1"); warning("warn2"); stop("err") } r = tryCatch2(f()) if(!is.null(r$error)) cat("Error detected\n") # Error detected if(!is.null(r$warning)) cat("Warning detected, count", length(r$warning), "\n") # Warning detected, count 2 

It works as expected, I can react with my own code. But in some cases, I would like to not stop the interrupt process, which is also caught. At the moment, it seems to me that I need to add an additional parameter to tryCatch2 , which will control if interrupts should be catchy or not. So the question asks about some invokeInterrupt function that I could use as follows:

 g = function(){ Sys.sleep(60); f() } r = tryCatch2(g()) # interrupt by pressing ctrl+c / stop while function is running! if(!is.null(r$interrupt)) cat("HERE I would like to invoke interrupt\n") # HERE I would like to invoke interrupt 

I think that if R is able to catch one, he should also be able to call him. How can I achieve invokeInterrupt functionality?

+6
r try-catch
Sep 28 '15 at 10:14
source share
1 answer

I can offer a partial solution based on the tools package.

 invokeInterrupt <- function() { require(tools) processId <- Sys.getpid() pskill(processId, SIGINT) } 

However, remember that pskill interrupt signal ( SIGINT ) is not very reliable. I did some tests, sending an exception and catching it using your function, for example:

 will_interrupt <- function() { Sys.sleep(3) invokeInterrupt() Sys.sleep(3) } r = tryCatch2(will_interrupt()) 

In linux, this works well when executed from the R command line. In windows, the R and R Gui command closed when this code was executed. There is even worse: on Linux and Windows, this code instantly crashed Rstudio ...

So, if your code needs to be run from the R command line on Linux, this solution should be fine. Otherwise, you might be out of luck ...

+3
Oct 20 '15 at 23:14
source share



All Articles