进程终止
进程终止
当一个进程的进程执行函数(通过spawn/4创建进程时第3个参数所指定的函数)执行完毕,或是(在catch之外)执行exit(normal),便会正常退出。参见程序7.1:
test:start()
创建一个注册名为
my_name的进程来执行test:process()。
程序7.1
-module(test).
-export([process/0, start/0]).
start() ->
register(my_name, spawn(test, process, [])).
process() ->
receive
{stop, Method} ->
case Method of
return ->
true;
Other ->
exit(normal)
end;
Other ->
process()
end. my_name!{stop,return}
令
test:process()返回true,接着进程正常终止。
my_name!{stop,hello}
也会令进程正常终止,因为它执行了BIF
exit(normal)。
任何其它的消息,比如my_name!any_other_message都将令进程递归执行test:process()(采用尾递归优化的方式,参见第??章)从而避免进程终止。
若进程执行BIF exit(Reason),则进程将异常终止。其中Reason是除了 原子式normal以外的任意的Erlang项式。如我们所见,在catch上下文中执行exit(Reason)不会导致进程退出。
进程在执行到会导致运行时失败的代码(如除零错误)时,也会异常终止。后续还会讨论各种类型的运行时失败。
