zakora

zakora

Trying to understand GenServer terminate/2 behavior when trapping exit

Out of curiosity I started to learn how to gracefully shutdown an Elixir application, but I have some trouble understanding the behavior of GenServer terminate/2.

So far I have understood that:

  • calling System.stop(), :init.stop() or c:q() from IEx will properly shutdown the application and the Elixir VM.
  • calling Application.stop(:myapp) from IEx will properly shutdown the application but keep the Elixir VM alive.

If one wants to do some clean-up in a GenServer during the shutdown, one must use Process.flag(:trap_exit, true) in the init/1 of said GenServer and perform the clean-up in terminate/2.

What I am not sure of:
Calling Process.exit(pid, :shutdown) (where pid is the GenServer pid) will effectively send an info message with 'EXIT' to the GenServer but terminate/2 will not be called and the GenServer is still alive.

Is this because the exit signal is not sent from the parent but from IEx?

The documentation states:

terminate/2 is called if a callback (except init/1 ) does one of the following:

What I don’t understand:
Calling Supervisor.stop(Myapp.Supervisor) will call terminate/2 but no info message is received by the GenServer. Since Process.exit(child_pid, :shutdown) is called automatically in this case, I was expecting to also receive an info message.

The documentation states:

The termination happens by sending a shutdown exit signal, via Process.exit(child_pid, :shutdown) , to the child process and then awaiting for a time interval for the child process to terminate.

Example:
The following mix.exs shows that:

  • calling Process.exit(pid, :shutdown) from IEx will not call the GenServer terminate/2, the GenServer is still alive.
  • calling Supervisor.stop(Myapp.Supervisor) from IEx will not send an info message to the GenServer.
defmodule Myapp.MixProject do
  use Mix.Project

  def project do
    [
      app: :myapp,
      version: "0.1.0",
      elixir: "~> 1.7",
      start_permanent: Mix.env() == :prod,
    ]
  end

  def application do
    [
      extra_applications: [:logger],
      mod: {Myapp.Application, []}
    ]
  end
end

defmodule Myapp.Application do
  use Application

  def start(_type, _args) do
    children = [
      {Myapp.Worker, name: Myapp.Worker},
    ]

    opts = [strategy: :one_for_one, name: Myapp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end


defmodule Myapp.Worker do
  use GenServer

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

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

  def handle_call(:ping, _from, state) do
    {:reply, :pong, state}
  end

  def handle_info(msg, state) do
    IO.puts "message received by #{__MODULE__}: #{inspect msg}"
    {:noreply, state}
  end

  def terminate(reason, _state) do
    IO.puts "#{__MODULE__}.terminate/2 called wit reason: #{inspect reason}"
  end
end

Marked As Solved

michalmuskala

michalmuskala

One of the elements of the contract of the OTP special process (and GenServer is such a process) is to die when it receives an EXIT message from parent. That’s what you’re seeing - the parent EXIT message is intercepted by GenServer internals and causes a suicide of the server.

http://erlang.org/doc/design_principles/spec_proc.html

If the special process is set to trap exits and if the parent process terminates, the expected behavior is to terminate with the same reason:

Also Liked

zakora

zakora

Thanks for your answers!

If I understand correctly, the fact that Process.exit(pid, :shutdown) was called from IEx and not the GenServer parent lead to the observed behaviour.

@tty: you are right, I should have written “one can use …”.

tty

tty

If one wants to do some clean-up in a GenServer during the shutdown, one must use Process.flag(:trap_exit, true) in the init/1 of said GenServer and perform the clean-up in terminate/2 .

According to the GenServer docs the one must use Process.flag(:trap_exit, true) in the init/1 is inaccurate. It is one of the 5 possible conditions terminate/2 is called, not the only condition.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement