From seth at userprimary.net  Thu Nov 15 06:08:53 2007
From: seth at userprimary.net (Seth Falcon)
Date: Wed, 14 Nov 2007 21:08:53 -0800
Subject: [Rd] isOpen on closed connections
In-Reply-To: <473B0739.3090507@jhsph.edu> (Roger D. Peng's message of "Wed\,
	14 Nov 2007 09\:33\:29 -0500")
References: <473B0739.3090507@jhsph.edu>
Message-ID: <m2hcjoksd6.fsf@userprimary.net>

"Roger D. Peng" <rpeng at jhsph.edu> writes:

> As far as I can tell, 'isOpen' cannot return FALSE in the case when 'rw = ""'. 
> If the connection has already been closed by 'close' or some other function, 
> then isOpen will produce an error.  The problem is that when isOpen calls 
> 'getConnection', the connection cannot be found and 'getConnection' produces an 
> error.  The check to see if it is open is never actually done.

I see this too with R-devel (r43376) {from Nov 6th}.

    con = file("example1", "w")
    isOpen(con)

    [1] TRUE

    showConnections()

      description class  mode text   isopen   can read can write
    3 "example1"  "file" "w"  "text" "opened" "no"     "yes"    

    close(con)
    isOpen(con)

    Error in isOpen(con) : invalid connection

    ## printing also fails
    con
    Error in summary.connection(x) : invalid connection

> This came up in some code where I'm trying to clean up connections after 
> successfully opening them.  The problem is that if I try to close a connection 
> that has already been closed, I get an error (because 'getConnection' cannot 
> find it).  But then there's no way for me to find out if a connection has 
> already been closed.  Perhaps there's another approach I should be taking?  The 
> context is basically,
>
> con <- file("foo", "w")
>
> tryCatch({
> 	## Do stuff that might fail
> 	writeLines(stuff, con)
> 	close(con)
>
> 	file.copy("foo", "bar")
> }, finally = {
> 	close(con)
> })

This doesn't address isOpen, but why do you have the call to close
inside the tryCatch block?  Isn't the idea that finally will always be
run and so you can be reasonably sure that close gets called once?

If your real world code is more complicated, perhaps you can make use
of a work around like:

myIsOpen = function(con) tryCatch(isOpen(con), error=function(e) FALSE)

You could do similar with myClose and "close" a connection as many
times as you'd like :-)

+ seth

-- 
Seth Falcon | seth at userprimary.net | blog: http://userprimary.net/user/



[Rd] isOpen on closed connections
Seth Falcon