2

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?

Max
  • 661
  • 1
  • 7
  • 12

1 Answers1

12

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.

archaelus
  • 7,109
  • 26
  • 37
  • I thought that was the case, but I had not found it explained in the Erlang books that I referenced. Many thanks for the clear explanation. – Max Dec 05 '10 at 08:29
  • See related question for explaining erlang PID format: http://stackoverflow.com/questions/243363/can-someone-explain-the-structure-of-a-pid-in-erlang – andreypopp Dec 05 '10 at 09:50
  • Just to generalise a little. What @archaelus writes is perfectly correct but you should not really try to interpret the internal format of the opaque data types like pids and refs. These are equal if you compare them in a test, on any node. If when you send messages to the pids they arrive at the same process then they are equal. – rvirding Dec 06 '10 at 10:26