Monitors and exits
| monitor/2 | |
| 'DOWN' messages | |
| demonitor/1 | |
| Links or monitors |
monitor/2
The monitor function watches a pid from the outside. It is one-directional and needs no mutual agreement, unlike a link.
When the watched process dies, the watcher receives a DOWN message with a reference that identifies the monitor.
1> Pid = spawn(fun() -> ok end).
<0.123456789.0>
2> Ref = erlang:monitor(process, Pid).
#Ref<0.123456789.0>
'DOWN' messages
The DOWN message carries the reference, the watched pid, and the exit reason. Match on the tag and the reference to tell monitors apart.
Two monitors on the same process are two separate DOWN messages with two references.
1> Pid = spawn(fun() -> exit(why) end).
<0.123456789.0>
2> Ref = erlang:monitor(process, Pid).
#Ref<0.123456789.0>
3> receive
{'DOWN', Ref, process, Pid, Reason}
why
demonitor/1
The demonitor function stops a monitor before it fires. Use the flush option to also remove a DOWN message already waiting in the mailbox.
Monitoring a dead process is safe: the DOWN has already been delivered or is on its way.
1> Pid = spawn(fun() -> timer:sleep(1000) end).
<0.111.0>
2> Ref = erlang:monitor(process, Pid).
#Ref<0.111.0>
3> erlang:demonitor(Ref, [flush]).
true
Links or monitors
Links fail together: use them inside a supervision tree that should die as one unit. Monitors observe without being touched: use them for one-way watching.
When in doubt, monitor. Links belong to structure, monitors to observation.
Next: GenServer
Article author: Arthur Isaev