beginning erlang/OTP - spawning gen_servers and supervisors

AJ Heller aj@REDACTED
Sun May 9 01:38:33 CEST 2010


I am reading through the OTP documentation, stopping to work with and
understand every piece as it is introduced. I've written a very simple
gen_server and a simpler supervisor, and they both work as I expect
them to, but I've had to stop there. I'd like to understand them each
before I move on to building an application, but I'm confused about
the behavior of the system when I spawn each of these pieces
independently.

(For reference, my gen_server (echo_server) and supervisor (echo_sup)
modules are at the end of this post)

I am able to spawn my simple gen_server from my erl shell using
`spawn(echo_server, start_link, []).` I can then interact with it
using its public api (`echo_server:echo(...)`).

However, I cannot spawn a supervisor the same way. By calling
`spawn(echo_sup, start_link, []).`, my supervisor and gen_server both
appear to exit immediately after they have finished initializing.
Everything looks fine until I try to interact with my gen_server and
get

"** exception exit: {noproc,{gen_server,call,[echo_server,{echo,hi}]}}
     in function  gen_server:call/2"

Why is it that I can spawn a gen_server but not a supervisor? Thank you much.


---------------------------------------------------------------------------------------------------------
echo_server:

% -- begin echo_server.erl -- %

-module(echo_server).
-behaviour(gen_server).
-export([start_link/0]).
-export([echo/1, crash/0]).
-export([init/1, handle_call/3, handle_cast/2]).

start_link() ->
    gen_server:start_link({local, echo_server}, echo_server, [], []).

%% public api
echo(Text) ->
    gen_server:call(echo_server, {echo, Text}).

%% crash this gen_server to test its supervisor
crash() ->
    gen_server:call(echo_server, crash).

%% behaviours
init(_Args) ->
    {ok, none}.
handle_call({echo, Text}, _From, State) ->
    {reply, Text, State};
handle_call(crash, _From, State) ->
    X=1,
    {reply, X=2, State}.
handle_cast(_, State) ->
    {noreply, State}.

% -- end echo_server.erl -- %




echo_sup:

% -- begin echo_sup.erl -- %

-module(echo_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).

start_link() ->
    supervisor:start_link({local, echo_sup}, echo_sup, []).
init(_Args) ->
    {ok,  {{one_for_one, 5, 60},
           [{echo_server, {echo_server, start_link, []},
                 permanent, brutal_kill, worker, [echo_server]}]}}.


% -- end echo_sup.erl -- %


More information about the erlang-questions mailing list