Skip to content

Commit

Permalink
Add system-level at_exit handlers for safe resource cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
kojix2 committed Jan 11, 2025
1 parent 036d9b7 commit d4d5f87
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/crystal/at_exit_handlers.cr
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# :nodoc:
module Crystal::AtExitHandlers
private class_getter(handlers) { [] of Int32, ::Exception? -> }
private class_getter(internal_handlers) { [] of Int32, ::Exception? -> }

def self.add(handler)
handlers << handler
end

def self.__crystal_add(handler)
internal_handlers << handler
end

def self.run(status, exception = nil)
if handlers = @@handlers
# Run the registered handlers in reverse order
Expand All @@ -19,6 +24,18 @@ module Crystal::AtExitHandlers
end
end

if internal_handlers = @@internal_handlers
# Run the registered internal handlers in reverse order
while handler = internal_handlers.pop?
begin
handler.call status, exception
rescue handler_ex
Crystal::System.print_error "Error running internal at_exit handler: %s\n", handler_ex.message || ""
status = 1 if status.zero?
end
end
end

status
end
end

0 comments on commit d4d5f87

Please sign in to comment.