global:whereis_name() returns different Pid from d

2019-07-15 03:03发布

问题:

Could somebody please explain to me why the Pid returned from global:whereis_name() is different when done in different terminals (under OSX, at least).

A simple demonstration is below.

demo.erl
-module(demo).

-export([start/0, loop/0, echo/1]).


start() ->
    Pid = spawn(?MODULE, loop, []),
    yes = global:register_name('demo', Pid).

echo(Msg) ->
    global:send('demo', Msg).

loop() ->
    receive
        Msg -> 
            io:format("demo: ~w~n", [Msg]),
            loop()
    end.

Terminal A:

erl -sname A -setcookie demo
(A@local)1> demo:start().
yes
(A@local)2> global:whereis_name(demo).
<0.39.0>
(A@local)3> demo:echo(aaa).
<0.39.0>
demo: aaa  
demo: bbb  
demo: ccc  
(A@local)4>

Terminal B:

erl -sname B -setcookie demo
(B@local)1> net_kernel:connect_node('A@local').
true
(B@local)2> demo:echo(bbb).                     
<6572.39.0>
(B@local)3> global:whereis_name(demo).
<6572.39.0>

Terminal C:

erl -sname C -setcookie demo
(C@local)1> net_kernel:connect_node('A@local').
true
(C@local)2> demo:echo(ccc).                     
<5829.39.0>
(C@local)3> global:whereis_name(demo).
<5829.39.0>

Why does global:whereis_name(demo) return a different value in Terminal B and Terminal C?

回答1:

The pids you see on nodes B and C are remote pids. The first part (xxx) of the pid <xxx.yyy.zzz> is the remote node number, the second two parts are the process id on that node. The remote node number that B assigns for A will not necessarily be the same as the number C assigns for A. So the first part of the pid may vary from node to node, but the second two will be the same; <xxx.0.39> in your example. All these pids refer to the same process.



标签: erlang