extension in c, close file when script ends, rb_io_fptr_finalize

  • Thread starter Alexander Fleck
  • Start date
A

Alexander Fleck

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.
 
B

Brian Candler

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top