I. Problem Introduction
When the Erlang monitoring process starts, it sets trap_exit to true, which will capture the exit signal and convert the exit signal to {'exit ', PID, reason} and save it to its own mailbox, therefore, after the process associated with the monitoring process exits, the monitoring process can calmly intercept the exit signal and does not exit. The process that starts the Erlang monitoring process will establish a link relationship with the monitoring process. However, when the starting process exits, the monitoring process does not look like a normal situation and exits unexpectedly, why does trap_exit exit even if it is set to true?
Ii. Cause Analysis
View the source code of the supervisor, which is implemented by gen_server. It analyzes the processing of messages received from {'exit ', PID, reason}, as follows:
Handle_info ({'exit ', PID, reason}, state)->
Case restart_child (PID, reason, State)
{OK, state1}->
{Noreply, state1 };
{Shutdown, state1}->
{Stop, shutdown, state1}
End;
The problem lies here. After the supervisor receives this signal, it regards the exited PID as its own sub-process to perform the restart operation. Obviously, the process for Starting monitoring is not a monitored sub-process, but not a sub-process specification. During the restart process, an exception will inevitably occur and {shutdown, state1} will be returned }, in this way, it will be transferred to the terminate of the supervisor, resulting in the termination of the supervisor. The process is as follows:
Iii. Summary
It does not mean that if process_flag (trap_exip, true) is set, the exit signal will be intercepted and not exited. This operation only converts the exit signal to the tuples {'exit ', PID, reason} is put into the mailbox. The key is whether to exit.
Is there any action that matches {'exit ', PID, reason} and what is done in the action of matching? This is the core and cannot stay on the surface.
Cause Analysis of Abnormal exit of Erlang monitoring process after the startup process exits