erlang学习笔记之用OTP构建系统5

本文详细介绍了如何在Erlang中使用Supervisor进行进程管理和控制,包括启动Supervisor、动态添加和停止子进程,以及简单_one_for_one策略的应用。还探讨了终止时的自动子进程清理过程。
摘要由CSDN通过智能技术生成

监控树2

6,启动一个supervisor


上面的例子通过调用ch_sup:start_link()来启动supervisor:

start_link() ->
  supervisor:start_link(ch_sup, []).

ch_sup:start_link调用方法supervisor:start_link/2,这个方法启动一个新的supervisor进程并连接它
1)第一个参数ch_sup是callback模块的名字,它是init callback方法所在的位置
2)第二个参数[]是传给init callback方法的参数
一个supervisor进程调用callback方法ch_sup:init([]),返回{ok, StateSpec}:

init(_Args) ->
  {ok, {{one_for_one, 1, 60},
    [{ch3, {ch3, start_link, []},
      permanent, brutal_kill, worker, [ch3]}]}}.

然后根据指定的子规范的入口来启动它的所有子进程,在这里有一个子进程ch3
注意supervisor:start_link是同步带,当作有子进程启动之后才会返回

7,添加一个子进程


除了静态的supervision tree,我们也可以添加动态子进程到已有的supervisor里:

supervisor:start_child(Sup, ChildSpec)

Sup是supervisor的pid或名字,ChildSpec是子规范
使用start_child/2来添加的子进程表现出像其他子进程一样的行为,除了这点:如果supervisor死掉然后重启,则所有动态添加的子进程都将丢失

8,停止一个子进程


任何子进程,不管静态的还是动态的,都可以使用shutdown规范来停止:

supervisor:terminate_child(Sup, Id)

停止的子进程的子规范使用如下调用来删除:

supervisor:delete_child(Sup, Id)

Sup是supervisor的pid或name,Id是子规范里指定的id
就像动态添加的子进程一样,如果supervisor本身重启,那么删除静态子进程的效果会丢失

9,simple_one_for_one supervisor


simple_one_for_one重启策略的supervisor是一个简化的one_for_one supervisor,所有的子进程都是动态添加的同一进程的实例
一个simple_one_for_one supervisor callback模块的例子:

-module(simple_sup).
-behaviour(supervisor).
 
-export([start_link/0]).
-export([init/1]).
 
start_link() ->
  supervisor:start_link(simple_sup, []).
 
init(_Args) ->
  {ok, {{simple_one_for_one, 0, 1},
    [{call, {call, start_link, []},
      temporary, brutal_kill, worker, [call]}]}}.
-module(simple_sup).
-behaviour(supervisor).
 
-export([start_link/0]).
-export([init/1]).
 
start_link() ->
  supervisor:start_link(simple_sup, []).
 
init(_Args) ->
  {ok, {{simple_one_for_one, 0, 1},
    [{call, {call, start_link, []},
      temporary, brutal_kill, worker, [call]}]}}.

当启动后,supervisor将不会启动任何子进程,而是通过调用如下代码来动态添加所有的子进程:

supervisor:start_child(Sup, List)

Sup是supervisor的pid或name,List是一个任意的term列表,将会被动态添加到子规范的参数列表里
如果启动方法指定为{M, F, A},则子进程通过调用apply(M, F, A++List)来启动
例如,添加一个子进程到simple_sup:

supervisor:start_child(Pid, [id1])

这将会通过调用apply(call, start_link, []++[id1])即call:start_link(id1)来启动子进程

10,终止


既然supervisor是supervision tree的一部分,则它将自动被它的supervisor终止
当终止时,它会按启动的反顺序根据相应的shudown规范来自动终止它所有的子进程,然后终止本身

补充:supervisor exports and callbacks

supervisor module                  Callback module
supervisor:start_link              Module:init/1
supervisor:start_child
supervisor:terminate_child
supervisor:delete_child
supervisor:restart_child
supervisor:which_children
supervisor:check_childspecs
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值