我是Erlang开发的新手,我对流程关系很感兴趣。
如果我们用process_flag(trap_exit, true)
链接两个进程P1和P2并使用像Pid ! msg
和receive .. after .. end
这样的结构 - 可以通过第二个进程P2捕获像badarith
这样的P1错误。
但是如果我们使用与P2链接的gen_server
进程P1,则P1在P2失败后终止。
那么,如何使用gen_server捕获exit()
错误?
提前致谢!
附:测试代码。
P1:
-module(test1).
-compile(export_all).
-behaviour(gen_server).
start() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init([]) -> Link = self(),
spawn(fun() ->
process_flag(trap_exit, true),
link(Link),
test2:start(Link)
end),
{ok, "lol"}.
handle_call(stop, From, State) ->
io:fwrite("Stop from ~p. State = ~p~n",[From, State]),
{stop, normal, "stopped", State};
handle_call(MSG, From, State) ->
io:fwrite("MSG ~p from ~p. State = ~p~n",[MSG, From, State]),
{reply, "okay", State}.
handle_info(Info, State) -> io:fwrite("Info message ~p. State = ~p~n",[Info, State]), {noreply, State}.
terminate(Reason, State) -> io:fwrite("Reason ~p. State ~p~n",[Reason, State]), ok.
P2:
-module(test2).
-compile(export_all).
start(Mod) ->
io:fwrite("test2: Im starting with Pid=~p~n",[self()]),
receiver(Mod).
receiver(Mod)->
receive
stop ->
Mod ! {goodbye},
io:fwrite("Pid: I exit~n"),
exit(badarith);
X ->
io:fwrite("Pid: I received ~p~n",[X])
end.
结果:test2进程因badarith退出test2后失败。
38>
38> c(test1).
test1.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,test1}
39> c(test2).
test2.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,test2}
40> test1:start().
test2: Im starting with Pid=<0.200.0>
{ok,<0.199.0>}
41> <0.200.0> ! stop.
Pid: I exit
Info message {goodbye}. State = "lol"
stop
** exception exit: badarith
42> gen_server:call(test1, stop).
** exception exit: {noproc,{gen_server,call,[test1,stop]}}
in function gen_server:call/2 (gen_server.erl, line 215)
43>
链接是双向的,但陷阱退出不是;你需要在P1中调用process_flag(trap_exit, true)
(你当前的代码在P2中执行),然后在{'EXIT', FromPid, Reason}
中处理handle_info
形式的消息(将P2的pid放入State
以帮助)。
在这种情况下,如果P1确实P2停止是有意义的,否则我建议使用monitor而不是链接。
附注:
spawn_link
而不是spawn
+ link
。spawn
移动到test2:start
是更好的风格。