1

我有一个简单的主管配置:

-module(my_supervisor).
-behaviour(supervisor).
-export([start_link/0, init/1]).

init(_Args) ->
    {ok, { {one_for_one, 5, 10},
       [
        {my_worker, {my_worker, start_link, []}, permanent, 5000, worker, [my_worker]}
        ]
     }
}.

甚至是简单的工人:

-module(my_worker).
-export([start_link/0]).
start_link() ->
    %??? is this the first time the supervisor is starting me or have I crashed and been restarted???

那么是否有可能确定这是主管第一次调用 start_link 函数,还是工作进程在过去某个时间崩溃并且现在正在重新启动?

4

1 回答 1

0
  1. For determining whether this is the first time the start_link function is called by the supervisor. You can use childId parameter and pass the childId from outside as follows, for details, please doc about erlang supervisor.

    start_child(ChildId, Mod, Args) -> {ok, _} = supervisor:start_child(?SERVER, {ChildId, {Mod, start_link, Args}, transient, ?MAX_WAIT, worker, [Mod]}), ok.

  2. For determining worker has been restarted. Please read document of monitor and link. When crash happens,your process will receive messages. If you read the supervisor's source code, you will find the supervisor actually use link and monitor to solve the crash monitor task.

3.

init([]) -> 
     process_flag(trap_exit, true), 
     ...


terminate(_Reason, _State) ->
    % may be crash here by check reason above. 
    ok.

handle_info({'EXIT',Self,Reason},State#state{self=Self)->
    error_logger:info_report([crash_now]),
    {stop,Reason,State};



  [1]: http://www.erlang.org/doc/man/supervisor.html
于 2013-01-03T12:02:58.983 回答