I'm new in Erlang development and I'm interested in processes relationship.
If we link two processes P1 and P2 with process_flag(trap_exit, true)
and use construction like Pid ! msg
and receive .. after .. end
- it's possible to catch P1 errors like badarith
by the second process P2.
But if we use gen_server
process P1 , which is linked with P2, - P1 terminates after P2 fails.
So, How to catch exit()
errors using gen_server?
Thanks in advance!
P.S. Testing code.
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.
Result: test1 process fails after test2 exits with badarith.
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>
Linking is bidirectional, but trapping exits isn't; you need to call process_flag(trap_exit, true)
in P1 (your current code does it in P2), and then handle messages of the form {'EXIT', FromPid, Reason}
in handle_info
(put P2's pid into State
to help).
In this case it makes sense for P2 to stop if P1 does, otherwise I'd suggest using a monitor instead of a link.
Side notes:
Use spawn_link
instead of spawn
+ link
.
It's better style to move spawn
into test2:start
.