In the last lesson, you kept state inside a process with a receive loop. Quick reminder: a process waits for messages with receive and often recurses to stay alive. Today, you will build on that by making your process aware of other processes’ life cycles. This is where monitoring (and, conceptually, linking) comes in.
- Monitoring lets one process watch another and receive a message when it exits.
- Linking ties processes together so a crash can propagate. We will mention linking for context but focus on monitoring in code.
Explanation:
unstable_workersleeps for 1s, prints a message, then callsexit(:abnormal). This simulates a failure without raising an exception (so you avoid noisy error logs).stable_workersleeps for 2s and finishes normally.monitor_workersspawns both workers and sets up monitors:ref1 = Process.monitor(pid1)andref2 = Process.monitor(pid2). A monitor is one-way: if the target process exits, you receive a{:DOWN, ref, :process, pid, reason}message. Your monitoring process does not crash because of it.wait_for_completion/2listens for those:DOWNmessages:- The first clause matches the for and prints the exit reason (expected here). It then recurses with set to to avoid matching it again.
You now know how to:
- Spawn workers and monitor them with
Process.monitor/1. - React to
{:DOWN, ref, :process, pid, reason}messages in areceiveloop. - Distinguish monitoring (one-way notification) from linking (bidirectional failure propagation).
This is the basis for building supervisor-like behavior and making your systems fault-aware. Ready to make it stick? Head to the practice section and put monitoring into action.
