concurrency - Can I catch an external exit in Erlang? -
i have 2 processes linked; let's they're a
, b
, a
set trap exits. want able recover piece of b
's process data if calls exit/2
on it, e.g. exit(b, diediedie)
.
in b
's module, let's call bmod.erl
, have code looks this:
-module(bmod). -export([b_start/2]). b_start(a, x) -> spawn(fun() -> b_main(a, x) end). b_main(a, x) -> try ! {self(), doing_stuff}, do_stuff() catch exit:_ -> exit({terminated, x}) end, b_main(a, x). do_stuff() -> io:format("doing stuff.~n",[]).
and in a
's module, let's call amod.erl
, have code looks this:
-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 terminated, had ~p.~n", [pid,x]), fine; {'exit', pid, _reason} -> io:format("process ~p terminated, can't find had.~n", [pid]), woops end.
(i realize should spawn_link
in original program there code in between spawn , link, , modeled example code way.)
now when run code, this.
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> terminated, can't find had. woops 5>
how b_main()
catch external exit can report state x
?
for b_main()
catch external exit, has trap exit calling process_flag(trap_exit, true)
. result in message process can exit state x
. code below
b_start(a, x) -> spawn(fun() -> process_flag(trap_exit, true), b_main(a, x) end). b_main(a, x) -> try ! {self(), doing_stuff}, do_stuff() catch exit:_ -> io:format("exit inside do_stuff() . ~n"), exit({terminated, x}) end, receive {'exit',pid, reason} -> io:format("process received exit ~p ~p.~n",[pid, reason]), exit({terminated, x}) after 0 -> ok end, b_main(a, x).
Comments
Post a Comment