[Rd] proper use of reg.finalizer to close connections

Murat Tasan mmuurr at gmail.com
Mon Oct 27 02:49:01 CET 2014


Hi all, I have a question about finalizers...
I have a package that manages state for a few connections, and I'd
like to ensure that these connections are 'cleanly' closed upon either
(i) R quitting or (ii) an unloading of the package.
So, in a pared-down example package with a single R file, it looks
something like:

##### BEGIN PACKAGE CODE #####
.CONNS <- new.env(parent = emptyenv())
.CONNS$resource1 <- NULL
.CONNS$resource2 <- NULL
## some more .CONNS resources...

reg.finalizer(.CONNS, function(x) sapply(names(x), disconnect), onexit = TRUE)

connect <- function(x) {
  ## here lies code to connect and update .CONNS[[x]]
}
disconnect <- function(x) {
  print(sprintf("disconnect(%s)", x))
  ## here lies code to disconnect and update .CONNS[[x]]
}
##### END PACKAGE CODE #####

The print(...) statement in disconnect(...) is there as a trace, as I
hoped that I'd see disconnect(...) being called when I quit (or
detach(..., unload = TRUE)).
But, it doesn't appear that disconnect(...) is ever called when the
package (and .CONNS) falls out of memory/scope (and I ran gc() after
detach(...), just to be sure).

In a second 'shot-in-the-dark' attempt, I placed the reg.finalizer
call inside an .onLoad function, but that didn't seem to work, either.

I'm guessing my use of reg.finalizer is way off-base here... but I
cannot infer from the reg.finalizer man page what I might be doing
wrong.
Is there a way to see, at the R-system level, what functions have been
registered as finalizers?

Thanks for any pointers!

-Murat



More information about the R-devel mailing list