1

I'm playing with Erlang OTP supervisors, and want to build a simple app with a supervisor and a worker.

I've create a simple gen_server based worker that takes 2 numbers and divides first by the second. And if the second number is 0, then it fails with an error.

And I have a supervisor, that should theoretically restart the work if it fails. But when I launch the app, the worker is not restarted after it fails. Instead, the shell crushes. I assume this happens because of how gen_server:call behaves in case of an error, but I'm not sure.


Worker:

-module(my_worker).
-behaviour(gen_server).
-export([init/1,handle_call/3,create/0,terminate/2]).

create() -> gen_server:start({local,my_calc},?MODULE,0,[]).

init(_) -> {ok, {}}.

handle_call({divide, _, 0}, _From, State) ->
  {stop, div_by_zero, State};
handle_call({divide, X, Y}, _From, State) ->
  {reply, X / Y, State}.

terminate(Reason,State) ->
  io:format("Terminated because of ~p", [Reason]).

Supervisor:

-module(my_supervisor).
-behaviour(supervisor).
-export([init/1,create/0]).

create() -> supervisor:start_link(?MODULE,{}).

init(_) ->
  {
    ok,
    {
       #{strategy => one_for_one, intensity => 10, period => 1000},
      [
        #{id => child_id1,
          start => {my_worker, create, []},
          restart => permanent,
          shutdown => 1000,
          type => worker,
          modules => [my_worker]
        }
      ]
    }
  }.

Shell:

c(my_worker).
c(my_supervisor).

my_supervisor:create().
gen_server:call(my_calc,{divide, 10, 2}). % 5.0
gen_server:call(my_calc,{divide, 10, 0}). % Everything dies
gen_server:call(my_calc,{divide, 10, 2}). % Worker is dead

Running in shell

0 Answers0