这段代码是我刚从书上看到的,虽然学过erlang的人都见过,但我还是想分享下这段巧妙的代码
-module(my_supervisor).
-export([start_link/2,stop/1]).
-export([init/1]).
start_link(Name,ChildSpecList) ->
register(Name,spwan_link(my_supervisor,init,[ChildSpecList])),ok. %注册了一个Name的监控
init(ChildSpecList) ->
process_flag(trap_exit,true), %允许接受进程
loop(start_children(ChildSpecList)).
start_children([]) -> [];
start_children([{M,F,A}|ChildSpecList]) -> %M-模块名 ,F-函数名,A- 参数
case (catch apply(M,F,A)) of %apply/3本网站有介绍
{ok,Pid} ->
[{Pid,{M,F,A}}|start_children(ChildSpecList)];%最后得出一个列表
_ ->
start_children(ChildSpecList)
end.
%重启子进程
restart_child(Pid,ChildList) ->
{value,{Pid,{M,F,A}}} = lists:keysearch(Pid,1,ChildList),
{ok,NewPid} = apply(M,F,A),
[{NewPid,{M,F,A}}|lists:keydelete(Pid,1,ChildList)].
loop(ChileList) ->
receive
{'EXIT',Pid,_Reason} ->
NewChildList = restart_child(Pid,ChildList),
loop( NewChildList);
{stop,From} ->
From ! {reply,terminate(ChildList)}
end.
stop(Name) ->
Name ! {stop,self()},
receive {reply,Reply} -> Reply end.
%循环结束ChildList中的子进程
terminate([{Pid,_}|ChildList]) ->
exit(Pid,kill),
terminnate(ChildList);
terminate(_ ChildList) -> ok.
|