loop exit question

Ulf Wiger <>
Thu Apr 19 15:40:06 CEST 2001


On Thu, 19 Apr 2001, Willem Broekema wrote:

>Now, if the State is not changed in any of the 'reveiced'
>branches, is there a reason not to move the final 'loop()'
>command to the end, and use 'exit()' for breaking out of
>the loop, like in the following?
>
>loop2(State) ->
>   receive
>       stop ->
>           exit(self(), stopped_upon_request);
>       Other ->
>           ...
>   end,
>   loop(State).

How you want to terminate your process depends in part on how you're
implementing it (plain erlang, gen_server, 'sys' compliant plain
erlang, ...), and in part on the context in which it is executing.

I would write the loop like this:

loop2(State) ->
   receive
      stop ->
         terminate(normal, State);
      Other ->
         NewState = handle_message(Other, State),
         loop2(NewState)
   end.

terminate(Reason, State) ->
   exit(Reason).   %% note: exit/1

handle_message(Msg, State) ->
   ...



I will give a few examples of context issues to consider:

- if you're using SASL, and the process was started with e.g.
  proc_lib:spawn_link/3 (as it should), exit(stopped_upon_request)
  would be interpreted as an abnormal exit, and would lead to a 
  crash report. exit(normal) would not.

- If the process is supervised, and is started as a transient
  process, any exit reason other than normal would cause the 
  supervisor to restart the process.

- If the process is supervised and trapping EXITs, it would 
  have to trap the following message:

   receive
      {'EXIT', Parent, shutdown} ->   %% assume Parent is bound
         terminate(shutdown, State);
      ...
   end.


This in order to comply with the OTP shutdown protocol.

Of course, if you use an OTP behaviour, like gen_server, you get
much of this for free.


/Uffe
-- 
Ulf Wiger                                    tfn: +46  8 719 81 95
Senior System Architect                      mob: +46 70 519 81 95
Strategic Product & System Management    ATM Multiservice Networks
Data Backbone & Optical Services Division      Ericsson Telecom AB





More information about the erlang-questions mailing list