Extension in c, close file when script ends, rb_io_fptr_fina

hi,
I wrote an extension that uses a file to handle an external device. The
initialize method opens the file and it then is permanently open. I don’
t
want to open and close it every time I write to it.

I wondered how to finalize the object or to close the file when my
script
ends. Currently the file keeps open and I have an open unused device.

I stumbled over the function ‘rb_io_fptr_finalize’, but I didn’ t find a
real reference which tells me if that’ s what I searched for or not.

Can someone help me or give me further infos?

thanks,
Alex.

On Thu, Mar 08, 2007 at 04:55:11PM +0900, Alexander F. wrote:

I wrote an extension that uses a file to handle an external device. The
initialize method opens the file and it then is permanently open. I don’ t
want to open and close it every time I write to it.

I wondered how to finalize the object or to close the file when my script
ends. Currently the file keeps open and I have an open unused device.

I’d recommend you copy the way that Ruby’s File class does it.

(1) Provide a ‘close’ method on your object, for the user to be able to
explicitly close it when needed.

(2) Provide a block-based method, which does an open / yield / close
sequence

File.open("/etc/passwd") do |f|
  puts f.read
end
# file is now closed at this point

(preferred implementation is to use begin … ensure … end, so that the
close is called even if an exception occurs when the yield is called)

(3) Let the files close themselves when the program exits.

I stumbled over the function ‘rb_io_fptr_finalize’, but I didn’ t find a
real reference which tells me if that’ s what I searched for or not.

As I understand it, finalisers are called when the object is
garbage-collected. However there’s not guarantee that an object will be
garbage-collected at any time before the program exits (and not even
then,
if the user calls ‘exit!’)

However, if it’s just a file, the operating system will close the file
when
the program exits anyway.

B.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs