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_worker sleeps for 1s, prints a message, then calls exit(:abnormal). This simulates a failure without raising an exception (so you avoid noisy error logs).
  • stable_worker sleeps for 2s and finishes normally.
  • monitor_workers spawns both workers and sets up monitors: ref1 = Process.monitor(pid1) and ref2 = 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/2 listens for those :DOWN messages:
    • The first clause matches the for and prints the exit reason (expected here). It then recurses with set to to avoid matching it again.
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 a receive loop.
  • 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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal