Mercurial > repos > other > SevenLanguagesInSevenWeeks
changeset 77:7bab4843aec6
Add roulette with auto-restarting process
(And black-magic auto-registering of atoms)
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sat, 03 Feb 2018 20:42:51 +0000 |
parents | 5860845f5dac |
children | 75dbcd30dee5 |
files | 5-Erlang/infinirun.erl 5-Erlang/roulette.erl |
diffstat | 2 files changed, 29 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/5-Erlang/infinirun.erl Sat Feb 03 20:42:51 2018 +0000 @@ -0,0 +1,21 @@ +-module(infinirun). +-export([loop/0]). + +% To run, call: Restarter = spawn(fun infinirun:loop/0). +% Then call Restarter ! new to initiate +% This does black magic and registers a public atom called "revolver", which is a process running roulette:loop/0 that can receive messages +loop() -> + % Indicate that we want exist signals, which are a 3-tuple of { 'EXIT', From, Reason } + process_flag(trap_exit, true), + receive + new -> + % Start a new process + io:format("Creating and monitoring process.~n"), + register(revolver, spawn_link(fun roulette:loop/0)), + loop(); + {'EXIT', From, Reason} -> + io:format("The shooter ~p died with reason ~p. Restarting…~n", [From, Reason]), + % Send ourselves a message to register a new process + self() ! new, + loop() +end. \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/5-Erlang/roulette.erl Sat Feb 03 20:42:51 2018 +0000 @@ -0,0 +1,8 @@ +-module(roulette). +-export([loop/0]). + +loop() -> + receive + 3 -> io:format("bang.~n"), exit({roulette, die, at, erlang:time()}); + _ -> io:format("click~n"), loop() +end. \ No newline at end of file