Do supervisors need to start their own supervisor?

3.9k views Asked by At

Let us say I have one supervisor and I need execute some start_child for this supervisor. Must I first start all of start my supervisors? Or can I only supervisor:start_child(my_sup,[]) without my_sup starting?

2

There are 2 answers

2
Yasir Arsanukayev On BEST ANSWER

First you create a supervisor process as part of a supervision tree calling supervisor:start_link/2 or supervisor:start_link/3. The created supervisor process calls Module:init/1 to find out about restart strategy, maximum restart frequency and child specifications.

This is the example code for a supervisor starting gen_server (though, you may start other gen_* modules):

-module(ch_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
    supervisor:start_link(ch_sup, []).
init(_Args) ->
    {ok, {{one_for_one, 1, 60},
          [{ch3, {ch3, start_link, []},
            permanent, brutal_kill, worker, [ch3]}]}}.

The tuple {ch3, ...} is a child specification, which is defined this way:

{Id, StartFunc, Restart, Shutdown, Type, Modules}

The child specification to start the server ch3 in the example above looks like:

{ch3, {ch3, start_link, []}, permanent, brutal_kill, worker, [ch3]}

From the example you see that module ch3 will be started, monitored and stopped by supervisor, you also see one_for_one restart strategy specified which is generally used. one_for_one in the child specification means that if one child process terminates and should be restarted, only that child process is affected, and this is probably your case. Your child processes are started, monitored, restarted and stopped automatically by supervisor.

start_child/2 is used to dynamically add a child specification to the supervisor SupRef which starts the corresponding child process.

Thus supervisour is always started first, then its child processes are started automatically or manually based on the restart strategies.

0
AudioBubble On

Yes, you should first start the supervisor because you will not be starting the child since the supervisor is the one which starts the child. Hope it helps.