supervisor

仕事が落ち着いたので、erlang 勉強再開。
id:cooldaemon:20070625 と id:cooldaemon:20070630 で作った server を supervisor tree に入れてみた。

-module(sup).
-behaviour(supervisor).

-export([start_link/1, stop/0]).
-export([init/1, worker_spec/2]).

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

stop() ->
  case whereis(?MODULE) of
    Pid when pid(Pid) ->
      exit(Pid, shutdown),
      ok;
    _ ->
      not_started
  end.

init(Code) ->
  Flags = {one_for_one, 0, 1},
  Children = [
    worker_spec(counter, []),
    worker_spec(code_lock, [Code])
  ],
  {ok, {Flags, Children}}.

worker_spec(WokerModule, Args) ->
  StartFunc = {WokerModule, start_link, Args},
  {WokerModule, StartFunc, permanent, brutal_kill, worker, [WokerModule]}.

sup:start_link("abcd"). で counter と code_lock が起動し、sup:stop(). で全てが停止する。