The Server

When you learn how to write gen_servers in Erlang, you eventually learn about the (now optional) callback terminate/2 . That callback is described as the opposite of init/2 in the sense that, while init/2 is used to initialize your server and setup everything that it needs to run, terminate/2 is called when the server dies and therefore it’s used to clean up and tear down what was started/created on init/2 .

To give you an example, let’s create a very simple server…

As you can see there, the server logs something on init/2 and then logs something else when terminate/2 is called. Let’s see it in action…

1> maybe_server:start_link().

{ok,<0.1986.0>} =INFO REPORT==== 25-Sep-2017::23:08:00 ===

Server <0.1986.0> starting.

2> maybe_server:stop().

ok =INFO REPORT==== 25-Sep-2017::23:08:05 ===

Server <0.1986.0> terminating with reason normal

3>

Perfect. So far, everything works as expected.

The Supervisor

But gen_servers are usually not alone, they tend to live in supervision trees. So, let’s add a supervisor!

I’m using a small trick here: Since supervisor:stop/1 does not exist I’m using gen_server:stop/1 to stop the supervisor because I know supervisors are implemented as gen_servers. Trust me: it doesn’t affect anything I’m about to show you… or don’t trust me and stop your supervisor in your own way ;)

In any case, let’s see what happens when we run this…

3> maybe_sup:start(). =INFO REPORT==== 25-Sep-2017::23:26:00 ===

Server <0.3453.0> starting.

{ok,<0.3452.0>}

4> maybe_sup:stop().

ok

5> is_process_alive(<0.3452.0>).

false

6>

Where is our terminate message? As you can see, terminate/2 is not evaluated anymore.