Skip to content

Instantly share code, notes, and snippets.

@michaeldperez
Created April 16, 2017 01:33
Show Gist options
  • Save michaeldperez/28aa02edacd80b9d0969a11452230c9a to your computer and use it in GitHub Desktop.
Save michaeldperez/28aa02edacd80b9d0969a11452230c9a to your computer and use it in GitHub Desktop.
Supervisor module for a frequency server
-module(superv).
-export([start/1, init/1]).
%% Starts the supervisor
%% Server has form {Module, Function, Args}
start(Server) ->
register(?MODULE,
spawn(?MODULE, init, [Server])).
%% Initializes the supervision process
init(Server) ->
process_flag(trap_exit, true),
loop(start_server(Server)).
%% Starts and links to the server
start_server({Module, Function, Args}) ->
apply(Module, Function, Args),
Pid = whereis(Module),
link(Pid),
{Pid, {Module, Function, Args}}.
%% The supervision loop
%% Listens for Exit signals from the server and restarts accordingly
%% If the supervisor receives a stop message, it terminates the server
loop({Pid, ServerInfo}) ->
receive
{'EXIT', Pid, _Reason} ->
unlink(Pid),
NewServerInfo = start_server(ServerInfo),
loop(NewServerInfo);
stop ->
terminate(Pid)
end.
%% Terminates a server
terminate(Pid) ->
exit(Pid, kill),
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment