I have two kind of processes to be started by a supervisor: some workers and a controller to which the workers need to report. For this they need to know the pid of the controller.
I was thinking about two ways to do this but none works.
Starting all at once
The principle is to start all the processes at once, then to retrieve the pid of the controller and then to send it to all the workers so that they can start to work. The code would look like this:
defmodule XYZ.MySup do
use Supervisor
def start_link(opts) do
...
end
def init(:ok) do
children = [
{XYZ.Controller, name: :ctrl},
%{id: XYZ.Worker_1,
start: {XYZ.Worker,
:start_link, [[name: :w1, args: {"arg_1"}]]}},
... some other workers ...
]
Supervisor.init(children, strategy: :one_for_one)
ch = Supervisor.which_children(self())
...
end
end
The line Supervisor.which_children(self())
generates the error ** (EXIT) process attempted to call itself
.
Starting the controller first
The principle is to start the controller, then to get its pid, then start the workers with the pid of the controller as a parameter (That would be the preferred method, btw).
- of course, getting the pid of the controller gets into the same issue: the runtime refuses to call
Supervisor.which_children(self))
. even if this would be solved, adding a worker to the supervisor with:
Supervisor.start_child(self(), %{id: XYZ.Worker_3, start: {XYZ.Worker, :start_link, [[name: :w3, args: {"arg_3"}]]}})
fails with the error
** (EXIT) process attempted to call itself
.
What am I doing wrong ?