+# Stuff to be done at begin such as setting the exit status
+# and signal handlers
+def do_at_begin
+ status = Status.new
+ status.set
+ exit_status = "OK"
+
+ # Install signal handlers
+ %w( INT TERM QUIT ).each do |signal|
+ Signal.trap(signal) do
+ exit_status = signal
+ exit
+ end
+ end
+
+ exit_status
+end
+
+# Make sure that file streams are closed, tmpdir removed, and
+# exit status is written to log file.
+def do_at_exit(exit_status)
+ at_exit do
+ begin
+ @in.close if @in.respond_to? :close
+ @out.close if @out.respond_to? :close
+ rescue Exception => exception
+ $stderr.puts "Exception caught!" # DEBUG
+ case exit_status
+ when 'INT' then exit_status = 'INTERRUPTED'
+ when 'TERM' then exit_status = 'TERMINATED'
+ end
+ exit_status = "DIED" unless exit_status =~ /INT|TERM|QUIT/
+ $stderr.puts exit_status
+ $stderr.puts exception.backtrace
+
+ ensure
+ status = Status.new
+ FileUtils.remove_entry_secure(status.get_tmpdir)
+ status.log(exit_status)
+ status.delete
+ puts "EXIT STATUS: #{exit_status}"
+ end
+ end
+end
+
+exit_status = do_at_begin
+do_at_exit(exit_status)
+
+