From a222d7beb2552fe913c86c39c55833ed184dbad6 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Fri, 12 Apr 2024 09:15:13 +0300 Subject: [PATCH] builtin: implement an `at_exit(cb)` wrapper for C.atexit (part 1) (#21254) --- vlib/builtin/builtin.c.v | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/vlib/builtin/builtin.c.v b/vlib/builtin/builtin.c.v index 81afa2ec84..afe7a28bc5 100644 --- a/vlib/builtin/builtin.c.v +++ b/vlib/builtin/builtin.c.v @@ -32,6 +32,23 @@ pub fn exit(code int) { C.exit(code) } +// at_exit registers a fn callback, that will be called at normal process termination. +// It returns an error, if the registration was not successful. +// The registered callback functions, will be called either via exit/1, +// or via return from the main program, in the reverse order of their registration. +// The same fn may be registered multiple times. +// Each callback fn will called once for each registration. +pub fn at_exit(cb FnExitCb) ! { + $if freestanding { + return error('at_exit not implemented with -freestanding') + } $else { + res := C.atexit(cb) + if res != 0 { + return error_with_code('at_exit failed', res) + } + } +} + // panic_debug private function that V uses for panics, -cg/-g is passed // recent versions of tcc print nicer backtraces automatically // Note: the duplication here is because tcc_backtrace should be called directly