Erlang simple_one_for_one supervisor does not restart child

有些话、适合烂在心里 提交于 2020-06-18 12:35:13

问题


I have a test module and a simple_one_for_one supervisor.

test.erl

-module(test).

-export([
    run/1,
    do_job/1
]).

run(Fun) ->
    test_sup:start_child([Fun]).


do_job(Fun) ->
    Pid = spawn(Fun),
    io:format("started ~p~n", [Pid]),
    {ok, Pid}.

test_sup.erl

-module(test_sup).
-behaviour(supervisor).

-export([start_link/0]).
-export([init/1]).
-export([start_child/1]).

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


init(_Args) ->
    SupFlags = #{strategy => simple_one_for_one, intensity => 2, period => 20},

    ChildSpecs = [#{id => test,
                    start => {test, do_job, []},
                    restart => permanent,
                    shutdown => brutal_kill,
                    type => worker,
                    modules => [test]}],

    {ok, {SupFlags, ChildSpecs}}.


start_child(Args) ->
    supervisor:start_child(?MODULE, Args).

I start supervisor in shell by command test_sup:start_link(). After that i run this command: test:run(fun() -> erlang:throw(err) end). I except the function do_job restart 2times but it never does. What is the problem?

Here is shell:

1> test_sup:start_link().
{ok,<0.36.0>}
2> test:run(fun() -> erlang:throw(err) end).
started <0.38.0>
{ok,<0.38.0>}
3> 
=ERROR REPORT==== 16-Dec-2016::22:08:41 ===
Error in process <0.38.0> with exit value:
{{nocatch,err},[{erlang,apply,2,[]}]}

回答1:


Restarting children is contrary to how simple_one_for_one supervisors are defined. Per the supervisor docs:

Functions delete_child/2 and restart_child/2 are invalid for simple_one_for_one supervisors and return {error,simple_one_for_one} if the specified supervisor uses this restart strategy.

In other words, what you're asking for can never happen. That's because a simple_one_for_one is intended for dynamic children that are defined on the fly by passing in additional startup args when you request the child. Other supervisors are able to restart their children because the startup args are statically defined in the supervisor.

Basically, this type of supervisor is strictly for ensuring a tidy shutdown when you need to have a dynamic pool of workers.



来源:https://stackoverflow.com/questions/41190705/erlang-simple-one-for-one-supervisor-does-not-restart-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!