I'm not quite sure why I can't get this but I'm sure the answer is extraordinarily simple. I'm just testing out a few things and in my tests discovered that I would like to spawn a process within handle_info of my gen_server.
However despite me trying different combinations the best result I'm getting from my child is dying with an error and returning {undef, [{bob, hello, [], []}]}.
Code:
-module(test).
-behaviour(gen_server).
-export([start_link/1, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
start_link(Args) ->
gen_server:start_link({local, Args}, ?MODULE, Args, []).
init(Args) ->
io:format("Init ~p ~p~n",[self(), Args]),
{ok, Args}.
handle_call(_, _, State) ->
io:format("Call ~p~n",[self()]),
{reply, ok, State}.
handle_cast(_, State) ->
io:format("Cast ~p~n",[self()]),
{noreply, State}.
handle_info(_, State) ->
io:format("Info ~p~n",[self()]),
spawn(?MODULE,fun hello/1,[]),
{noreply, State}.
terminate(_, _) ->
ok.
code_change(_, State, _) ->
{ok, State}.
hello([]) ->
io:format("WOOT ~p~n",[self()]).
My first goal was to determine if multiple servers could be started with one module. The second was if handle_info was executed in a separate process... for some reason when I read it was asynchronous I thought it was in another process. Now the third is to spawn a process within that call.
My typical shell goes something like (with comments):
> c(test), {ok, P} = gen_server:start_link(bob)
> %% Warns me the function hello in any incarnation is not used
> P ! woot.
> %% An error of some kind depending on what I've done
> f(P), gen_server:stop(bob).
I've used hello/1 with [] and _, hello/0. As well as spawn/1, spawn/3, spawn_link/1 and spawn_link/3... I've used ?MODULE, test, State and for chuckles {local, State} as the module parameter. I've parted with what I've seen on multiple websites and put in fun hello/0 and fun hello/1 when passing the function. This produces crashes but got rid of the compiler warning.
Where did I go wrong?