How does -on_load work in erlang?

I don’t seem to understand how the -on_load directive works. In the module I wrote, I have a function to initialize the ets table and populate it with some data. This function works correctly when you call it explicitly. However: I thought it would be nice if the ets table was populated “automatically” when the module was loaded. But this does not work, because ets:info(filesig) tells me "undefined" after loading the module. The corresponding code looks something like this:

 ... -on_load(init/0), init() -> % load filesig database into ETS {_, Signatures} = file:consult("path to a file"), ets:new(filesig, [set, protected, named_table]), ets:insert(filesig, Signatures), ok. ... 

I tested it from erlang shell. Any hints on me, what am I doing wrong?

+4
source share
1 answer

manual says that this code works in a newly created process that exits immediately after the function returns.

The ETS table you created is deleted after the ownership process is complete. This is the standard behavior of ETS. This is what the ets man page says:

Note that there is no automatic garbage collection for tables. Even if there are no table references from any process, it will not be automatically destroyed if the owner process does not stop. It can be destroyed explicitly with delete / 1. The default owner is the process that created the table. The ownership of the table can be transferred to the end of the process using the heir option or explicitly by calling give_away / 3.

+4
source

Source: https://habr.com/ru/post/1438645/


All Articles