Skip to content

Instantly share code, notes, and snippets.

@iain17
Created April 6, 2017 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iain17/250e5030f75a03edaa73e9237c0cd1ec to your computer and use it in GitHub Desktop.
Save iain17/250e5030f75a03edaa73e9237c0cd1ec to your computer and use it in GitHub Desktop.
-module(doctor_translate).
-export([loop/0, watch/0]).
%Assignments:
%Make the Doctor process restart itself if it should die.
%+
%Make a monitor for the Doctor monitor. If either monitor dies, restart it.
loop() ->
process_flag(trap_exit, true),
receive
new ->
io:format("Creating and monitoring process.~n"),
register(translator, spawn_link(fun translate_service:loop/0)),
loop();
{'EXIT', From, Reason} ->
io:format("The translate service ~p died with reason ~p.~n", [From, Reason]),
io:format("Restarting... ~n"),
self() ! new,
loop()
end.
watch() ->
process_flag(trap_exit, true),
receive
new ->
io:format("Creating and monitoring new Doctor process.~n"),
register(doctor, spawn_link(fun loop/0)),
doctor ! new,
watch();
{'EXIT', From, Reason} ->
io:format("The translate service doctor ~p died with reason ~p.~n", [From, Reason]),
io:format("Restarting... ~n"),
self() ! new,
watch()
end.
% Based on: https://media.pragprog.com/titles/btlang/code/erlang/translate_service.erl
-module(translate_service).
-export([loop/0, translate/2]).
%Assignment: Monitor the translate_service and restart it should it die.
loop() ->
receive
{From, "casa"} ->
From ! "house",
loop();
{From, "blanca"} ->
From ! "white",
loop();
{From, _} ->
From ! "I don't understand.",
exit("Undefined word.")
end.
translate(To, Word) ->
To ! {self(), Word},
receive
Translation -> Translation
end.

Usage

c(translate_service).
c(doctor_translate).

Doctor = spawn(fun doctor_translate:watch/0).
Doctor ! new.

translate_service:translate(translator, "casa").
translate_service:translate(translator, "blanca").
translate_service:translate(translator, "incorrect").
translate_service:translate(translator, "casa").
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment