我正在尝试学习Erlang但是在向另一个节点发送消息时遇到了问题。该程序只是一个非常简单的乒乓球,应该像这样工作。我在节点m1 @ ASUS-N55SF上启动了一个程序。它创建了一个过程,它成功地在节点m2上产生了一个过程。所以我得到的Pids包含{PidPing,PidPong}元组。 PidPing和PidPong是进程ID,如< 0.X.0>和< Y.Z.0取代。
之后我调用ps5:start_pinging(Pids)函数,我收到一个错误:
Pinging started
Ping received 0 on <0.53.0>
{ping,{<0.53.0>,<6807.43.0>},0}
Nodes: 'm1@ASUS-N55SF' 'm2@ASUS-N55SF'
(m1@ASUS-N55SF)8>
=ERROR REPORT==== 1-Dec-2012::15:27:18 ===
Error in process <0.53.0> on node 'm1@ASUS-N55SF' with exit
value: {badarg,[{ps5,loop_ping,0,[{file,"ps5.erl"},{line,33}]}]}
所以初始消息到达PidPing和loop_ping接收并且成功匹配但是我不能向另一个节点发送消息,即使它们彼此可见。 这会成功,因为此初始消息是在同一节点上发送的:
PidPing ! {pong, {PidPing, PidPong}, 0}.
据我所知,要向另一个节点发送消息,我应该发送一条消息,如:
{PidPong, ?NODE_TP} ! {pong, {PidPing, PidPong}, Number + 1},
但它会返回badarg。节点连接,以相同的cookie启动,在同一台机器上运行,并且可以互相ping并可见。它们在同一个文件夹中启动,因此它们在同一个ps5.erl文件中查找。我尝试过不同的文件夹,但也无法正常工作。如果代码在seme节点上运行,只需在另一个节点上删除spawn并在同一节点上创建进程,它就可以工作。
以下是代码:
-module(ps5).
-define(NODE_AS, 'm1@ASUS-N55SF').
-define(NODE_TP, 'm2@ASUS-N55SF').
%-define(NODE_TP, 'm2@ThinkPad-Z60m').
-compile(export_all).
start() ->
PidPing = ps5:start_ping(),
PidPong = ps5:start_pong(),
Pids = {PidPing, PidPong}.
start_ping() ->
Pid = spawn(?NODE_AS, ps5, loop_ping, []).
start_pong() ->
Pid = spawn(?NODE_TP, ps5, loop_pong, []).
start_pinging({PidPing, PidPong}) ->
io:format("Pinging started ~n", []),
PidPing ! {ping, {PidPing, PidPong}, 0}.
stop({PidPing, PidPong}) ->
exit(PidPing, normal),
exit(PidPong, normal).
loop_ping() ->
receive
{ping, {PidPing, PidPong}, Number} when Number < 10 ->
io:format("Ping received ~p on ~p~n", [Number, PidPing]),
io:format("Nodes: ~p ~p ~n", [?NODE_AS, ?NODE_TP]),
{PidPong, ?NODE_TP} ! {pong, {PidPing, PidPong}, Number + 1},
io:format("Ping sent ping ~p to ~p~n", [Number, PidPong]),
ps5:loop_ping();
{ping, {PidPing, PidPong}, Number} when Number >= 10->
io:format("Ping received ~p on ~p~n and closing.~n", [Number, PidPing]);
Oops ->
io:format("Oops received: ~p~n", [Oops]),
ps5:loop_ping()
end.
loop_pong() ->
receive
{pong, {PidPing, PidPong}, Number} when Number < 10 ->
io:format("Pong received ~p on ~p~n", [Number, PidPong]),
io:format("Nodes: ~p ~p ~n", [?NODE_AS, ?NODE_TP]),
{PidPing, ?NODE_AS} ! {ping, {PidPing, PidPong}, Number + 1},
io:format("Pong sent ping ~p to ~p~n", [Number, PidPing]),
ps5:loop_pong();
{pong, {PidPing, PidPong}, Number} when Number >= 10->
io:format("Pong received ~p on ~p~n and closing.~n", [Number, PidPing]);
Oops ->
io:format("Oops received: ~p~n", [Oops]),
ps5:loop_pong()
end.
在编译期间有一些警告,但它们与此问题无关(至少我相信如此)。
答案 0 :(得分:6)
构造{Registered_process_name, Erlang_node} ! Some_message
用于向远程已注册进程发送消息,这些进程的PID不知道。
在您的情况下,您知道pids(并且流程未注册),这意味着您不得使用{name, node} ! message
,而是PID ! message
,即更改:
{PidPong, ?NODE_TP} ! {pong, {PidPing, PidPong}, Number + 1},
到
PidPong ! {pong, {PidPing, PidPong}, Number + 1},
和
{PidPing, ?NODE_AS} ! {ping, {PidPing, PidPong}, Number + 1},
到
PidPing ! {ping, {PidPing, PidPong}, Number + 1},