我有两个流程链接;假设它们是A
and B
,并A
设置为陷阱出口。B
如果有人调用它,我希望能够恢复一段进程数据exit/2
,例如exit(B, diediedie)
。
在B
's 模块中,我们称之为它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
's 模块中,我们称之为它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
?