-
Notifications
You must be signed in to change notification settings - Fork 1
/
ex2behaviour.erl
executable file
·52 lines (40 loc) · 1.01 KB
/
ex2behaviour.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
-module(ex2behaviour).
-export([start/1, send/2]).
-export([init/2, behaviour_info/1]).
start(CallBack) ->
proc_lib:start_link(?MODULE, init, [self(), CallBack]).
send(Pid, Msg) ->
Pid ! {'$ex2behaviour', send, Msg}.
%%% Internal functions
init(Parent, CallBack) ->
try
{ok, State} = CallBack:init(),
proc_lib:init_ack(Parent, {ok, self()}),
loop(CallBack, State)
catch
_C:E ->
io:format("going down with ~p~n", [E]),
exit(E)
end.
behaviour_info(callbacks) ->
[{init, 0},
{handle_msg, 2}];
behaviour_info(_) ->
undefined.
loop(CallBack, State) ->
receive
{'$ex2behaviour', send, Msg} ->
case catch CallBack:handle_msg(Msg, State) of
{ok, NewState} ->
loop(CallBack, NewState);
{stop, NewState} ->
io:format("stopping process ~p with state ~p~n", [self(), NewState]),
ok;
Error ->
io:format("application error ~p~n", [Error]),
exit(Error)
end;
BadMsg ->
io:format("bad message ~p~n", [BadMsg]),
exit(BadMsg)
end.