Martin Morgan
2011-Jul-22 04:29 UTC
[Rd] reg.finalizer and connection gc -- which runs when (and why)?
With this set-up options(warn = 1) tf <- tempfile() finalizer <- function(obj) { message("finalizer") close(obj$f) } this code works ev <- new.env() ev$f <- file(tf, "w") reg.finalizer(ev, finalizer) rm(ev) gc() whereas this (reversing the order of file() and reg.finalizer()) ev <- new.env() reg.finalizer(ev, finalizer) ev$f <- file(tf, "w") rm(ev) produces > gc() Warning: closing unused connection 3 (/tmp/Rtmp9CWLtN/file6998ee7b) finalizer Error in close.connection(obj$f) : invalid connection In some respects, it seems like the user should get a chance to clean up their mess before the system does it for them, so the above seems like a bug. But maybe there is another way to understand this? Martin -- Computational Biology Fred Hutchinson Cancer Research Center 1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109 Location: M1-B861 Telephone: 206 667-2793
luke-tierney at uiowa.edu
2011-Jul-22 13:05 UTC
[Rd] reg.finalizer and connection gc -- which runs when (and why)?
Connections use finalizers for cleanup. Once finalizers become eligible to run, the order in which they are run is unspecified. If you want to be sure yours runs first then you need to make sure the connection one doesn't become eligible to run until yours has. Best, luke On Thu, 21 Jul 2011, Martin Morgan wrote:> With this set-up > > options(warn = 1) > tf <- tempfile() > finalizer <- function(obj) { > message("finalizer") > close(obj$f) > } > > this code works > > ev <- new.env() > ev$f <- file(tf, "w") > reg.finalizer(ev, finalizer) > rm(ev) > gc() > > whereas this (reversing the order of file() and reg.finalizer()) > > ev <- new.env() > reg.finalizer(ev, finalizer) > ev$f <- file(tf, "w") > rm(ev) > > produces > >> gc() > Warning: closing unused connection 3 (/tmp/Rtmp9CWLtN/file6998ee7b) > finalizer > Error in close.connection(obj$f) : invalid connection > > In some respects, it seems like the user should get a chance to clean up > their mess before the system does it for them, so the above seems like a bug. > But maybe there is another way to understand this? > > Martin >-- Luke Tierney Statistics and Actuarial Science Ralph E. Wareham Professor of Mathematical Sciences University of Iowa Phone: 319-335-3386 Department of Statistics and Fax: 319-335-3017 Actuarial Science 241 Schaeffer Hall email: luke at stat.uiowa.edu Iowa City, IA 52242 WWW: http://www.stat.uiowa.edu
Seemingly Similar Threads
- proper use of reg.finalizer to close connections
- Finalizer execution order question
- reg.finalizer(): Multiple finalizers?
- reg.finalizer(): Is it safe for the finalizer function to attach/load a package?
- The finalizer of the externalPtr does not work when closing R?