[R] Debugging a hanging function within R

Duncan Murdoch murdoch at stats.uwo.ca
Fri Nov 16 15:16:25 CET 2007


On 11/16/2007 6:58 AM, Yan Wong wrote:
> Hi,
> 
> I have an R program which takes several days to run, and sometimes  
> hangs while running, presumably stuck in some sort of loop within a  
> package function. I don't know where in the program code it is  
> hanging: it is likely to be within a routine that is iterated many  
> hundreds of thousands of times, each time with different random  
> numbers used.
> 
> I'd like to debug the R code, but I can't simply set a breakpoint on  
> the function, as it works fine for the first n-thousand times. What  
> I'd really like to do is to interrupt the running program once it has  
> hung, then step into the function, examining the variables as I go.
> 
> I can't seem to find a way to do this (i.e. interrupt a routine at an  
> arbitrary time during its run, then step into it using the debugger).  
> Is it possible?
> 
> Apologies if this is answered in the manuals, but I've had a trawl  
> through and can't seem to find how to do it. I have tried attaching  
> to the process using gdb, but then don't know how to issue gdb  
> commands to invoke the R debugger in the stopped R session.
> 
> Thanks


If you prepare in advance by using options(error=recover), it's easy:

 > options(error=recover)
 > f <- function() {
+  i <- 0
+  repeat {
+     i <- i + 1
+     x <- rnorm(10000)
+  }
+ }
 > f()

# At this point, R appears hung up.  I hit Esc in the Windows Rgui.  In 
Unix or Rterm, you'd use Ctrl-C.

Enter a frame number, or 0 to exit

1: f()

Selection: 1
Called from: eval(expr, envir, enclos)
Browse[1]> ls()
[1] "i" "x"
Browse[1]> i
[1] 426
Browse[1]>

Duncan Murdoch



More information about the R-help mailing list