Search code examples
erlangerlang-otpgen-server

Should I not call gen_server:stop() directly?


In the LYSE book the author handles the termination of the server as follows:

%% Synchronous call
close_shop(Pid) -> gen_server:call(Pid, terminate).

handle_call(terminate, _From, Cats) ->
    {stop, normal, ok, Cats}.

terminate(normal, Cats) ->
    [io:format("~p was set free.~n",[C#cat.name]) || C <- Cats],
    ok.

So it returns a stop value from the handle_call callback.

Here is how I wrote it:

close_shop(Pid) -> gen_server:stop(Pid).

terminate(_Reason, {Cats, Money}) ->
    io:format("Made $~w~n", [Money]),
    [io:format("~p was set free.~n",[C#cat.name]) || C <- Cats].

Is this not a good practice then to call gen_server:stop() directly?


Solution

  • It is not a bad practice to call gen_server:stop/1,3 directly. It does an almost same thing as the example from LYSE but without calling handle_call/3 from your module. Try and check it out. You can even read the source code to be sure.