TExcelTAD
Home › Elixir › Elixir Links & Monitors

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

elixir · try it yourself
{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)}")
end
true
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:

elixir · try it yourself
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)}")
end
1st: :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:

elixir · try it yourself
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)}")
end
group 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:

elixir · try it yourself
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:

  1. Write the happy path clearly.
  2. Let the process crash when something unexpected happens.
  3. 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?

  1. An exception
  2. A {:DOWN, ref, :process, pid, reason} message
  3. Nothing, unless it is linked
  4. 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?

  1. Nothing
  2. A receives a :DOWN message
  3. A exits with reason :boom too
  4. A restarts B

Which statement about monitors is true?

  1. They are bidirectional
  2. They kill the watcher when the target dies
  3. They are one-way and notify the watcher with a message
  4. They only work for named processes