Skip to content

Instantly share code, notes, and snippets.

@stormwatch
Created July 15, 2020 05:25
Show Gist options
  • Save stormwatch/39bac39cae21ed82e0b4b7487d66631b to your computer and use it in GitHub Desktop.
Save stormwatch/39bac39cae21ed82e0b4b7487d66631b to your computer and use it in GitHub Desktop.
-module(super).
-export([super/0]).
%% Comments on killing processes
%% 1. Without a supervisor:
%% evaluating ~exit(Pid,kill)~ kills Pid but the listener keeps looping.
%% If we were to kill the listener instead with ~exit(whereis(echo), kill)~ then
%% Pid would terminate as well with an error because it asumes a registered
%% process named 'echo' on talk.erl line 8 “echo!Msg”.
%% 2. When using the supervisor in =super.erl=
%% We must call ~observer:star()~ first in order to be able to kill processes spawned by =super/0=.
%% If we kill =talk=, =super= will trap its exit and respawn it.
%% If we kill =echo=, =super= will respawn it, and if we add the
%% ~timer:sleep(1000)~ instruction, =talk= will exit with error when it tries to
%% send a message to =echo= and it will be respawned by =super= as well.
super() ->
process_flag(trap_exit, true),
E = spawn_link(echo,listener,[]),
register(echo,E),
io:format("echo spawned.~n"),
T = spawn_link(talk,worker,[]),
register(talk,T),
io:format("worked spawned as Pid ~w.~n",[whereis(talk)]),
loop(E, T).
loop(E,T) ->
receive
{'EXIT', T, _} ->
NewT = spawn_link(talk,worker,[]),
register(talk,NewT),
io:format("worker re-spawned as Pid ~w.~n",[whereis(talk)]),
loop(E,NewT);
{'EXIT', E, _} ->
timer:sleep(1000),
NewE = spawn_link(echo,listener,[]),
register(echo,NewE),
io:format("echo re-spawned.~n"),
loop(NewE,T)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment