停止

在监督树中

若genserver是某个监督树的一部分,则无需停止函数。它的督程会自动终止它。它的具体做法由督程中设置的 [关闭策略_]($cfa29cf763f4b135.md#shutdown) 定义。

如果在终止之前需要进行一些清理工作,那么关闭策略必须是一个超时值,同时gen_server必须在 init 函数中设置为捕获退出信号。当gen_server被要求关闭时,它就会调用回调函数 terminate(shutdown,State)

  1. init(Args) ->
  2. ...,
  3. process_flag(trap_exit, true),
  4. ...,
  5. {ok, State}.
  6.  
  7. ...
  8.  
  9. terminate(shutdown, State) ->
  10. ..code for cleaning up here..
  11. ok.

独立Gen_Server

如果gen_server并非某个监督树的一部分,那么可以用一个停止函数,例如:

  1. ...
  2. export([stop/0]).
  3. ...
  4.  
  5. stop() ->
  6. gen_server:cast(ch3, stop).
  7. ...
  8.  
  9. handle_cast(stop, State) ->
  10. {stop, normal, State};
  11. handle_cast({free, Ch}, State) ->
  12. ....
  13.  
  14. ...
  15.  
  16. terminate(normal, State) ->
  17. ok.

回调函数处理 stop 请求并返回一个元组 {stop,normal,State1} ,其中 normal 表示这是一个正常的终止, State1 是gen_server状态的新值。这会引发gen_server调用 terminate(normal,State1) 来优雅地终止。