14.4 Running a Function When a Module is Loaded

The -on_load() directive names a function that is to be run automatically when a module is loaded.

Its syntax is as follows:

  1. -on_load(Name/0).

It is not necessary to export the function. It is called in a freshly spawned process (which terminates as soon as the function returns).

The function must return ok if the module is to become the new current code for the module and become callable.

Returning any other value or generating an exception causes the new code to be unloaded. If the return value is not an atom, a warning error report is sent to the error logger.

If there already is current code for the module, that code will remain current and can be called until the on_load function has returned. If the on_load function fails, the current code (if any) will remain current. If there is no current code for a module, any process that makes an external call to the module before the on_load function has finished will be suspended until the on_load function have finished.

Note

Before OTP 19, if the on_load function failed, any previously current code would become old, essentially leaving the system without any working and reachable instance of the module. That problem has been eliminated in OTP 19.

In embedded mode, first all modules are loaded. Then all on_load functions are called. The system is terminated unless all of the on_load functions return ok.

Example:

  1. -module(m).
  2. -on_load(load_my_nifs/0).
  3.  
  4. load_my_nifs() ->
  5. NifPath = ..., %Set up the path to the NIF library.
  6. Info = ..., %Initialize the Info term
  7. erlang:load_nif(NifPath, Info).

If the call to erlang:load_nif/2 fails, the module is unloaded and a warning report is sent to the error loader.