Supervisor received unexpected message - is it possible to catch kill message inside Test.Server or Supervisor?

Is it possible to catch :kill signal ?

defmodule Test.Application do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    children = [
      worker(Test.Server, [], restart: :transient),
    ]

    opts = [strategy: :one_for_one, name: __MODULE__]
    Supervisor.start_link(children, opts)
  end
end
defmodule Test.Server do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def init(:ok) do
    Process.flag(:trap_exit, true)
    {:ok, %{}}
  end

  def handle_info({:EXIT, _pid, _reason}, state) do
    IO.puts "exit"
    {:noreply, state}
  end

  def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
    IO.puts "down"
    {:noreply, state}
  end

  def terminate(_reason, _state) do
    IO.puts "terminate"
  end
end
iex(1)> Process.exit(Process.whereis(Test.Server), :foo) 
exit
true
iex(2)> Process.exit(Process.whereis(Test.Server), :shutdown)
exit
true
iex(3)> Process.exit(Process.whereis(Test.Server), :normal)  
exit
true
iex(4)> Process.exit(Process.whereis(Test.Server), :kill)  
true

If I create a Process.monitor inside Test.Server.init:

  def start_link do
    {:ok, pid } = GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
    Process.monitor(pid)
    {:ok, pid}
  end

I’ve got the following message: [error] Supervisor received unexpected message: {:DOWN, #Reference<0.0.4.241>, :process, #PID<0.121.0>, :killed}

Can anyone explain if is it possible to catch kill message inside Test.Server or Supervisor and when is :kill signal is produced ( right now I want to reproduce a crash and restore state of a gen_server, I try to kill process via iex or :observer)

Thanks,

1 Like

Any suggestions ?!

1 Like

@alexandrubagu: Please take a look at &GenServer.terminate/2 docs.

I read it then it’s an old post :slight_smile: Thanks