zoukankan      html  css  js  c++  java
  • 如何设置gen_server在退出时执行相关操作

              如果gen_server在监控树中不需要stop函数,gen_server会由其supervisor根据shutdown策略自动终止掉.如果要在进程终止之前执行清理,shutdown策略必须设定一个timeout值而不是brutal_kill并且gen_server要在init设置trap_exit.当被supervisor命令shutdown的时候,gen_server会调用terminnate(shutdown,State),特别注意: 被supervisor终止掉,终止的原因是Reason=shutdown,这个我们之前也

    init(Args) ->
    ...,
    process_flag(trap_exit, true),
    ...,
    {ok, State}.
    ...
    terminate(shutdown, State) ->
    ..code forcleaning up here..
    ok.
    如果gen_server不是supervisor的一部分,stop方法就很有用了:
    ...
    export([stop/0]).
    ...
    stop() ->
    gen_server:cast(ch3, stop).
    ...
    handle_cast(stop, State) ->
    {stop, normal, State};
    handle_cast({free, Ch}, State) ->
    ....
    ...
    terminate(normal, State) ->
    ok.
    通过调用terminate方法,gen_server可以优雅的关闭掉了. 如果结束的消息不是normal,shutdowngen_server就会被认为是异常终止并通过error_logger:format/2产生错误报告.
    Note: if any reason other than normal, shutdown or {shutdown, Term} is used whenterminate/2 is called, the OTP framework will see this as a failure and start logging a bunch of stuff here and there for you.
     
  • 相关阅读:
    LeetCode Best Time to Buy and Sell Stock
    LeetCode Scramble String
    LeetCode Search in Rotated Sorted Array II
    LeetCode Gas Station
    LeetCode Insertion Sort List
    LeetCode Maximal Rectangle
    Oracle procedure
    浏览器下载代码
    Shell check IP
    KVM- 存储池配置
  • 原文地址:https://www.cnblogs.com/riasky/p/3430941.html
Copyright © 2011-2022 走看看