Skip to content

Instantly share code, notes, and snippets.

@hubertlepicki
Last active May 18, 2017 07:45
Show Gist options
  • Save hubertlepicki/fed0af104bf582de0708c434b215e98f to your computer and use it in GitHub Desktop.
Save hubertlepicki/fed0af104bf582de0708c434b215e98f to your computer and use it in GitHub Desktop.
Gracefully shut down the process tree with name registration
defmodule ParentServer do
use GenServer
import Supervisor.Spec
def start_link() do
GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end
def init(_) do
Process.flag(:trap_exit, true)
children = [
worker(ChildServer, [])
]
{:ok, child_supervisor_pid} = Supervisor.start_link(children, strategy: :one_for_one, name: ChildSupervisor)
IO.puts("Started Supervisor")
IO.puts("Started #{__MODULE__}:")
{:ok, nil}
end
def terminate(reason, state) do
IO.puts("Terminating #{__MODULE__}")
# This works! Uncomment this line and run the script with no error!
# GenServer.stop(ChildSupervisor)
:normal
end
end
defmodule ChildServer do
use GenServer
def start_link() do
GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end
def init(_) do
Process.flag(:trap_exit, true)
IO.puts("Started #{__MODULE__}:")
{:ok, nil}
end
def terminate(reason, state) do
IO.puts("Terminating #{__MODULE__}")
:normal
end
end
for i <- 1..1000 do
{:ok, parent_pid} = ParentServer.start_link()
GenServer.stop(parent_pid)
# Uncommenting this out sorts out registration problem
# :timer.sleep(10)
end
$ elixir gracefully_shutdown_process_tree.exs
...
Started Elixir.ChildServer:
Started Supervisor
Started Elixir.ParentServer:
Terminating Elixir.ParentServer
Terminating Elixir.ChildServer
** (EXIT from #PID<0.71.0>) an exception was raised:
** (MatchError) no match of right hand side value: {:error, {:already_started, #PID<0.81.0>}}
gracefully_shutdown_process_tree.exs:16: ParentServer.init/1
(stdlib) gen_server.erl:328: :gen_server.init_it/6
(stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment