一、从start方法产出的独立gen_server进程

实验代码:

%%%--------------------------------------
%%% @Module  :
%%% @Author  :
%%% @Email   :
%%% @Created :
%%% @Description:
%%%--------------------------------------
-module(ter_a).
-behaviour(gen_server).

%% gen_server callbacks exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
     terminate/2, code_change/3]).
%% gen_server api exports
-export([start/1, link/1, is_alive/0, mistake/0, stop/1]).

-record(state, {}).

%%====================================================================
%% API
%%====================================================================
start(Flag) ->
    gen_server:start({local, ?MODULE}, ?MODULE, [Flag], []).

link(Flag) ->
    gen_server:call(?MODULE, {link, Flag}).

is_alive() ->
    gen_server:call(?MODULE, is_alive).

mistake() ->
    gen_server:cast(?MODULE, mistake).

stop(Reason) ->
    gen_server:cast(?MODULE, {stop, Reason}).

%%====================================================================
%% gen_server callbacks
%%====================================================================
init([Flag]) ->
    case Flag of
        0 -> skip;
        _ -> process_flag(trap_exit, true)
    end,
    {ok, #state{}}.

handle_call({link, Flag}, _From, State) ->
    {ok, Pid} = ter_b:start_link(Flag),
    io:format("handle_call, link to ter_b, LinkPid:~p~n", [Pid]),
    {reply, Pid, State};

handle_call(is_alive, _From, State) ->
    io:format("yes, i'm alive~n"),
    {reply, alive, State};

handle_call(Request, _From, State) ->
    io:format("handle_call, Request:~p~n", [Request]),
    Reply = ok,
    {reply, Reply, State}.

handle_cast(mistake, State) ->
    A = 0,
    _B = 1 / A,
    {noreply, State};

handle_cast({stop, Reason}, State) ->
    io:format("handle_cast, stop, Reason:~p~n", [Reason]),
    {stop, Reason, State};

handle_cast(Msg, State) ->
    io:format("handle_cast, Msg:~p~n", [Msg]),
    {noreply, State}.

handle_info(Info, State) ->
    io:format("handle_info, Info:~p~n", [Info]),
    {noreply, State}.

terminate(Reason, _State) ->
    io:format("terminate, Reason:~p~n", [Reason]),
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

1) 无论有没有在初始化的时候捕捉退出即process_flag(trap_exit, true),只要回调函数以{stop, Reason, State}或者{stop, Reason, State}结束,则都会跑到terminate/2。特别的如果Reson为normal、shutdown或者{shutdown, ElseInfo},进程会正常退出,否则进程会报错然后才退出。部分实验数据如下:

1> ter_a:start(0).
{ok,<0.33.0>}
2> ter_a:stop(normal).
handle_cast, stop, Reason:normal
terminate, Reason:normal
ok
3> ter_a:start(1).
{ok,<0.36.0>}
4> ter_a:stop(else).
handle_cast, stop, Reason:else
terminate, Reason:else
ok
5>
=ERROR REPORT==== 28-Apr-2015::10:38:42 ===
** Generic server ter_a terminating
** Last message in was {'$gen_cast',{stop,else}}
** When Server state == {state}
** Reason for termination ==
** else

实际上,可以通过gen_server的源码了解到这些东西:

dispatch({'$gen_cast', Msg}, Mod, State) ->
Mod:handle_cast(Msg, State);
dispatch(Info, Mod, State) ->
Mod:handle_info(Info, State). handle_msg({'$gen_call', From, Msg}, Parent, Name, State, Mod) ->
case catch Mod:handle_call(Msg, From, State) of
...
{stop, Reason, Reply, NState} ->
{'EXIT', R} =
(catch terminate(Reason, Name, Msg, Mod, NState, [])),
reply(From, Reply),
exit(R);
Other -> handle_common_reply(Other, Parent, Name, Msg, Mod, State)
end;
handle_msg(Msg, Parent, Name, State, Mod) ->
Reply = (catch dispatch(Msg, Mod, State)),
handle_common_reply(Reply, Parent, Name, Msg, Mod, State). handle_msg({'$gen_call', From, Msg}, Parent, Name, State, Mod, Debug) ->
case catch Mod:handle_call(Msg, From, State) of
...
{stop, Reason, Reply, NState} ->
{'EXIT', R} =
(catch terminate(Reason, Name, Msg, Mod, NState, Debug)),
_ = reply(Name, From, Reply, NState, Debug),
exit(R);
Other ->
handle_common_reply(Other, Parent, Name, Msg, Mod, State, Debug)
end;
handle_msg(Msg, Parent, Name, State, Mod, Debug) ->
Reply = (catch dispatch(Msg, Mod, State)),
handle_common_reply(Reply, Parent, Name, Msg, Mod, State, Debug). handle_common_reply(Reply, Parent, Name, Msg, Mod, State) ->
case Reply of
...
{stop, Reason, NState} ->
terminate(Reason, Name, Msg, Mod, NState, []);
{'EXIT', What} ->
        terminate(What, Name, Msg, Mod, State, []);
_ ->
terminate({bad_return_value, Reply}, Name, Msg, Mod, State, [])
end. handle_common_reply(Reply, Parent, Name, Msg, Mod, State, Debug) ->
case Reply of
...
{stop, Reason, NState} ->
terminate(Reason, Name, Msg, Mod, NState, Debug);
{'EXIT', What} ->
        terminate(What, Name, Msg, Mod, State, Debug);
_ ->
terminate({bad_return_value, Reply}, Name, Msg, Mod, State, Debug)
end.
 

terminate(Reason, Name, Msg, Mod, State, Debug) ->
    case catch Mod:terminate(Reason, State) of

{'EXIT', R} ->

FmtState = format_status(terminate, Mod, get(), State),

error_info(R, Name, Msg, FmtState, Debug),

exit(R);

_ ->

case Reason of

normal ->

exit(normal);

shutdown ->

exit(shutdown);

{shutdown,_}=Shutdown ->

exit(Shutdown);

_ ->

FmtState = format_status(terminate, Mod, get(), State),

error_info(Reason, Name, Msg, FmtState, Debug),

exit(Reason)

end

end.

2) 从外部用exit(Pid, Reason)去杀死这个进程的情况

a) 只要Reason不是normal或者kill,如果进程没有捕捉退出,则进程会以Reason的理由直接退出,不会跑到terminate/2;如果有捕捉退出,进程不会退出,而且这个操作会转换成一条法外消息{'EXIT', From, Reason}发到进程,由handle_info处理:

1> {ok, Pid} = ter_a:start(0).
{ok,<0.33.0>}
2> exit(Pid, else).
true
3> ter_a:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_a,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)
4> {ok, Pid1} = ter_a:start(1).
{ok,<0.38.0>}
5> exit(Pid1, else).
handle_info, Info:{'EXIT',<0.36.0>,else}
true
6> ter_a:is_alive().
yes, i'm alive
alive

b) Reason是normal,如果进程没有捕捉退出,则进程不会退出;如果有捕捉退出,进程也不会退出,只会转为{'EXIT', From, normal}消息投递到Info的消息{'EXIT', From, normal}消息投递到进程信箱,由handle_info处理:

1> {ok, Pid0} = ter_a:start(0).
{ok,<0.33.0>}
2> exit(Pid0, normal).
true
3> ter_a:is_alive().
yes, i'm alive
alive
4> ter_a:stop(normal).
handle_cast, stop, Reason:normal
terminate, Reason:normal
ok
5> {ok, Pid1} = ter_a:start(1).
{ok,<0.38.0>}
6> exit(Pid1, normal).
handle_info, Info:{'EXIT',<0.31.0>,normal}
true
7> ter_a:is_alive().
yes, i'm alive
alive

c) Reason是kill,无论进程有没有捕捉退出,进程都会无条件退出,而且不会跑到terminate/2:

1> {ok, Pid0} = ter_a:start(0).
{ok,<0.33.0>}
2> exit(Pid0, kill).
true
3> ter_a:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_a,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)
4> {ok, Pid1} = ter_a:start(1).
{ok,<0.38.0>}
5> exit(Pid1, kill).
true
6> ter_a:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_a,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)

二、gen_server进程相互链接的情况(假如有进程A、B)

进程B的代码如下:

%%%--------------------------------------
%%% @Module :
%%% @Author :
%%% @Email :
%%% @Created :
%%% @Description:
%%%--------------------------------------
-module(ter_b).
-behaviour(gen_server). %% gen_server callbacks exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]). %% gen_server api exports
-export([start_link/1, is_alive/0]).
-record(state, {}). %%====================================================================
%% API
%%====================================================================
start_link(Flag) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [Flag], []). is_alive() ->
gen_server:call(?MODULE, is_alive). %%====================================================================
%% gen_server callbacks
%%==================================================================== init([Flag]) ->
case Flag of
0 -> skip;
_ ->
process_flag(trap_exit, true)
end,
{ok, #state{}}. handle_call(is_alive, _From, State) ->
io:format("ter_b, i'm alive~n"),
{reply, alive, State}; handle_call(_Request, _From, State) ->
io:format("ter_b, handle_call, _Request:~p~n", [_Request]),
Reply = ok,
{reply, Reply, State}. handle_cast(_Msg, State) ->
io:format("ter_b, handle_cast, Msg:~p~n", [_Msg]),
{noreply, State}. handle_info(_Info, State) ->
io:format(ter_b, "handle_info, Msg:~p~n", [_Info]),
{noreply, State}. terminate(_Reason, _State) ->
io:format("ter_b, terminate~n"),
ok. code_change(_OldVsn, State, _Extra) ->
{ok, State}.

1) B不捕捉退出,如果A异常退出,则B也会随之退出,A进程会跑到terminate/2而B进程不会;如果A正常退出,则B不做任何处理:

异常退出:

1> ter_a:start(0).
{ok,<0.33.0>}
2> ter_a:link(0).
handle_call, link to ter_b, LinkPid:<0.35.0>
<0.35.0>
3> ter_a:mistake().
terminate, Reason:{badarith,
[{ter_a,handle_cast,2,[{file,"ter_a.erl"},{line,63}]},
{gen_server,handle_msg,5,
[{file,"gen_server.erl"},{line,599}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,237}]}]}
ok
4>
=ERROR REPORT==== 28-Apr-2015::11:35:25 ===
** Generic server ter_a terminating
** Last message in was {'$gen_cast',mistake}
** When Server state == {state}
** Reason for termination ==
** {badarith,[{ter_a,handle_cast,2,[{file,"ter_a.erl"},{line,63}]},
{gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,599}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,237}]}]} 4> ter_a:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_a,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)
5> ter_b:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_b,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)

正常退出:

1> ter_a:start(0).
{ok,<0.33.0>}
2> ter_a:link(0).
handle_call, link to ter_b, LinkPid:<0.35.0>
<0.35.0>
3> ter_a:stop(normal).
handle_cast, stop, Reason:normal
terminate, Reason:normal
ok
4> ter_a:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_a,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)
5> ter_b:is_alive().
ter_b, i'm alive
alive

2) B捕捉退出,只要A退出,B都会随着退出,两个进程都会跑到terminate/2:

异常退出:

Eshell V6.2  (abort with ^G)
1> ter_a:start(0).
{ok,<0.33.0>}
2> ter_a:link(1).
handle_call, link to ter_b, LinkPid:<0.35.0>
<0.35.0>
3> ter_a:mistake().
terminate, Reason:{badarith,
[{ter_a,handle_cast,2,[{file,"ter_a.erl"},{line,63}]},
{gen_server,handle_msg,5,
[{file,"gen_server.erl"},{line,599}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,237}]}]}
ter_b, terminate
ok
4>
=ERROR REPORT==== 28-Apr-2015::11:40:11 ===
** Generic server ter_a terminating
** Last message in was {'$gen_cast',mistake}
** When Server state == {state}
** Reason for termination ==
** {badarith,[{ter_a,handle_cast,2,[{file,"ter_a.erl"},{line,63}]},
{gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,599}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,237}]}]} =ERROR REPORT==== 28-Apr-2015::11:40:11 ===
** Generic server ter_b terminating
** Last message in was {'EXIT',<0.33.0>,
{badarith,
[{ter_a,handle_cast,2,
[{file,"ter_a.erl"},{line,63}]},
{gen_server,handle_msg,5,
[{file,"gen_server.erl"},{line,599}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,237}]}]}}
** When Server state == {state}
** Reason for termination ==
** {badarith,[{ter_a,handle_cast,2,[{file,"ter_a.erl"},{line,63}]},
{gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,599}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,237}]}]} 4> ter_a:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_a,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)
5> ter_b:is_alive().
** exception exit: {noproc,{gen_server,call,[ter_b,is_alive]}}
in function gen_server:call/2 (gen_server.erl, line 182)

正常退出:

1> ter_a:start(0).
{ok,<0.33.0>}
2> ter_a:link(1).
handle_call, link to ter_b, LinkPid:<0.35.0>
<0.35.0>
3> ter_a:stop(normal).
handle_cast, stop, Reason:normal
terminate, Reason:normal
ok
ter_b, terminate

三、一些结论和补充

1) 在gen_server中,进程结束时不是什么情况都会跑到terminat/2函数;

2)  如果有两个gen_server进程相互链接,需要让两个进程同时存在同时消亡(无论原因),并且在消亡的时候都保证要跑到terminate/2去,则需要给每个进程捕获退出消息process_flag(trap_exit, true);

3) 如果gen_server进程是supervision tree的一部分,并且由supervision去终止,只要符合以下条件terminate/2就会以shutdown作为Reason被调用

a) gen_server进程捕获退出;

b) 在supervision关于这个gen_server子策略中,Shutdown的值是一个整数,而非brutal_kill .

(完)

[erlang 002]gen_server中何时会跑到terminate函数的更多相关文章

  1. Erlang模块gen_server翻译

    gen_server 概要: 通用服务器行为描述: 行为模块实现服务器的客户端-服务器关系.一个通用的服务器进程使用这个模块将实现一组标准的接口功能,包括跟踪和错误报告功能.它也符合OTP进程监控树. ...

  2. Erlang的gen_server的terminate()/2未执行

    官方资料参考: Module:terminate(Reason, State) Types: Reason = normal | shutdown | {shutdown,term()} | term ...

  3. 转载: 让我们聊聊Erlang的nif中资源的安全释放

    让我们聊聊Erlang的nif中资源的安全释放 http://my.oschina.net/u/236698/blog/479221

  4. 专访探探DBA张文升:PG在互联网应用中同样也跑的很欢畅

    张文升认为,PG无论在可靠性和性能方面都不输其它任何关系型数据库   张文升,探探DBA,负责探探的数据库架构.运维和调优的工作.拥有8年开发经验,曾任去哪儿网DBA.   9月24日,张文升将参加在 ...

  5. C语言学习笔记 (002) - C++中引用和指针的区别(转载)

    下面用通俗易懂的话来概述一下: 指针-对于一个类型T,T*就是指向T的指针类型,也即一个T*类型的变量能够保存一个T对象的地址,而类型T是可以加一些限定词的,如const.volatile等等.见下图 ...

  6. hive中的lateral view 与 explode函数的使用

    hive中的lateral view 与 explode函数的使用 背景介绍: explode与lateral view在关系型数据库中本身是不该出现的. 因为他的出现本身就是在操作不满足第一范式的数 ...

  7. MATLAB中白噪声的WGN和AWGN函数的使用

    MATLAB中白噪声的WGN和AWGN函数的使用如下: MATLAB中产生高斯白噪声非常方便,可以直接应用两个函数,一个是WGN,另一个是AWGN.WGN用于产生高斯白噪声,AWGN则用于在某一 信号 ...

  8. FastReport调用Delphi中的人民币大写转换自定义函数

    FastReport调用Delphi中的人民币大写转换自定义函数   FastReport调用Delphi中的人民币大写转换自定义函数 function TJzpzEdit1.MoneyCn(mmje ...

  9. Matlab中如何将(自定义)函数作为参数传递给另一个函数

    假如我们编写了一个积分通用程序,想使它更具有通用性,那么可以把被积函数也作为一个参数.在c/c++中,可以使用函数指针来实现上边的功能,在matlab中如何实现呢?使用函数句柄--这时类似于函数指针的 ...

随机推荐

  1. JavaFX 之窗口跳转(一)

    一.前言 笔者此处不讲JavaFX的基础API,只针对笔者工作时遇到的问题进行记录与总结. 零基础的网友可以访问 http://www.javafxchina.net/blog/docs/tutori ...

  2. 利用OsCache实现后端轮循

    轮循随处可见,最常用的是APP首页的一些促销活动,一两秒切换一张图片,让前端实现起来也不难.这里说下后端的轮循,实现原理是数组+缓存.将数组放入缓存,指定缓存失效时间,如果是在失效前从缓存中取数据,那 ...

  3. 关于NHibernate的一些代码

    SessionManager using System; using System.IO; using System.Runtime.Serialization; using System.Runti ...

  4. javascript基础-js对象

    一.js对象的创建 1.普通最简单的方式 var teacher = new Object( ); teacher.name = "zhangsan"; teacher.age = ...

  5. FPGA的新变化

    FPGA SoC通过融合FPGA和ASIC两者的元件,跨越了灵活性和性能之间的界限.但随着它们进入高安全性.任务关键型市场,它们也面临着与标准SoC相同的问题,包括在日益复杂的器件中快速传输越来越多的 ...

  6. 以太坊客户端Geth命令用法

    命令用法 geth [选项] 命令 [命令选项] [参数…] 命令: account 管理账户attach 启动交互式JavaScript环境(连接到节点)bug 上报bug Issuesconsol ...

  7. 【转】Jmeter之短板以及建议解决方案

    随着JMeter的应用,发现JMeter的局限性越来越多,急需进一步扩展改进. 一.几百兆的sample 日志解析出现OutOfMemory 最近的几个项目都是Java sample 日志,应用都是高 ...

  8. appium+python自动化30-list定位(find_elements)

    前言 有时候页面上没有id属性,并且其它的属性不唯一,平常用的比较多的是单数(element)的定位方法,遇到元素属性不唯一,就无法直接定位到了. 于是我们可以通过复数(elements)定位,先定位 ...

  9. TCP之三:TCP/IP协议中backlog参数(队列参数)

    目录: <TCP洪水攻击(SYN Flood)的诊断和处理> <TCP/IP协议中backlog参数> TCP建立连接是要进行三次握手,但是否完成三次握手后,服务器就处理(ac ...

  10. GC之八--GC 触发Full GC执行的情况及应对策略

    目录: GC之一--GC 的算法分析.垃圾收集器.内存分配策略介绍 GC之二--GC日志分析(jdk1.8)整理中 GC之三--GC 触发Full GC执行的情况及应对策略 gc之四--Minor G ...