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.
     
  • 相关阅读:
    查看dll定义的宏
    循环调用dll库的界面时,首次正常,再次无响应
    strftime使用%F格式化日期失败
    自己程序生成的二维码部分手机无法识别
    Drools规则
    idea快捷键
    风控文档笔记
    工作笔记
    工具方法
    BIO,NIO,AIO
  • 原文地址:https://www.cnblogs.com/riasky/p/3430941.html
Copyright © 2011-2022 走看看