Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Fault Tolerance and OTP

Links, monitors and exit signals

Understand how Erlang processes detect each other's failure: spawn_link, exit signals, trap_exit, monitors and DOWN messages, and the let it crash philosophy.

Most languages try to prevent errors. Erlang accepts that something will eventually fail, a bad input, a lost connection, a bug, and instead makes failure cheap to detect and cheap to recover from. The two basic tools are links and monitors. Together with supervisors (next lessons) they implement the famous philosophy: let it crash.

Exit reasons

When a process terminates it has an exit reason:

  • normal: its function returned, or it called exit(normal).
  • Any other term: it crashed (for example {badarith, ...}), called exit(Reason), or was killed.
  • kill: a special signal that cannot be trapped; the victim's reason becomes killed.
ERLANG
spawn(fun() -> 1 / 0 end).
%% =ERROR REPORT==== ... Error in process <0.120.0> with exit value:
%% {badarith,[{erlang,'/',[1,0],...}]}

The crash prints an error report but the shell, a different process, continues unharmed.

A link is a bidirectional relationship between two processes. If one ends with a reason other than normal, an exit signal travels along the link and the other process is terminated too, with the same reason.

ERLANG
Pid = spawn_link(fun() ->
    timer:sleep(100),
    exit(boom)
end).

spawn_link/1 creates the process and the link atomically; always prefer it over spawn followed by link(Pid), because the child might die between the two calls. link/1 and unlink/1 work on existing processes.

This models "these processes only make sense together": a worker and the process that coordinates it. If the coordinator dies, the workers go too and nothing is left orphaned. A normal exit sends a signal that is simply ignored by default.

Trapping exits

A process that traps exits receives exit signals as ordinary messages {'EXIT', FromPid, Reason} instead of dying. This is how a supervisor watches its children.

ERLANG
supervisor_like() ->
    process_flag(trap_exit, true),
    Worker = spawn_link(fun() -> exit(oops) end),
    receive
        {'EXIT', Worker, Reason} ->
            io:format("worker ended: ~p~n", [Reason])
    end.

Calling it prints worker ended: oops. The one exception: exit(Pid, kill) kills even a trapping process, delivered to others as killed.

Link versus monitor

Link Two-way, shared fate
Monitor One-way, just watching
Link signal Kills partner unless trapped
Monitor signal A DOWN message, never kills

Links express dependence; monitors express interest.

1 / 2

Monitors: watch without sharing fate

A monitor is one-way and stackable. The watcher gets a message when the target goes away but is never killed by it.

ERLANG
Ref = erlang:monitor(process, Pid),
receive
    {'DOWN', Ref, process, Pid, Reason} ->
        io:format("~p went down: ~p~n", [Pid, Reason])
end.

Reason is normal if the process finished normally, noproc if it did not exist at all, and the crash reason otherwise. Each call returns a new reference, so several parts of a program can independently monitor the same process. erlang:demonitor(Ref, [flush]) stops monitoring and removes a pending DOWN message.

spawn_monitor/1 combines spawn and monitor atomically, ideal for "run this and tell me how it went":

ERLANG
{Pid, Ref} = spawn_monitor(fun() -> exit(too_bad) end),
receive {'DOWN', Ref, process, Pid, R} -> R end.   % too_bad

Monitors also work across nodes: you receive noconnection as the reason if the network breaks.

try/catch versus supervision

Inside one process you still use try ... catch for expected problems (bad user input, a missing file). Use crashes for unexpected ones. A good rule: if you do not know how to repair the situation at this point, let the process die and let someone with more context (a supervisor) decide.

ERLANG
safe_div(A, B) ->
    try A / B
    catch error:badarith -> {error, divide_by_zero}
    end.

This JavaScript stand-in is not Erlang. A "process" is an object; ending it propagates exit signals to linked partners or sends DOWN messages to monitors, and a trapExit flag turns a signal into a message.

JS Stand-in: links, trap_exit and monitors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Practical advice

  • Use links for processes that cannot live without each other; use monitors for clients watching a server.
  • A process that traps exits must handle {'EXIT', _, _} messages, otherwise they pile up in the mailbox.
  • Do not trap exits everywhere: it disables the automatic clean-up that makes crashes safe.
  • Keep processes small and focused so a crash loses little state, and rebuild state from a source of truth when restarting.

A worker with a watcher (read-only)

A typical pattern: a manager starts jobs, monitors each, and retries on failure.

ERLANG
run_job(Fun) ->
    {Pid, Ref} = spawn_monitor(Fun),
    receive
        {'DOWN', Ref, process, Pid, normal} -> ok;
        {'DOWN', Ref, process, Pid, Reason} -> {error, Reason}
    after 5000 ->
        exit(Pid, kill),
        {error, timeout}
    end.

Every path leaves nothing behind: either the job ended, or we killed it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to a linked process when its partner exits with reason boom (not trapping exits)?

    An exit signal with a non-normal reason kills the linked process unless it traps exits.
  2. 2. How does a process that has trap_exit set learn about a linked process crash?

    Trapped exit signals are converted into regular messages.
  3. 3. What is the main difference between a monitor and a link?

    A monitor only delivers a DOWN message; a link shares fate in both directions.
  4. 4. Why prefer spawn_link/1 to spawn/1 followed by link/1?

    Creating process and link in one step avoids a race where the signal is lost.
  5. 5. What reason does a DOWN message carry for a process that never existed?

    Monitoring a non-existing process delivers an immediate DOWN with reason noproc.

Summary

  • A process exits with a reason; anything but normal is a crash.
  • Links are bidirectional and spread non-normal exits; trap_exit turns signals into messages.
  • Monitors are one-way and deliver {'DOWN', Ref, process, Pid, Reason}.
  • Use spawn_link and spawn_monitor for race-free setup.
  • Catch expected errors locally; let unexpected ones crash and be handled by a supervisor.

Next: gen_server