[erlang-questions] Killing a genserver

Peter Lemenkov lemenkov@REDACTED
Thu Oct 30 16:56:45 CET 2008


2008/10/30 BJörn Lindqvist <bjourne@REDACTED>:
> Hello good people!
>
> Here is my code for killing a genserver:
>
> -module(kill).
> -behaviour(gen_server).
> -compile(export_all).
>
> -export([code_change/3,
>         handle_call/3,
>         handle_cast/2,
>         handle_info/2,
>         init/1,
>         terminate/2]).
>
> code_change(_, _, _) ->
>    {ok, []}.
>
> init([]) ->
>    {ok, []}.
>
> handle_call(_, _, _) ->
>    {reply, [], []}.
>
> handle_cast(_, _) ->
>    {noreply, []}.
>
> handle_info(_, _) ->
>    {noreply, []}.
>
> terminate(_, _) ->
>    ok.
>
> start_stop(_) ->
>    {ok, Pid} = gen_server:start({local, kill}, kill, [], []),
>    MRef = erlang:monitor(process, Pid),
>    true = exit(Pid, kill),
>    receive
>        {'DOWN', MRef, process, Pid, killed} ->
>            ok
>    end,
>    erlang:demonitor(MRef).
>
> test_start_and_stop() ->
>    lists:foreach(fun start_stop/1, lists:seq(1, 10000)).
>
> I wonder if this is a good way of doing it? What I want is to send the
> exit signal to the process and then wait until the process has
> actually died. And this is the best way I've found. But it seem
> complicated, is there no shorter way?

Better way is to define function:

handle_cast(stop, State) ->
   {stop, {reason, "Just received stop message"}, State}.

and send a proper message to server:

gen_server:cast({local,kil}, stop).


-- 
With best regards!


More information about the erlang-questions mailing list