如何在Erlang中创建一个保持活动的过程 [英] how to create a keep-alive process in Erlang

查看:115
本文介绍了如何在Erlang中创建一个保持活动的过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读编程Erlang !在第13章结尾,我们要创建一个保持活动的过程,例如

I'm currently reading Programming Erlang! , at the end of Chapter 13, we want to create a keep-alive process, the example likes:

on_exit(Pid, Fun) ->
    spawn(fun() ->
            Ref = monitor(process, Pid),
            receive
                {'DOWN', Ref, process, Pid, Info} ->
                    Fun(Info)
            end
    end).
keep_alive(Name, Fun) ->
    register(Name, Pid = spawn(Fun)),
    on_exit(Pid, fun(_Why) -> keep_alive(Name, Fun) end).

但是在 register / 2 on_exit / 2 该进程可能退出,因此显示器将失败,我更改了 keep_alive / 2 ,如下所示: p>

but when between register/2 and on_exit/2 the process maybe exit, so the monitor will failed, I changed the keep_alive/2 like this:

keep_alive(Name, Fun) ->
    {Pid, Ref} = spawn_monitor(Fun),
    register(Name, Pid),
    receive
        {'DOWN', Ref, process, Pid, _Info} ->
            keep_alive(Name, Fun)
end.

spawn_monitor / 2 和 register / 2 ,该过程可能退出。这怎么可能成功运行?谢谢。

There also an bug, between spawn_monitor/2 and register/2, the process maybe exit. How could this come to run successfully? Thanks.

推荐答案

我不确定你有一个需要解决的问题。即使您的进程在注册/ 2之后退出,Monitor / 2也会成功。 Monitor / 2将发送一个向下消息,其Info组件将为noproc。根据文件:

I'm not sure that you have a problem that needs solving. Monitor/2 will succeed even if your process exits after register/2. Monitor/2 will send a 'DOWN' message whose Info component will be noproc. Per the documentation:


如果项目不存在,则DOWN消息将发送到监控过程,如果项目不存在,或者连接丢失到项目所在的节点。 (见 http://www.erlang.org/doc/man/erlang .html#monitor-2 )。

A 'DOWN' message will be sent to the monitoring process if Item dies, if Item does not exist, or if the connection is lost to the node which Item resides on. (see http://www.erlang.org/doc/man/erlang.html#monitor-2).

所以,在你的原始代码


  1. 注册协议名称到Pid

  2. Pid死亡

  3. on_exit被调用和监视器/ 2执行

  4. 监视器立即发送由on_exit

  5. 收到的语句的Fun(Info)函数接收到的DOWN消息执行调用keep_alive / 2

  1. register assocates Name to the Pid
  2. Pid dies
  3. on_exit is called and monitor/2 is executed
  4. monitor immediately sends a 'DOWN' message which is received by the function spawned by on_exit
  5. the Fun(Info) of the received statement is executed calling keep_alive/2

我认为一切都很好。

这篇关于如何在Erlang中创建一个保持活动的过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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