I have gen_server:
start(UserName) ->
case gen_server:start({global, UserName}, player, [], []) of
{ok, _} ->
io:format("Player: " ++ UserName ++ " started");
{error, Error} ->
Error
end
...
Now i want to write function to stop this gen server. I have:
stop(UserName) ->
gen_server:cast(UserName, stop).
handle_cast(stop, State) ->
{stop, normal, State};
handle_cast(_Msg, State) ->
{noreply, State}.
I run it:
start("shk").
Player: shk startedok
stop(shk).
ok
start("shk").
{already_started,<0.268.0>}
But:
stop(player).
ok
is work.
How can i run gen_server by name and stop by name?
Thank you.
First: You must always use the same name to address a process,
"foo"andfooare different, so start by having a strict naming convention.Second: When using globally registered processes, you also need to use
{global, Name}for addressing processes.In my opinion you should also convert the
stopfunction to usegen_server:call, which will block and let you return a value from the gen_server. An example:This would return
shutdown_okto the caller.With this said, the
globalmodule is rather limited and alternatives likegprocprovides much better distribution.