Programming for Fault Tolerance
In this section, you’ll learn a few simple techniques that can be used to make fault-tolerant code. This is not the whole story of how to make a fault-tolerant system, but it is the start of a story.
Performing an Action When a Process Dies
The function on_exit(Pid, Fun)
watches the process
Pid
and evaluates Fun(Why)
if the process
exits with the reason Why
.
lib_misc.erl | |
Line 1 | on_exit(Pid, Fun) -> |
2 | spawn(fun() -> |
3 | Ref = monitor(process, Pid), |
4 | receive |
5 | {'DOWN', Ref, process, Pid, Why} -> |
6 | Fun(Why) |
7 | end |
8 | end). |
monitor(process, Pid)
(line 3) creates a monitor to
Pid
. When the process dies, a DOWN
message is
received (line 5) and calls
Fun(Why)
(line 6).
To test this, we’ll define ...
Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.