Process Monitoring and Linking
Process Monitoring and Linking
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.
Monitoring Two Workers and Handling DOWN Messages
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
DOWNforref1and prints the exit reason (expected:abnormalhere). It then recurses withref1set tonilto avoid matching it again. - The second clause matches the
DOWNforref2and prints a completion message.
- The first clause matches the
- The final line starts the whole flow. Expected order: after ~1s, you’ll see the “abnormally” message and “Process 1 died: :abnormal,” and after ~2s, you’ll see “Stable worker completed” and “Process 2 completed.”
About linking (briefly): linking connects processes so that a crash in one can bring down the linked process unless you trap exits. Monitoring is safer for observers because it only sends a message on exit and does not crash the observer.
Summary and Next Steps
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.
