Skip to content

Instantly share code, notes, and snippets.

@iain17 iain17/Usage.md
Created Apr 6, 2017

Embed
What would you like to do?
-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
You can’t perform that action at this time.