Erlang supervisor dinámico iniciar gen_server
-
27-10-2019 - |
Pregunta
Tengo un supervisor raíz que crea otro supervisor:
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
RestartStrategy = {one_for_one, 5, 600},
ListenerSup =
{popd_listener_sup,
{popd_listener_sup, start_link, []},
permanent, 2000, supervisor, [popd_listener]},
Children = [ListenerSup],
{ok, {RestartStrategy, Children}}.
Y tengo gen_server - oyente.¿Cómo puedo ejecutar este gen_server con popd_listener_sup
supervisor, ¿cuándo se creó el supervisor?
Gracias.
Solución
supervisor raíz
-module(root_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1, shutdown/0]).
start_link() ->
supervisor:start_link({local,?MODULE}, ?MODULE, []).
init(_Args) ->
RestartStrategy = {one_for_one, 10, 60},
ListenerSup = {popd_listener_sup,
{popd_listener_sup, start_link, []},
permanent, infinity, supervisor, [popd_listener_sup]},
Children = [ListenerSup],
{ok, {RestartStrategy, Children}}.
% supervisor can be shutdown by calling exit(SupPid,shutdown)
% or, if it's linked to its parent, by parent calling exit/1.
shutdown() ->
exit(whereis(?MODULE), shutdown).
% or
% exit(normal).
Si el proceso hijo es otro supervisor, Shutdown
en la especificación secundaria debe establecerse en infinity
para darle al subárbol tiempo suficiente para cerrarse, y Type
debe establecerse en supervisor
, y eso es lo que hicimos.
supervisor infantil
-module(popd_listener_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local,?MODULE}, ?MODULE, []).
init(_Args) ->
RestartStrategy = {one_for_one, 10, 60},
Listener = {ch1, {ch1, start_link, []},
permanent, 2000, worker, [ch1]},
Children = [Listener],
{ok, {RestartStrategy, Children}}.
Aquí, en una especificación secundaria, establecemos el valor de Shutdown
a 2000
.Un valor de tiempo de espera entero significa que el supervisor le indicará al proceso hijo que finalice llamando exit(Child,shutdown)
y luego espere una señal de salida con el motivo del cierre del proceso secundario.
Oyente
-module(ch1).
-behaviour(gen_server).
% Callback functions which should be exported
-export([init/1]).
-export([handle_cast/2, terminate/2]).
% user-defined interface functions
-export([start_link/0]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init(_Args) ->
erlang:process_flag(trap_exit, true),
io:format("ch1 has started (~w)~n", [self()]),
% If the initialization is successful, the function
% should return {ok,State}, {ok,State,Timeout} ..
{ok, []}.
handle_cast(calc, State) ->
io:format("result 2+2=4~n"),
{noreply, State};
handle_cast(calcbad, State) ->
io:format("result 1/0~n"),
1 / 0,
{noreply, State}.
terminate(_Reason, _State) ->
io:format("ch1: terminating.~n"),
ok.
De la documentación de Erlang/OTP:
Si el Gen_Server es parte de un árbol de supervisión y su supervisor ordena que termine, la función
Module:terminate(Reason, State)
será llamado conReason=shutdown
Si se aplican las siguientes condiciones:
- el
gen_server
ha sido configurado para atrapar señales de salida, y- la estrategia de apagado tal como se define en la especificación secundaria del supervisor
es un valor de tiempo de espera entero, no
brutal_kill.
Por eso llamamos erlang:process_flag(trap_exit, true)
en Module:init(Args)
.
Ejecución de muestra
Iniciando el supervisor raíz:
1> root_sup:start_link().
ch1 has started (<0.35.0>)
{ok,<0.33.0>}
El supervisor raíz se ejecuta e inicia automáticamente sus procesos secundarios, supervisor secundario en nuestro caso.El supervisor infantil, a su vez, inicia sus procesos infantiles;solo tenemos un hijo en nuestro caso, ch1
.
Hagamos ch1
evaluar el código normal:
2> gen_server:cast(ch1, calc).
result 2+2=4
ok
Ahora un código incorrecto:
3> gen_server:cast(ch1, calcbad).
result 1/0
ok
ch1: terminating.
=ERROR REPORT==== 31-Jan-2011::01:38:44 ===
** Generic server ch1 terminating
** Last message in was {'$gen_cast',calcbad}
** When Server state == []
** Reason for termination ==
** {badarith,[{ch1,handle_cast,2},
{gen_server,handle_msg,5},
{proc_lib,init_p_do_apply,3}]}
ch1 has started (<0.39.0>)
4> exit(normal).
ch1: terminating.
** exception exit: normal
Como puede ver el proceso hijo ch1
fue reiniciado por el supervisor infantil popd_listener_sup
(aviso ch1 has started (<0.39.0>)
).
Dado que nuestro shell y supervisor raíz están vinculados bidireccionalmente (llame supervisor:start_link
, no supervisor:start
en la función de supervisor raíz start_link/0
), exit(normal)
resultó en el cierre del supervisor raíz, pero sus procesos secundarios tuvieron algo de tiempo para limpiarse.