Elixir Process Monitors
A process monitor is a one-way watch on another process. When the watched process ends, the watcher gets a DOWN message with the reason.
A monitor reports a normal end
The watched worker ends normally, and the watcher reads the reason.
worker = spawn(fn -> receive do :stop -> :ok end end)
Process.monitor(worker)
send(worker, :stop)
receive do {:DOWN, _ref, :process, _pid, reason} -> IO.puts(reason) endA monitor reports an error end
The watched worker ends with an error, and the watcher reads that reason.
worker = spawn(fn -> receive do :go -> exit(:boom) end end)
Process.monitor(worker)
send(worker, :go)
receive do {:DOWN, _ref, :process, _pid, reason} -> IO.puts(reason) endThe watcher survives a watched error
The watcher reads the error reason and is still alive afterwards.
worker = spawn(fn -> receive do :go -> exit(:boom) end end)
Process.monitor(worker)
send(worker, :go)
receive do {:DOWN, _ref, :process, _pid, reason} -> IO.puts(reason) end
IO.puts(Process.alive?(self()))Example
worker = spawn(fn -> receive do :stop -> :ok end end)
Process.monitor(worker)
send(worker, :stop)
receive do {:DOWN, _ref, :process, _pid, reason} -> IO.puts(reason) end
worker2 = spawn(fn -> receive do :go -> exit(:boom) end end)
Process.monitor(worker2)
send(worker2, :go)
receive do {:DOWN, _ref2, :process, _pid2, reason2} -> IO.puts(reason2) endKey points
- Monitor: Process.monitor starts watching another process.
- One-way: Only the watcher gets a notice, and the watched process is not affected.
- Notice: The notice is a DOWN message that carries the reason the process ended.
- Reason: The DOWN message holds a reference and a process id, so print only the reason.
- Survival: A watcher stays alive after a watched process ends with an error.
In this example, two workers are watched one after the other. The first ends normally and the second ends with an error, and each DOWN message prints only its reason.
Note
A monitor does not end the watched process when the watcher ends.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a watcher receive when a watched process ends?