typestar

Monitors in Erlang

A monitor turns another process's death into a message.

%% A monitor turns another process's death into a message.
main(_) ->
    {Pid, Ref} = spawn_monitor(fun() ->
        io:format("Test call on the spare pair~n")
    end),

    receive
        {'DOWN', Ref, process, Pid, Reason} ->
            io:format("Worker finished: ~p~n", [Reason])
    end,

    %% A crash arrives the same way, as data.
    {_, Ref2} = spawn_monitor(fun() -> exit(blown_fuse) end),
    receive
        {'DOWN', Ref2, process, _, Why} ->
            io:format("Second worker: ~p~n", [Why])
    end.

How it works

  1. spawn_monitor answers both the pid and a reference.
  2. The 'DOWN' message carries the reason it ended.
  3. A crash arrives the same way — death is data.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
441
Tokens
113
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 123 seconds.

Type this snippet

Step 4 of 4 in Processes, step 28 of 31 in Language basics.

← Previous Next →