2012-03-06 41 views
4

仔細研究「gproc」項目的gproc_tests.erl文件時。我找到了下面的代碼。 在「erlang:monitor/2」之前發送「再見」消息,我認爲可能不會收到'DOWN'消息。這是對的嗎?如果是這樣,兩條線應該切換,對嗎?erlang:監視器和'DOWN'消息

t_simple_aggr_counter() -> 
    ?assert(gproc:reg({c,l,c1}, 3) =:= true), 
    ?assert(gproc:reg({a,l,c1}) =:= true), 
    ?assert(gproc:get_value({a,l,c1}) =:= 3), 
    P = self(), 
    P1 = spawn_link(fun() -> 
       gproc:reg({c,l,c1}, 5), 
       P ! {self(), ok}, 
       receive 
       {P, goodbye} -> ok 
       end 
      end), 
    receive {P1, ok} -> ok end, 
    ?assert(gproc:get_value({a,l,c1}) =:= 8), 
    ?assert(gproc:update_counter({c,l,c1}, 4) =:= 7), 
    ?assert(gproc:get_value({a,l,c1}) =:= 12), 
    P1 ! {self(), goodbye}, %<<===========This line 
    R = erlang:monitor(process, P1), %<<======This line 
    receive {'DOWN', R, _, _, _} -> 
     gproc:audit_process(P1) 
    end, 
    ?assert(gproc:get_value({a,l,c1}) =:= 7). 

回答

10

二郎神:監控/ 2呼叫仍將產生{「DOWN」,...}消息調用進程,即使被監控的進程已經死亡。

例如:

1> F = fun() -> io:format("finished.~n") end. 
#Fun<erl_eval.20.111823515> 
2> Pid = spawn(F). 
finished. 
<0.45.0> 
3> erlang:monitor(process, Pid). % process Pid has already exited. 
#Ref<0.0.0.76> 
4> flush(). 
Shell got {'DOWN',#Ref<0.0.0.76>,process,<0.45.0>,noproc} 
ok 
+0

flush()命令非常有用。 – 2012-03-06 22:42:26

+0

還有一個可能會派上用場的守護神召喚選項。 – 2012-03-07 10:13:10

5

根據文檔erlang:monitor/2:如果項模具A「DOWN」消息將被髮送到監控過程,如果項目不存在,或者如果連接丟失到項目所在的節點。