Erlang停止gen_server [英] Erlang stop gen_server

查看:527
本文介绍了Erlang停止gen_server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有gen_server:

  start(UserName) - > 
case gen_server:
{ok,_} - 的开始({global,UserName},player,[],[])
io:format(Player:++ UserName ++started);
{error,Error} - >
错误
结束
...

现在我想写功能来停止这个gen服务器。我有:

  stop(UserName) - > 
gen_server:cast(UserName,stop)。

handle_cast(stop,State) - >
{stop,normal,State};
handle_cast(_Msg,State) - >
{noreply,State}。

我运行它:

 开始( SHK)。 
玩家:shk startok
stop(shk)。
ok
start(shk)。
{already_started,< 0.268.0>}

但是:

  stop(player)。 
ok

是工作。



如何通过名称运行gen_server并按名称停止?



谢谢。

解决方案首先:您必须始终使用相同的名称来解决进程,foo foo 是不同的,所以从一个严格的命名约定开始。



第二:当使用全局注册的进程时,还需要使用 {global ,名称} 用于寻址流程。



在我看来,您还应该转换 stop 函数使用 gen_server:call ,这将阻止并让您从gen_server返回一个值。一个例子:

  stop(Name) - > 
gen_server:call({global,Name},stop)。

handle_call(stop,_From,State) - >
{stop,normal,shutdown_ok,state}

这将返回 / code code code code code code code code code code code code code $ c $有限的选择,例如 gproc 提供更好的分发。


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" and foo 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 use gen_server:call, which will block and let you return a value from the gen_server. An example:

stop(Name) ->
    gen_server:call({global, Name}, stop).

handle_call(stop, _From, State) ->
    {stop, normal, shutdown_ok, State}

This would return shutdown_ok to the caller.

With this said, the global module is rather limited and alternatives like gproc provides much better distribution.

这篇关于Erlang停止gen_server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆