谈谈erlang:exit/2

转载请注明,来自:http://blog.csdn.net/skyman_2001

有同学用erlang:exit(Pid, normal)来关闭Pid进程,其实这样Pid进程是不会自动退出的。官方文档上对erlang:exit/2的说明讲得很清楚:

Sends an exit signal with exit reason Reason to the processPid.

The following behavior apply if Reason is any term exceptnormal or kill:

If Pid is not trapping exits, Pid itself will exit with exit reasonReason. If Pid is trapping exits, the exit signal is transformed into a message{'EXIT', From, Reason} and delivered to the message queue ofPid. From is the pid of the process which sent the exit signal. See alsoprocess_flag/2.

If Reason is the atom normal,Pid will not exit. If it is trapping exits, the exit signal is transformed into a message{'EXIT', From, normal} and delivered to its message queue.

If Reason is the atom kill, that is ifexit(Pid, kill) is called, an untrappable exit signal is sent toPid which will unconditionally exit with exit reason killed.


简而言之,如果Reason是kill,那么是不能被捕获的,会无条件退出;
如果Reason是normal,则进程是不会退出的,如果该进程设置了捕获退出消息,则会收到{'EXIT',From,normal}消息;
如果Reason是原子值,则如果进程设置为不捕获退出消息,则该进程会退出;但如果设置了捕获退出消息,则不会退出,而是收到{'EXIT',From,Reason}消息。

进程要设置为捕获退出消息,在进程初始化时调用:process_flag(trap_exit,true)。
这个知识点容易混淆,我们要理解清楚透彻,避免用错。

还有就是如果是gen_server进程,最好不要直接用exit(),推荐这样:
stop(Pid) when is_pid(Pid) ->
gen_server:cast(Pid, stop).


handle_cast(stop, State) ->
{stop, normal, State};

返回{stop,normal,State},该gen_server进程会调用terminate()回调然后终止。

注意:通过eixt(Pid,shutdown)或exit(Pid,kill)来终止gen_server进程,该gen_server进程是不会调用terminate()回调的!因为没捕捉退出消息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值