首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 服务器 > 云计算 >

谈一下erlang:exit/2

2012-11-04 
谈谈erlang:exit/2转载请注明,来自:http://blog.csdn.net/skyman_2001有同学用erlang:exit(Pid, normal)来

谈谈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 orkill:

If Pid is not trapping exits, Pid itself will exit with exit reasonReason. IfPid 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 reasonkilled.


简而言之,如果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()回调的!因为没捕捉退出消息。

热点排行