Skip to content

Instantly share code, notes, and snippets.

@iain17 iain17/Usage.md

Last active Apr 6, 2017
Embed
What would you like to do?
% 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.

Usage

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").
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.