title: Forcing Code in Ruby on Windows when X button is hit
body: <p>While writing a ruby script on Windows (ruby -v outputs ruby 1.9.3p545) I encountered an interesting and rather specific problem. I was attempting to close an opened file if a user terminates execution. For example,</p>
  
  <pre><code>begin
  f = File.open("monkeys.txt", "w+")
  #stuff with the file
  rescue Exception =&gt; e #I know this is a bad idea
  puts e.backtrace
  ensure
  f.close
  end
  </code></pre>
  
  <p>Now, this works if I terminate execution via Ctrl+C while running this in cmd. However, when I hit the "X" on the cmd prompt window, the code in the ensure block doesn't run. I tried something like...</p>
  
  <pre><code>at_exit do
  f.close if !f.closed?
  end
  </code></pre>
  
  <p>...but that still doesn't execute the code I want it to when the X button is hit. 
  So, what do I do in order to force "ensure" code in Ruby if it's closed via that X button?</p>