[erlang-questions] supervisor children's pid

Jachym Holecek freza@REDACTED
Wed May 18 10:34:22 CEST 2011


# Vance Shipley 2011-05-18:
> On Wed, May 18, 2011 at 12:37:02AM +0200, Roberto Ostinelli wrote:
> }  currently, i'm calling supervisor:which_children/1 on the init function of
> }  the gen_servers, and match the Ids to get the Child [Pid].
> 
> You can't call the supervisor from the init function of one of it's
> own children.  You have to return from init/1 before that is possible.
> 
> What you can do is to return {ok, State, Timeout} from init/1 with
> a Timeout value of 0 and go on with the initialization after the
> supervisor has completed starting the children.  The attached example
> uses a psuedo state to carry on with the initialization:
> 
>      1> supervisor:start_link(which_sup, []).
>      Server=1, Siblings=[<0.36.0>,<0.35.0>]
>      Server=2, Siblings=[<0.36.0>,<0.34.0>]
>      Server=3, Siblings=[<0.35.0>,<0.34.0>]
>      {ok,<0.33.0>}

Nice trick, but there is no guarantee process' siblings will already be
started after some arbitrary timeout -- try this on a heavily loaded
system... it's just not safe.

> }  is this the best strategy to achieve this?
> 
> Yes, use supervisor:which_children/1 to learn the siblings.

No, if he's using anything other than one_for_all strategy the Pids
he learns this way may become stale in the future.

Usual ways to handle this:

  * Register the processes, if the names need to be dynamic supervisor
    can compute them at init/1 and pass to children in arguments.

  * Run a name resolution server somewhere and have all the children
    subscribe to it. The server will monitor them and may provide
    notification facility to announce Pid changes/availability to
    anyone interested -- this lets you do safe startup of dependent
    processes.

  * In some cases, you'd start_link those child processes from one
    master server directly (not from supervisor), and use their Pids
    directly. Only makes sense if they're very closely bound.

  * Probably something else I can't remember right now. :-)

HTH,
	-- Jachym



More information about the erlang-questions mailing list