ErlangOTP中的监控器

问题描述 投票:5回答:3

我有一个关于监视器的问题。

1> Pid=spawn(fun() -> timer:sleep(500000) end).
2> exit(Pid, kill).
3> Ref=erlang:monitor(process, Pid).

4> flush().

在我的shell中,flush()的输出是 {'DOWN',#Ref<0.0.0.159>,process,<0.69.0>,noproc}

我的问题是:如果在创建监视器之前,进程已经被杀死,为什么shell会得到 'DOWN' 信息?

erlang monitor
3个回答
7
投票

这是一个避免竞赛条件的特性。 请记住,就当前进程所知,另一个进程可能在任何时候死亡。 因此,它可能会在调用到 erlang:monitor如果每一个监视器都要考虑这两种情况,那将是非常麻烦的。

这就是为什么监控一个死掉的进程时,会给出与被监控的进程死亡时相同的消息。 唯一不同的是,退出的原因总是给出为 noproc.


2
投票

你会收到一条消息,说有noproc。这是有道理的,因为当你开始监视一个进程时,它可能已经死了。

1> Pid=spawn(fun() -> timer:sleep(500000) end).
<0.35.0>
2> exit(Pid, kill).
true
3> Ref=erlang:monitor(process, Pid).
#Ref<0.0.0.38>
4> flush().
Shell got {'DOWN',#Ref<0.0.0.38>,process,<0.35.0>,noproc}
ok
5> 
5> Pid1=spawn(fun() -> timer:sleep(500000) end).
<0.40.0>
6> Ref1=erlang:monitor(process, Pid1).          
#Ref<0.0.0.53>
7> exit(Pid1, kill).                            
true
8> flush().                                     
Shell got {'DOWN',#Ref<0.0.0.53>,process,<0.40.0>,killed}
ok
9> 

1
投票

如果Pid2以退出原因Reason终止,一个 "DOWN "消息会被发送到Pid1。

{'DOWN', Ref, process, Pid2, Reason}

如果Pid2不存在,则立即发送 "DOWN "消息,并将Reason设置为noproc。

© www.soinside.com 2019 - 2024. All rights reserved.