简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM