Erlang停止gen_server
我有 gen_server:
start(UserName) ->
case gen_server:start({global, UserName}, player, [], []) of
{ok, _} ->
io:format("Player: " ++ UserName ++ " started");
{error, Error} ->
Error
end
...
现在我想编写函数来停止这个 gen 服务器。我有:
stop(UserName) ->
gen_server:cast(UserName, stop).
handle_cast(stop, State) ->
{stop, normal, State};
handle_cast(_Msg, State) ->
{noreply, State}.
我运行它:
start("shk").
Player: shk startedok
stop(shk).
ok
start("shk").
{already_started,<0.268.0>}
但是:
stop(player).
ok
是工作。
如何按名称运行 gen_server 并按名称停止?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一:您必须始终使用相同的名称来寻址进程,
"foo"
和foo
是不同的,因此首先要有严格的命名约定。第二:使用全局注册的进程时,还需要使用
{global, Name}
来对进程进行寻址。在我看来,您还应该将
stop
函数转换为使用gen_server:call
,这将阻止并让您从 gen_server 返回一个值。示例:这会将
shutdown_ok
返回给调用者。话虽如此,
global
模块相当有限,而像gproc
这样的替代品则提供了更好的分发。First: You must always use the same name to address a process,
"foo"
andfoo
are 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
stop
function to usegen_server:call
, which will block and let you return a value from the gen_server. An example:This would return
shutdown_ok
to the caller.With this said, the
global
module is rather limited and alternatives likegproc
provides much better distribution.我面前没有文档,但我的猜测是您需要将用户名包装在 gen_server 转换中的全局元组中。
I don't have the docs infront of me, but my guess would be that you need to wrap the username in a global tuple within the gen_server cast.