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) ->
spawn​(​fun​() ->
Ref = ​monitor​(process, Pid),
receive
{'DOWN', Ref, process, Pid, Why} ->
Fun(Why)
end
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.