[erlang-questions] supervisors, gen_server:terminate/2, and trap_exit

Fred Hebert <>
Thu Mar 12 14:57:27 CET 2015

On 03/12, Youngkin, Rich wrote:
> So let's say that:
>   1. Supervisor1 starts Supervisor2 and GenServerA in that order.

        /  \
    Sup2   GenA

>   2. A Supervisor1 is given a child_spec with a simple_one_for_one restart
> strategy.

That isn't possible because Sup2 and GenA are two different types. Maybe
you meant:


Which I will assume from now on because otherwise it doesn't make sense.
So Sup1 has a SOFO strategy over a supervisor 'Sup2', which itself has
an undetermined child_spec to GenA.

>   3. GenServerA implements a start/0 API function that results in calling
> supervisor:start_child(Supervisor1, [SomeArgs]) that creates ChildZ.

     |   \
    Sup2 Sup2FromGenA (ChildZ)
     |      |
    GenA  GenZ

This is the only thing that makes sense for this, because the SOFO
strategy keeps GenZ from being a child of Sup1.

>   4. ChildZ's init/1 function does not trap_exits.

In this case I'll assume you mean 'GenZ' ? But it breaks your
assumptions of simple_one_for_one supervisors.

So let's back track and say you meant 'one_for_one'. Then we can have:

    /  \     |
  Sup2 GenA ChildZ

Because we can have multiple strategies.

>   4. GenServerA also implements a stop/0 API function that results in
> calling supervisor:terminate_child(Supervisor1, ChildZPid)

Going with the last graph then okay, that works. Any of the prior ones

> At step 4, will ChildZ:terminate/2 get called? Or does it have to

No it will not get called because supervisors shut down their children
with exit signals. If ChildZ is not trapping exit, the exit signal will
not be controlled and it will kill the process.

> trap_exit? If it's the latter AND ChildZ doesn't trap_exit then it seems as
> if ChildZ would have to implement handle_info('EXIT', ParentPid, shutdown)
> which could then call terminate/2?

THe process can only have handle_info({'EXIT', NonParentPid, shutdown},
State) if, and only if it traps exits. Actually you will *never* see
ParentPid show up, because signals from the parent process are filtered,
handled, and hidden by the OTP behaviour themselves. Only trapped
signals from non-parent processes are bubbled up and shown to the user
via the handle_info/2 function.


> Thanks,
> Rich

More information about the erlang-questions mailing list