I have two gen_server modules.
First serv.erl
-module(serv).
-behaviour(gen_server).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
code_change/3,
terminate/2,
start_link/0
]).
start_link() ->
gen_server:start_link(?MODULE, [], []).
init([]) ->
process_flag(trap_exit, true),
spawn_link(user, start_link,[]),
{ok, []}.
handle_call(_E, _From, State) ->
{noreply, State}.
handle_cast(_Message, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
handle_info(Message, State) ->
{noreply, State}.
code_change(_OldVersion, State, _Extra) ->
{ok, State}.
And user.erl (which is completely the same except init/1):
init([]) ->
{ok, []}.
I thought that the servers would last forever. And if the first server dies another one gets {'EXIT', Pid, Reason} message.
But if you start the modules by serv:start_link() , the user module will exit immediately after the start with a message {'EXIT',Pid,normal} . Why does user die?
When you use the spawn link function, you are starting a new process which calls user:start_link
. That process starts and links to a user gen_server process, and then exits, since the call to user:start_link
returned. The user process is linked to that process, so it gets an exit signal. Since the user process isn't trapping exits, it also exits.
You should just run user:start_link
in your serv:init
function, as suggested in the comments.