Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang. Correct way to stop process

Tags:

erlang

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 ?

like image 504
Dfr Avatar asked Nov 01 '11 17:11

Dfr


People also ask

How do I stop erlang shell?

If you then press a (for abort) you will exit the shell directly. Other ways of exiting the erlang shell are: init:stop() which does the same thing as q() or erlang:halt() .

How do you kill erlang node?

To terminate first node you could type erlang:halt().

Is process alive erlang?

This is called as is_process_alive(Pid). A Pid must refer to a process at the local node. It returns true if the process exists and is alive i.e., whether it is not exiting and has not exited.

What is an erlang process?

Erlang processes are light-weight (grow and shrink dynamically) with small memory footprint, fast to create and terminate and the scheduling overhead is low.


2 Answers

Not being an Erlang programmer and just from the documentation of exit (here), I'd say, that exit requires a process id as first argument whereas you are passing an atom (?SERVER) to it.

Try

exit(whereis(?SERVER), ok).

instead (whereis returns the process id associated with a name, see here)

like image 180
MartinStettner Avatar answered Oct 05 '22 02:10

MartinStettner


You need to change the call to exit/2 as @MartinStettner has pointed out. The reason the process stops anyway is that you have started it with spawn_link. Your process is then linked to the shell process. When you called mrtask_net:stop() the error caused the shell process to crash which then caused your process to crash as they were linked. A new shell process is then automatically started so you can keep working with the shell. You generally do want to start your servers with spawn_link but it can cause confusion when your are testing them from the shell and they just "happen" to die.

like image 26
rvirding Avatar answered Oct 05 '22 03:10

rvirding