What is the purpose of trap_exit
lud opened this issue · comments
Hi,
I know that this process flag transforms the exits signals into messages that can be received. But what if we do not set the flag ? I guess a supervisor will still be able to kill/restart the process if needed, so what is the reason behind ?
Thank you.
If I read the docs correctly, that would be to implement a supervisor …
Nowadays, monitoring is best done using monitors, but process linking can be very useful for cascading exits. Conversely, enabling trap_exit
may be needed if yi don't want to die immediately when a linked process dies. As far as the supervisor is concerned, the behaviors recognize an {'EXIT', Parent, shutdown}
and self-terminate. Otherwise, the supervisor will send an exit(Child, kill)
Thank you :)
Looking at the supervisor
module code, it seems that whenever a process (even gen_server
) does not traps exits, the supervisor will report an error, because the process will exit with reason killed
which it neither shutdown
nor normal
.
So I think I need to trap exit in my processes in order to avoid this.
plain_fsm
handles any exit message (and call terminate
if exported), even when the signal does not come from the parent process, is that true ?
Actually, no. If you use the pseudo-function plain_fsm:extended_receive(Expr)
, receive clauses that specifically match EXIT
signals from the parent will be generated; other EXIT
signals are ignored. Otherwise, you have to take care of your own messages, and plain_fsm
can help you e.g. find the parent pid easily. See the documentation here for examples:
Oh yes, I missed that bit :
get_parent_expr() ->
{match,0,
{var,0,'__FSM_Parent'},
{call,0,{remote,0,
{atom,0,?PLAIN_FSM},
{atom,0,info}},
[{atom,0,parent}]}}.
Thank you very much for the explainations.