Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erlang:monitor and 'DOWN' message

Tags:

erlang

When studying carefully "gproc" project's gproc_tests.erl file. I have found the following code. The "goodbye" message is send before "erlang:monitor/2", I think it is possible that 'DOWN' message won't be received. Is it correct? If so, the two lines should be switched, right?

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).
like image 403
Chen Yu Avatar asked Mar 06 '12 14:03

Chen Yu


2 Answers

the erlang:monitor/2 call will still generate a {'DOWN', ...} message to the calling process even if the monitored process has already died.

for example:

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
like image 97
butter71 Avatar answered Oct 18 '22 20:10

butter71


According to documentation erlang: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.

like image 33
Hynek -Pichi- Vychodil Avatar answered Oct 18 '22 20:10

Hynek -Pichi- Vychodil