From ross at biostat.ucsf.edu  Tue Feb 20 22:44:16 2007
From: ross at biostat.ucsf.edu (Ross Boylan)
Date: Tue, 20 Feb 2007 13:44:16 -0800
Subject: [Rd] "try"ing to understand condition handling (interrupts)
In-Reply-To: <Pine.LNX.4.64.0702201312050.30864@nokomis.stat.uiowa.edu>
References: <20070219224141.GA21040@wheat.betterworld.us>
	<Pine.LNX.4.64.0702200725490.1805@gannet.stats.ox.ac.uk>
	<20070220174113.GB5871@wheat.betterworld.us>
	<Pine.LNX.4.64.0702201312050.30864@nokomis.stat.uiowa.edu>
Message-ID: <20070220214416.GD5871@wheat.betterworld.us>

[resequencing and deleting for clarity]
On Tue, Feb 20, 2007 at 01:15:25PM -0600, Luke Tierney wrote:
> On Tue, 20 Feb 2007, Ross Boylan wrote:
> >>>P.S. Is there any mechanism that would allow one to trap an interrupt,
> >>>like a ctl-C,  so that if the user hit ctl-C some state would be
> >>>changed but execution would then continue where it was?  I have in
> >>>mind the ctl-C handler setting a "time to finish up" flag which the
> >>>maini code checks from time to time.
> 
> >On Tue, Feb 20, 2007 at 07:35:51AM +0000, Prof Brian Ripley wrote:
...

> >>I quess 'ctl-C' is your private abbreviation for 'control C' (and
> >>not a
[yes, ctl-C = control C, RB]
> >>type of cancer): that generates an interrrupt in most (but not all) R
> >>ports.  Where it does, you can set up interrupt handlers (as the help page
> >>said)
> >>
> >My P.S. concerned whether the code that was interrupted could continue
> >from the point of interruption.  As far as I can tell from ?tryCatch
> >there is not,
> 
> Currently interrupts cannot be handled in a way that allows them to
> continue at the point of interruption.  On some platforms that is not
> possible in all cases, and coming close to it is very difficult.  So
> for all practical purposes only tryCatch is currently useful for
> interrupt handling.  At some point disabling interrupts will be
> possible from the R level but currently I believe it is not.
> 
> Best,
> 
> luke
I had suspected that, since R is not thread-safe, handling
asynchronous events might be challenging.

I tried the following experiment on Linux:

> h<-function(e) print("Got You!")
> f<-function(n, delay) for (i in seq(n)) {Sys.sleep(delay); print(i)}
> withCallingHandlers(f(7,1), interrupt=h)
[1] 1
[1] "Got You!"

So in this case the withCallingHandlers acts like a tryCatch, in that
control does not return to the point of interruption.  However,
sys.calls within h does show where things were just before the
interrupt:
> h<-function(e) {print("Got You!"); print(sys.calls());}
> withCallingHandlers(f(7,1), interrupt=h)
[1] 1
[1] 2
[1] 3
[1] "Got You!"
[[1]]
withCallingHandlers(f(7, 1), interrupt = h)

[[2]]
f(7, 1)

[[3]]
Sys.sleep(delay)

[[4]]
function (e)
{
    print("Got You!")
    print(sys.calls())
}(list())


Ross



[Rd] "try"ing to understand condition handling (interrupts)
Ross Boylan