I am using gen_event behaviour and apart from handling events, I wish to be able to handle other generic messages. According to the documentation these messages should be received through handle_info. However, this seems not to be working... unless I am missing something very obvious!
Here is my behaviour implementation:
-module(genevent).
-behaviour(gen_event).
-export([init/1, handle_event/2, handle_info/2, handle_call/2, terminate/2, start_link/0]).
init(_Args) -> {ok, []}.
handle_event(Event, State) ->
io:format("***Event*** ~p~n", [Event]),
{ok, State}.
handle_call(Call, State) ->
io:format("***Call*** ~p~n", [Call]),
{ok, State}.
handle_info(Info, State) ->
io:format("***Info*** ~p~n", [Info]),
{ok, State}.
start_link() -> gen_event:start_link({local, genevent}).
terminate(_Args, _State) -> ok.
And here is my usage
{ok,PID} = genevent:start_link(),
io:format("***Sending to*** ~p~n", [PID]),
PID ! {hello},
io:format("***Sent hello to*** ~p~n", [PID]).
The problem is that the code io:format("Info ~p~n", [Info]) is never reached.
I hope I am not doing something very stupid! Thanks
gen_event:start_link/1
just starts an event manager; it doesn't add your event handler to this new event manager. You need to do that yourself with gen_event:add_handler/3
:
1> c(genevent).
genevent.erl:3: Warning: undefined callback function code_change/3 (behaviour 'gen_event')
{ok,genevent}
2> {ok,PID} = genevent:start_link().
{ok,<0.38.0>}
3> gen_event:add_handler(PID, genevent, {}).
ok
4> PID ! foo.
***Info*** foo
foo