Alex Rivera | Logout

Erlang. Correct way to stop process

Asked 2011-11-01T17:39:23.563
12

Good day, i have following setup for my little service:

-module(mrtask_net).

-export([start/0, stop/0, listen/1]).

-define(SERVER, mrtask_net).

start() ->
    Pid = spawn_link(fun() -> ?MODULE:listen(4488) end),
    register(?SERVER, Pid),
    Pid.

stop() ->
    exit(?SERVER, ok).

....

And here is the repl excerpt:

(emacs@rover)83> mrtask_net:start().
<0.445.0>
(emacs@rover)84> mrtask_net:stop().
** exception error: bad argument
     in function  exit/2
        called as exit(mrtask_net,ok)
     in call from mrtask_net:stop/0
(emacs@rover)85> 

As you see, stopping process produces error, process is stopping though. What does this error mean and how to make thing clean ?

Edit
Report

1 Answer

2

I would suggest you to stick with OTP. It really gives you tons of advantages (I hardly can immagine the case where OTP doesn't benefit).

So, if you want to stop process in OTP you should do something like this for gen_server:

% process1.erl
% In case you get cast message {stopme, Message}
handle_cast({stopme, Message}, State) ->
    % you will stop
    {stop, normal, State}
handle_cast(Msg, State) ->
    % do your stuff here with msg
    {noreply, State}.

% process2.erl
% Here the code to stop process1
gen_server:cast(Pid, {stopme, "It's time to stop!"}),

More about it you can find here: http://www.erlang.org/doc/man/gen_server.html

answered 2011-11-02T18:33:50.790

Your Answer