c(translate_service).
Service = spawn(fun translate_service:watch_loop/0).
Service ! new.
translate_service:translate(translator, "casa").
translate_service:translate(translator, "blanca").
translate_service:translate(translator, "incorrect").
translate_service:translate(translator, "casa").
Last active
April 6, 2017 21:24
-
-
Save iain17/b9cea6c90957b977877896735f690c9b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% Based on: https://media.pragprog.com/titles/btlang/code/erlang/translate_service.erl | |
-module(translate_service). | |
-export([loop/0, translate/2, watch_loop/0]). | |
%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. | |
% based on: https://media.pragprog.com/titles/btlang/code/erlang/doctor.erl | |
% This method has to be blow the above method it seems. | |
watch_loop() -> | |
process_flag(trap_exit, true), | |
receive | |
new -> | |
io:format("Creating and monitoring process.~n"), | |
register(translator, spawn_link(fun loop/0)), | |
watch_loop(); | |
{'EXIT', From, Reason} -> | |
io:format("~nTranslator ~p died with reason ~p", [From, Reason]), | |
io:format(" Restarting. ~n"), | |
self() ! new, | |
watch_loop() | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment