Skip to content

How to perform package cleanup when R session is ending?

4 messages · Jiefei Wang, Bill Dunlap

#
Hi,

I am looking for a way to clean up my package resources before R is ended.
It looks like the .onUnload function would not be helpful as it would not
be called before R is ended. This behavior has been described in the
document:

*Note that packages are not detached nor namespaces unloaded at the end of
an R session unless the user arranges to do so (e.g., via .Last).*

I have also searched for ?.Last as the document says. However, the .Last
function is for the end user to use, not for the package developers, so I
am clueless now. How to clean up my package before R ends? Any suggestions?

Best,
Jiefei
#
Have you tried using reg.finalizer(..., onexit=TRUE)?

-BIll
On Fri, Dec 18, 2020 at 7:29 AM Jiefei Wang <szwjf08 at gmail.com> wrote:

            

  
  
#
E.g., as in a package containing just the following R code:

$ cat testFinalizer/R/zzz.R
envir <- new.env()
cleanup <- function(e) {
    message("cleanup(", format(e), ")")
    if (!isTRUE(envir$cleaned)) {
        message("    cleaning ", format(e))
        envir$cleaned <- TRUE
    } else {
        # cleanup previously called by .onUnload()
        message("    ", format(e), " has already been cleaned")
    }
}
.onLoad <- function(libname, pkgname) {
    message("Loading ", pkgname, " from ", libname)
    reg.finalizer(e=envir, f=cleanup, onexit=TRUE)
    message("Installed finalizer for ", format(envir))
}
.onUnload <- function(libpath) {
    message("Unloading ", libpath)
    cleanup(envir)
}

This gives:

$ R --quiet
Loading testFinalizer from /home/bill/packages/lib
Installed finalizer for <environment: 0x55a558b16120>
Unloading /home/bill/packages/lib/testFinalizer
cleanup(<environment: 0x55a558b16120>)
    cleaning <environment: 0x55a558b16120>
cleanup(<environment: 0x55a558b16120>)
    <environment: 0x55a558b16120> has already been cleaned
$ R --quiet
Loading testFinalizer from /home/bill/packages/lib
Installed finalizer for <environment: 0x55f8dac2d598>
character(0)
cleanup(<environment: 0x55f8dac2d598>)
    cleaning <environment: 0x55f8dac2d598>

On Fri, Dec 18, 2020 at 7:39 AM Bill Dunlap <williamwdunlap at gmail.com>
wrote:

  
  
#
Thank you! This solution works! I actually tried reg.finalizer but it
didn't work when it is a part of the package code,
so I thought this is not the right function. Your example is very helpful.
Putting the function inside the package
initializer makes the finalizer works as I wish. Not sure why it behaves
differently when in different locations but
this is good enough for me. Many thanks!

Best,
Jiefei

On Sat, Dec 19, 2020 at 1:09 AM Bill Dunlap <williamwdunlap at gmail.com>
wrote: