[erlang-questions] remote spawns and sending messages to the remote PID

Jeff Macdonald macfisherman@REDACTED
Mon Apr 13 05:13:18 CEST 2009


Hi,

I'm just getting my feet wet in erlang. I have Joe's book, but I
wanted to try some low level stuff myself.

I created a small counter module. It simply increments a value every
time it see's an inc message and sends a reply back to the caller
supplied PID. This works fine within a single node. However, I can't
see to get it to work correctly when I start two nodes on the same
computer using sname (foo and bar). First I spawn a local receive
loop:

(foo@REDACTED)2> R=spawn(fun counter:loop/0).
<0.43.0>

Testing it on that node works:

(foo@REDACTED)3> R ! {ok,5}.
Value is 5
{ok,5}


Now I spawn the counter on the bar node:
(foo@REDACTED)3> S=spawn('bar@REDACTED',counter,run,[5]).
<5734.41.0>

and send it a message:
(foo@REDACTED)4> S ! {inc, R}.
{inc,<0.38.0>}

Normally when this is done on the local node, I get this:
(foo@REDACTED)5> T=counter:run(5).
<0.48.0>
(foo@REDACTED)6> T ! {inc, R}.
Value is 1
{inc,<0.38.0>}

Note the Value line in the output.

I'm aware of the rpc library, but I thought I could do simple things
like above without it. Below is the code. I'm not currently using the
registered process name. It was my understanding that all that one
needed was a PID. If one used a registered process name instead, than
one needed the node too. Is that incorrect?

TIA

-module(counter).
-export([run/1, counter/2, loop/0]).

run(Limit) ->
	S = spawn(counter, counter, [Limit, 0]),
	register(counter, S),
	S.
	
counter(Limit, Sum) ->
	receive
        	{value, Requester}	->
        		Requester ! {ok, Sum},
        		counter(Limit, Sum);

        	{inc, Requester} when Sum < Limit	->
		    	Requester ! {ok, Sum + 1},
		    	counter(Limit, Sum + 1);

	        {inc, Requester}	->
	        	Requester ! {error, limit},
	        	counter(Limit, Sum)
	    end.

loop()	->
	receive
		{ok, V}	->
			io:format("Value is ~p~n",[V]),
			loop();
		{error, Reason}	->
			io:format("Error ~p~n",[Reason]),
			loop()
	end.




-- 
Jeff Macdonald
Ayer, MA



More information about the erlang-questions mailing list