Process links propagate abnormal termination across process boundaries. Exit trapping changes that behavior: instead of terminating when a linked process crashes, the receiving process gets an exit notification in its message queue. section 8.2.1
Use exit trapping when a process must observe linked-process termination and decide what to do:
- Call Process.flag(:trap_exit, true) in the receiving process. section 8.2.1
- Receive the resulting {:EXIT, from_pid, exit_reason} message. section 8.2.1
- Inspect the originating PID and termination reason, then react to the failure or remove associated state. section 8.2.1 section 10.3.4
- Set the trap in a GenServer init/1 callback when graceful termination must invoke terminate/2 for cleanup. section 9.1.6
Detecting a linked crash
A trapping process links to a worker that raises an exception, then receives a message such as {:EXIT, pid, {%RuntimeError{message: "Something went wrong"}, stacktrace}} instead of crashing itself. section 8.2.1
iex(1)> spawn(fn ->
Process.flag(:trap_exit, true) #1
spawn_link(fn -> raise("Something went wrong") end) #2
receive do #3
msg -> IO.inspect(msg) #3
end #3
end)
Runnable Elixir example showing trap setup, linked-process failure, and message reception. section 8.2.1
