Elixir Links & Monitors
Processes are isolated, so a crash in one doesn't corrupt another. But someone usually needs to know about the crash: to restart the worker, to return an error to a client, or to stop everything that depends on it. The BEAM offers two mechanisms.
| Link | Monitor | |
|---|---|---|
| Created with | spawn_link/1, Process.link/1 |
spawn_monitor/1, Process.monitor/1 |
| Direction | bidirectional | one-way (the watcher is told) |
| On abnormal exit | the other process is killed too (unless it traps exits) | the watcher receives a :DOWN message |
| Used by | supervisors, groups of processes that must live and die together | clients that call a server, Task.await |
Exit reasons
Every process ends with an exit reason. :normal means the function simply returned. Anything else, such as an exception or exit(:boom), is an abnormal exit.
Monitors: get a message when a process dies
{pid, ref} = spawn_monitor(fn -> exit(:disk_full) end)
IO.inspect(is_pid(pid))
receive do
{:DOWN, ^ref, :process, ^pid, reason} -> IO.puts("worker stopped: #{inspect(reason)}")
end
{_pid2, ref2} = spawn_monitor(fn -> :finished_fine end)
receive do
{:DOWN, ^ref2, :process, _pid, reason} -> IO.puts("second worker: #{inspect(reason)}")
endtrue
worker stopped: :disk_full
second worker: :normal
The :DOWN message contains the monitor reference, the PID and the reason. Pinning ^ref makes sure we handle the notification for this monitor. A normal exit also sends :DOWN, with the reason :normal.
Monitoring with Process.monitor/1
You can monitor any existing process. If the process is already dead when you start monitoring, you get the :DOWN message right away with the reason :noproc:
worker = spawn(fn -> receive do: (:stop -> :ok) end)
ref = Process.monitor(worker)
send(worker, :stop)
receive do
{:DOWN, ^ref, :process, _, reason} -> IO.puts("1st: #{inspect(reason)}")
end
ref = Process.monitor(worker) # it's dead already
receive do
{:DOWN, ^ref, :process, _, reason} -> IO.puts("2nd: #{inspect(reason)}")
end1st: :normal
2nd: :noproc
Links: share a fate
A link ties two processes together. If one exits abnormally, the exit signal travels along the link and the other one exits too, with the same reason. To see this without killing the script itself, we start a small "group" process that links to a worker:
group =
spawn(fn ->
spawn_link(fn -> exit(:worker_failed) end)
Process.sleep(:infinity)
end)
ref = Process.monitor(group)
receive do
{:DOWN, ^ref, :process, _, reason} -> IO.puts("group died too: #{inspect(reason)}")
endgroup died too: :worker_failed
The group was just sleeping, yet it died, because its linked worker exited with :worker_failed. This "all or nothing" behaviour is exactly what you want for processes that cannot work without each other.
Trapping exits
A process can trap exits: incoming exit signals are then converted into ordinary {:EXIT, pid, reason} messages instead of killing it. This is how supervisors survive the crashes of their children:
Process.flag(:trap_exit, true)
worker = spawn_link(fn -> exit(:timeout) end)
receive do
{:EXIT, ^worker, reason} -> IO.puts("caught exit: #{inspect(reason)}")
end
ok_worker = spawn_link(fn -> :done end)
receive do
{:EXIT, ^ok_worker, reason} -> IO.puts("caught exit: #{inspect(reason)}")
end
IO.puts("the script is still alive")caught exit: :timeout
caught exit: :normal
the script is still alive
Note:
Process.exit(pid, :kill)sends an exit signal that cannot be trapped. It is the last resort for stopping a stuck process; the reason seen by linked processes is:killed.
"Let it crash"
In many languages you defend against every possible error with try blocks. In Elixir, the idiomatic approach for unexpected errors is different:
- Write the happy path clearly.
- Let the process crash when something unexpected happens.
- Have a supervisor (linked, trapping exits) restart it in a known good state.
Expected errors (invalid user input, a missing file) are still handled with {:error, reason} tuples. "Let it crash" is for the bugs and rare failures you didn't anticipate.
Test yourself
What does a monitoring process receive when the monitored process exits?
- An exception
- A
{:DOWN, ref, :process, pid, reason}message - Nothing, unless it is linked
- An
{:EXIT, pid, reason}message
Process A is linked to B and does not trap exits. B exits with reason :boom. What happens to A?
- Nothing
- A receives a :DOWN message
- A exits with reason
:boomtoo - A restarts B
Which statement about monitors is true?
- They are bidirectional
- They kill the watcher when the target dies
- They are one-way and notify the watcher with a message
- They only work for named processes