gen_server定义了6个callback接口:
1
2
3
4
5
6
init/1
handle_call/3
handle_cast/2
handle_info/2
terminate/2
code_change/3
对于callback的实现者来说,理解callback函数的触发点是最重要的,本文只讨论terminate的调用。
terminate的被调用有如下几种情况:
handle_info | handle_cast返回 {stop, Reason, StateN} -> terminate(Reason, StateN) |
handle_call | handle_info | handle_cast 抛出异常(在gen_server.erl中被捕获为{‘EXIT’, What}) -> terminate(What, State) |
handle_call | handle_info | handle_cast 返回值非法 -> terminate({bad_return_value, Reply}, State) |
结论:
terminate被调用的方式有如下几种:
如果希望gen_server进程崩溃时terminate一定被调用到(exit(Pid, kill)除外),设为system进程即可。
以上仅仅是结论,通过查看源码,以及写测试代码得出。这里有一些用得到的测试代码: