【发布时间】:2013-04-20 06:01:10
【问题描述】:
我有两个进程链接;假设他们是A 和B,A 设置为陷阱出口。如果有人在上面调用exit/2,我希望能够恢复B 的一部分进程数据,例如exit(B, diediedie).
在B 的模块中,我们称之为bmod.erl,我有一些代码如下所示:
-module(bmod).
-export([b_start/2]).
b_start(A, X) ->
spawn(fun() -> b_main(A, X) end).
b_main(A, X) ->
try
A ! {self(), doing_stuff},
do_stuff()
catch
exit:_ -> exit({terminated, X})
end,
b_main(A, X).
do_stuff() -> io:format("doing stuff.~n",[]).
在A 的模块中,我们称之为amod.erl,我有一些代码如下所示:
-module(amod).
-export([a_start/0]).
a_start() ->
process_flag(trap_exit, true),
link(bmod:b_start(self(), some_stuff_to_do)),
a_main().
a_main() ->
receive
{Pid, doing_stuff} ->
io:format("Process ~p did stuff.~n",[Pid]),
exit(Pid, diediedie),
a_main();
{'EXIT', Pid, {terminated, X}} ->
io:format("Process ~p was terminated, had ~p.~n", [Pid,X]),
fine;
{'EXIT', Pid, _Reason} ->
io:format("Process ~p was terminated, can't find what it had.~n", [Pid]),
woops
end.
(我意识到我应该正常使用spawn_link,但在我的原始程序中,spawn 和链接之间有代码,所以我以这种方式模拟了这个示例代码。)
现在当我运行代码时,我得到了这个。
2> c(amod).
{ok,amod}
3> c(bmod).
{ok,bmod}
4> amod:a_start().
doing stuff.
Process <0.44.0> did stuff.
doing stuff.
Process <0.44.0> did stuff.
Process <0.44.0> was terminated, can't find what it had.
woops
5>
如何让b_main() 捕获这个外部出口,以便它可以报告其状态X?
【问题讨论】:
标签: concurrency erlang try-catch exit