[plt-scheme] ports and garbage collection

From: Daniel Silva (daniel.silva at gmail.com)
Date: Sun Nov 21 14:48:24 EST 2004

It doesn't have to be ugly :-)

With a function:

(module using-port-fn mzscheme
  (require (lib "contract.ss"))
  
  (define (using-port port proc)
    (define (cleanup) (close-input-port port))
    (begin0
      (parameterize ([current-input-port port])
        (with-handlers ([void (lambda (e)
                                (cleanup)
                                (raise e))])
          (proc)))
      (close-input-port port)))
  
  (provide/contract [using-port (input-port? (-> any/c) . -> . any/c)]))

....
  
(using-port (post-pure-port url query)  read-xml)


Or with a macro:

(module using-port-stx mzscheme
  (require (lib "contract.ss"))
  
  (define-syntax (using-port stx)
    (syntax-case stx ()
      [(_ port exprs ...)
       #`(begin
           (define the-port port) ;; only evaluate port expr once
           (define (cleanup) (close-input-port the-port))
           (begin0
             (parameterize ([current-input-port the-port])
               (with-handlers ([void (lambda (e)
                                       (cleanup)
                                       (raise e))])
                 exprs ...))
             (close-input-port port)))]))
  
  (provide using-port))

....

(using-port (post-pure-port url query)
   (read-xml))


Daniel

On Sat, 20 Nov 2004 19:13:47 -0500, Doug Orleans <dougo at place.org> wrote:
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> 
> I've been using code like this to make a bunch of XML queries via HTTP POST:
> 
>   (read-xml (post-pure-port url query))
> 
> Now suddenly I get a "host not found" error, and then "Too many open
> files" when I try to open a file to save data.  I thought ports
> were closed when garbage collected, but apparently not.  How come?
> It seems tedious to have to close ports manually:
> 
>   (let ((in (post-pure-port url query)))
>     (begin0 (read-xml in)
>             (close-input-port in)))
> 
> but maybe I'm just spoiled.
> 
> --dougo at place.org
>


Posted on the users mailing list.