Erlang:主管 start_child 成功但未添加 child

Erlang: Supervisor start_child succeeds but no child is added

我正致力于在 Erlang 中构建一个如下所示的主管:

-module(a_sup).
-behaviour(supervisor).

%% API
-export([start_link/0, init/1]).

start_link() ->
  {ok, supervisor:start_link({local,?MODULE}, ?MODULE, [])}.

init(_Args) ->
  RestartStrategy = {simple_one_for_one, 5, 3600},
  ChildSpec = {
    a_gen_server,
    {a_gen_server, start_link, []},
    permanent,
    brutal_kill,
    worker,
    [a_gen_server]
  },
  {ok, {RestartStrategy,[ChildSpec]}}.

这就是我的 gen_server 的样子:

-module(a_gen_server).
-behavior(gen_server).

%% API
-export([start_link/2, init/1]).

start_link(Name, {X, Y}) ->
  gen_server:start_link({local, Name}, ?MODULE, [Name, {X,Y}], []),
  ok.

init([Name, {X,Y}]) ->
  process_flag(trap_exit, true),
  io:format("~p: position {~p,~p}~n",[Name, X, Y]),
  {ok, {X,Y}}.

我的 gen_server 完全正常。当我运行主管为:

1> c(a_sup).
{ok,a_sup}
2> Pid = a_sup:start_link().
{ok,{ok,<0.85.0>}}
3> supervisor:start_child(a_sup, [Hello, {4,3}]).
Hello: position {4,3}
{error,ok}

我不明白 {error, ok} 是从哪里来的,如果有错误,那是什么原因造成的。这就是我检查 children:

状态时得到的结果
> supervisor:count_children(a_sup).
[{specs,1},{active,0},{supervisors,0},{workers,0}]

这意味着尽管它调用了 gen_server 的 init 方法并生成了一个进程,但还没有 children 注册到主管?显然有一些错误阻止了该方法成功完成,但我似乎无法收集任何提示来解决这个问题。

问题是 a_gen_server:start_link(因为这是子规范中使用的函数)预计 return {ok, Pid},而不仅仅是 ok

正如the docs所说:

The start function must create and link to the child process, and must return {ok,Child} or {ok,Child,Info}, where Child is the pid of the child process and Info any term that is ignored by the supervisor.

The start function can also return ignore if the child process for some reason cannot be started, in which case the child specification is kept by the supervisor (unless it is a temporary child) but the non-existing child process is ignored.

If something goes wrong, the function can also return an error tuple {error,Error}.