Nic*_*Saw 2 erlang erlang-otp gen-server
我是Erlang开发的新手,我对流程关系很感兴趣.
如果我们连接两个进程P1和P2与process_flag(trap_exit, true)和使用建筑像Pid ! msg和receive .. after .. end-有可能赶上P1错误,如badarith第二进程P2.
但是如果我们使用gen_server与P2链接的进程P1,则P1在P2失败后终止.
那么,如何exit()使用gen_server 捕获错误?
提前致谢!
PS测试代码.
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.
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
结果: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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |