More Related Content Similar to Erlang otpを触ってみた Similar to Erlang otpを触ってみた (20) More from Yoichi Toyota (20) Erlang otpを触ってみた7. -module(shop).
-behaviour(gen_server).
%% API
-export([start_link/0, open_shop/0, close_shop/0, is_opened/0, stop/0]).
-export([init/1, handle_call/3, handle_cast/2, terminate/2]).
start_link() ->
gen_server:start_link({local, shop}, shop, [], []).
open_shop() ->
gen_server:cast(shop, open_shop).
close_shop() ->
gen_server:cast(shop, close_shop).
is_opened() ->
gen_server:call(shop, is_opened).
stop() ->
gen_server:cast(shop, stop).
9. init([]) -> {ok, close}.
handle_cast(open_shop, State) ->
{noreply, open};
handle_cast(close_shop, State) ->
{noreply, close};
handle_cast(stop, State) ->
{stop, normal, State}.
handle_call(is_opened, _From, State) ->
{reply, State, State}.
terminate(normal, State) ->
ok.
12. 1> c(shop).
{ok,shop}
2> shop:start_link().
{ok,<0.41.0>}
3> shop:is_opened().
close
4> shop:open_shop().
ok
5> shop:is_opened().
open
6> shop:close_shop().
ok
7> shop:is_opened().
Close
8> shop:stop().
ok
9> shop:is_opened().
** exception exit: {noproc, {gen_server,call,[shop,is_opened]}}
in function gen_server:call/2 (gen_server.erl, line 180)
15. -module(shop_status).
-behaviour(gen_fsm).
-export([start_link/0, staff_comming/0, customer_coming/0])
-export([init/1, closed/2, opened/2, attending/2])
start_link() ->
gen_fsm:start_link({local, shop_status}, shop_status, [], []).
staff_coming() ->
gen_fsm:send_event(shop_status, staff_coming).
customer_coming() ->
gen_fsm:send_event(shop_status, customer_coming).
17. init(State) ->
{ok, closed, State}.
closed(staff_coming, State) ->
io:format("staff came. shop status is opened.~n"),
{next_state, opened, State, 60000}.
opened(customer_coming, State) ->
io:format("customer came. shop status is attending.~n"),
{next_state, attending, State, 5000};
opened(timeout, State) ->
io:format("staff left. shop status is closed.~n").
attending(timeout, State) ->
io:format("customer left. shop status is opened.~n"),
{next_state, opened, State, 60000}.
22. -module(shop_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link(shop_sup, []).
init(_Args) ->
{ok, {one_for_one, 1, 60},
[{shop_status, {shop_status, start_link, []},
permanent, brutal_kill, worker, [shop_status]}]
}}.