开发者

Erlang gen_event don't work

I try to write simple gen_event applcation in erlang.

My code:

-module(test).
-behavior(gen_event).

-export([notify/0]).

%% API
-export([start_link/0, add_handler/0, stop/0]).

%% gen_event callbacks
-export([init/1, handle_event/2, handle_call/2, 
     handle_info/2, terminate/2, code_change/3]).

-define(SERVER, ?MODULE). 

start_link() ->
    gen_event:start_link({local, ?SERVER}).

add_handler() ->
    gen_event:add_handler(?SERVER, ?MODULE, []).

stop() ->
    gen_event:stop(?MODULE).

init([]) ->
    %add_handler(),
    {ok, null}.

handle_event(_Event, State) ->
    {ok, State};
handle_event({test}, State) ->
    io:format("Test"),
    {ok, State}.

handle_call(_Request, S开发者_运维技巧tate) ->
    Reply = ok,
    {ok, Reply, State}.

handle_info(_Info, State) ->
    {ok, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

notify() ->
    gen_event:notify(?SERVER, {test}).

When i try notify i expect that function handle_event({test}, State) execute but nothing occurs. Why? What's wrong?

And where i can see simple example of gen_event?

Thank you.


Well, you have reversed your handle_event clauses. The first one will always match, so you won't reach the {test} clause.

As far as I know, the best online documentation is http://www.erlang.org/doc/design_principles/events.html. But I can recommend e.g. the book Erlang and OTP in action http://www.amazon.com/Erlang-OTP-Action-Martin-Logan/dp/1933988789


Apart from swapping the clauses as @E Dominique mentioned have you actually added a handler using test:add_handler()? The call test:start_link() just starts the event manager, you need to tell it what to do by adding handlers. This even if the handler code is in the same module as the manager. This is generally not good practice even if alarm_handler which is part of sasl does this.

Doing this your code works writing "Test" when it gets an event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜