Joe Half Face
Joe Half Face

Reputation: 2333

I can't fire terminate callback on exiting iex -S mix

I have an application, which uses Application module, and also has an GenServer instance running. This GenServer module has a terminate callback.

The callback works fine if I force some error happen inside server instance, but doesn't fire if I abort the iex -S mix session using Ctrl-C a or by just closing console window (it should write into some file).

I've tried putting this in init():

Process.flag(:trap_exit, true)

and also calling stop/1 in the main module:

def stop(state) do
  IO.puts "something" #never shown
  GenServer.stop(pid) #doesn't seem to work
end

Upvotes: 0

Views: 226

Answers (1)

Sheharyar
Sheharyar

Reputation: 75820

From Saša Jurić’s post:

There is no way of catching abrupt BEAM OS process exits from within. It's a self-defining property: the BEAM process terminates suddenly, so it can't run any code (since it terminated)

Hence, if BEAM is brutally terminated, the callback will not be invoked.

So one solution is to not exit the session using Ctrl-C. Instead, you can try calling :init.stop which should gracefully shut down the supervision tree.

Upvotes: 2

Related Questions