Why does this Supervisor not start the Genserver?

182 views Asked by At

When the Supervisor code below is invoked I expect the GenServer to start. The GenServer does not start and I want to know why and how to fix it.

defmodule App.Service do
  use GenServer

  def start_link(state) do
    GenServer.start_link(__MODULE__, state)
  end

  def init(state) do
     {:ok, state}
  end

  def get_state(pid) do
     GenServer.call(pid, :get_state)
  end

  def set_state(pid,state) do
     GenServer.call(pid, {:set_state, state})
  end


  def handle_call(:get_state, _from, state) do
     {:reply, state, state}
  end


  def handle_call({:set_state, new_state}, _from, state)do
    {:reply,state,[new_state | state]}
  end
   
end

defmodule App.Supervisor do
  use Supervisor

  def start do
    Supervisor.start_link(__MODULE__, [])
  end

  def init(_) do
     children = [
      App.Service
     ]
  Supervisor.init(children, strategy: :one_for_one)
  end
end



x = App.Supervisor.start()
IO.inspect x

pid = Process.whereis(App.Service)

# The following is nil. I expect a PID

IO.inspect pid  
2

There are 2 answers

3
sabiwara On

If you want to register a GenServer under a name, you should pass the name explicitly to start_link/3 as explained here.

GenServer.start_link(__MODULE__, state, name: __MODULE__)

In your case, the genserver was started but as an anonymous process.

0
Kociamber On

It looks like your GenServer starts and it gets a randomly generated PID. You can indeed register a name during the start:

{:ok, _} = GenServer.start_link(MyApp, [:hello], name: :your_genserver_name)

And then get the PID:

pid = Process.whereis(:your_genserver_name)

Or you can try to find it with Observer (Erlang VM inspection tool) in the Applications tab:

:observer.start()