Recently I was writing a nif about quic, when nif call ‘load’ function I initialized some global variables, when the VM shutdown need to release these global variables. It seems that this can only be done with nif ‘unload’ function, but this function is called when the VM is shutdown or the module is upgraded, but the code that releases global variables needs to be executed only when the VM is shutdown. But don’t know how to judge calling ‘unload’ is being called from the VM shutdown.
Looks like you’re interested in On-halt and delayed halt support for NIFs by rickard-green · Pull Request #6370 · erlang/otp · GitHub (which, in turn, is triggered with erts halt may crash the emulator when dirty NIFs are still running · Issue #5325 · erlang/otp · GitHub).
Unfortunately it’s in the master branch, so target is OTP 26.
It seemed to answer my needs with the on_halt function .
If it’s only memory you want to release at VM shutdown, then don’t bother. It’s just a waste of CPU, as the OS will do that much more efficient for us when the beam terminates. The VM itself does not waste time releasing any of its allocated memory before shutdown.
The problem is that not only memory,
the nif nifload opens up some other configuration and then if nifload does something wrong, must have to clean up the open configuration before
it return otherwise core dump happens,
and I’m afraid have a similar problem when the VM shutdown. So I think it’s better to have a cleanup function.
You could install an atexit
callback when loading the NIF and do this cleanup in the callback.
The caveat with atexit
, VM is still running (and calling functions, working with shared objects) when atexit is called. What we ran into, if we use atexit
to free resources, other schedulers that are still running cause SIGSEGV as soon as atexit
freed up resources.
I’ll try it when that pr merges