Programming Erlang读书笔记9: 并行程序里的错误

本文介绍了Erlang中进程间的连接方式及错误处理机制,包括使用BIFlink连接节点、设置进程标志trap_exit来捕获进程退出信号的方法,并提供了三种处理进程崩溃的常见模式。
使用BIF link将两个节点连接起来,如果其中一个节点B退出,则另一个节点A会收到{'EXIT', B, Why}的信号

可以创建一个on_exit(Pid, Fun)方法来捕获某个Pid进程的死掉:
[code]
on_exit(Pid, Fun) ->
spawn(fun() ->
process_flag(trap_exit, true),
link(Pid),
receive
{'EXIT', Pid, Why} ->
Fun(Why)
end
end).
[/code]

Erlang可以远程捕获和处理错误(跨机器)

调用BIF process_flag(trap_exit, true)来将一个正常的进程转换为一个可以trap exits的系统进程

[code]
trap_exit Exit Signal Action
true kill Die: Broadcast the exit signal killed to the link set.
true X Add {'EXIT', Pid, X} to the mailbox.
false normal Continue: Do-nothing signal vanishes.
false kill Die: Broadcast the exit signal killed to the link set.
false X Die: Broadcast the exit signal X to the link set.
[/code]

Idiom1: I Don't Care If a Process I Created Crashes
[code]
Pid = spawn(fun() -> ... end)
[/code]

Idiom2: I Want to Die If a Process I Created Crashes
[code]
Pid = spawn_link(fun() -> ... end)
[/code]

Idiom3: I Want to Handle Errors If a Process I Create Crashes
[code]
...
process_flag(trap_exit, true),
Pid = spawn_link(fun() -> ... end),
...
loop(...).

loop(State) ->
receive
{'EXIT', SomePid, Reason} ->
%% do something with the error
loop(State1);
...
end
[/code]

Error Handling Primitives
[code]
@spec spawn_link(Fun) -> Pid

@spec process_flag(trap_exit, true)

@spec link(Pid) -> true

@spec unlink(Pid) -> true

@spec exit(Why) -> none()

@spec exit(Pid, Why) -> true

@spec erlang:monitor(process, Item) -> MonitorRef
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值