1

I have a R script that I have to 'kill' sometimes to stop its execution. But on 'killing' it, the code that does the cleanup(closing connections, etc.) is not executed. How can I make sure the cleanup code is executed no matter how the script is stopped.

My script is myTest.R:

print("script called")

Sys.sleep(20)

.Last<-function()
{
 print("Last called")
}

I start the R script from command line:

> Rscript myTest.R

If I wait for 20 seconds, the .Last function is called.

Now sometimes I have to interrupt the execution of script by calling:

kill -USR1 pid

where pid is the process id. This call is documented here: http://stat.ethz.ch/R-manual/R-devel/library/base/html/Signals.html

This kills the process but the .Last function is not called. but the documentation says it should be called. What am I missing here. Help please. Oh and I am running it on Linux.

Thanks

umbersar
  • 1,821
  • 3
  • 24
  • 34
  • 1
    The packages `fork` and `mulicore` might offer some insight (http://stackoverflow.com/questions/9122261/recursively-kill-r-process-with-children-in-linux) and (cran.r-project.org/web/packages/fork/fork.pdf), specifically in definition of `.Last` function which is the last step of execution – Silence Dogood Aug 12 '14 at 07:32
  • What is the script and how are you running it (`source`, from the command line, etc.)? – Thomas Aug 12 '14 at 13:02
  • thanks. I have documented the question with a sample script and the way I am killing it. I have added reference to relevant help docs as well. Let me know if you need further info. – umbersar Aug 13 '14 at 01:21

2 Answers2

0

You will find all possibilities of error handling in ?conditions. One possibilities being the use of tryCatch that allow you to fail with a defined expression or value:

library(parallel)          
cl <- makeCluster(2)
test <- function(x) {
  2+x
  e <- simpleError("test error")
  stop(e)
}
# I do not stop the connection to the cluster in  test()
tryCatch(test(2), finally = stopCluster(cl))
#but after failing a call to 
stopCluster(cl) #gives,
Error in summary.connection(connection) : invalid connection
# because with tryCatch it fails with closing the connections

However there other possibilities such as withRestart, withCallingHandlers...

BBrill
  • 1,922
  • 17
  • 17
  • Thanks. I should have made myself clear. I have added some more info to the question above. I am not stopping it from the script itself but killing it form command line – umbersar Aug 13 '14 at 01:23
-1

The .Last function needs to be defined before we can send the interrupt to R. So it should be:

print("script called")

.Last<-function()
{
 print("Last called")
} 

Sys.sleep(20)

It works fine now.

umbersar
  • 1,821
  • 3
  • 24
  • 34