Peter Saxton
Peter Saxton

Reputation: 4676

How to reference previously started processes in an Elixir supervisor

I am starting a Supervisor that monitors two children. The second child needs a reference to the first. It seams like this should be possible because by using the one_for_rest strategy I can make sure that if the first dies the second is restarted.

children = [
  supervisor(SupervisorA, [arg1]),
  supervisor(SupervisorB, [arg2, ref_to_supervisor_a_process]),
]

supervise(children, strategy: :one_for_rest)

Ideally without having to globally name either process.

Upvotes: 4

Views: 620

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 120990

Supervisor.Spec.supervisor/3 returns a spec.

One might pass it through:

{id, _, _, _, _, _} = sup_a = supervisor(SupervisorA, [arg1])
children = [
  sup_a,
  supervisor(SupervisorB, [arg2, id]),
]

Upvotes: 0

Mike Buhot
Mike Buhot

Reputation: 4885

SupervisorA can supply the name: option to Supervisor.start_link/3.

SupervisorB can then use Process.whereis/1 to resolve the name to a pid or just send messages to the named process.

https://hexdocs.pm/elixir/Supervisor.html#start_link/3 https://hexdocs.pm/elixir/Process.html#whereis/1

Upvotes: 1

Related Questions