1
votes

I am reading the Little Elixir and OTP Guidebook to learn elixir, there is a chapter in the book in which the author builds a Supervisor from scratch. There is a part where the author implements a function to terminate the Supervisor process which in turn also terminates all the child processes linked to it before terminating itself.

As far as I understand if you have processes linked to a particular process and if one of them is killed then all of them are killed right? So why do we need to kill all the child procs before killing the supervisor, is it just a best practice?

This is what the book says btw

Before you terminate the supervisor process, you need to terminate all the children it’s linked to, which is handled by the terminate_children/1 private function,

defmodule ThySupervisor do
use GenServer
######################
# Callback Functions #
######################
def terminate(_reason, state) do
terminate_children(state)
:ok
end
#####################
# Private Functions #
#####################
defp terminate_children([]) do
:ok
end
defp terminate_children(child_specs) do
child_specs |> Enum.each(fn {pid, _} -> terminate_child(pid) end)
end
defp terminate_child(pid) do
Process.exit(pid, :kill)
:ok
end
end
1

1 Answers

2
votes

if you have processes linked to a particular process and if one of them is killed then all of them are killed

TL;DR: there is no magic, OTP does it, but if you decide to re-implement OTP, you are, well, to re-implement it :)


There is no such thing as a linked process in vacuum. Erlang VM takes care of passing messages back and forth, that is. Everything else is done by the client code. E. g. with Process.monitor/1 (which simple delegates to :erlang.monitor/1,) one might ask the VM “please tell me when this process will die.”

But under the hood, all these links are established by the Elixir (which in the vast majority of cases delegates to Erlang/OTP.) Supervision trees are a core of the fault-tolerant paradigm, that’s why all the code was written once decades ago and now we might use the higher level of abstraction, thinking in terms like “processes are linked.”