0

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
Sheharyar
  • 73,588
  • 21
  • 168
  • 215
Joe Half Face
  • 2,303
  • 1
  • 17
  • 45
  • See this: [Graceful Shutdown of GenServer](http://stackoverflow.com/questions/39756769/graceful-shutdown-of-genserver) – Sheharyar Apr 02 '17 at 00:59

1 Answers1

2

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.

Community
  • 1
  • 1
Sheharyar
  • 73,588
  • 21
  • 168
  • 215