erlang分布式入门(一)-ping pong
erlang分布式入门(一)-ping pong
测试环境和http://willvvv.iteye.com/blog/1523918 一样,192.168.0.182(centos-182)和192.168.0.183(centos-183),
1.按照上面链接(步骤1-4)设置通过ssh hostname 免输入密码直接登录。
2.设置erlang的magiccookie,由于都是以root账号操作,分别在两台机子上执行以下命令
cd /root
vi .erlang.cookie
输入
- centos_erlang
:wq 退出保存
chmod 400 .erlang.cookie,linux下需要用户对magiccookie有读权限
3.启动epmd进程,它负责映射符号名到机器地址在两个机器都执行:epmd -daemon
4.ping-pong测试代码,来源自网上erlang教程,tut17.erl
- -module(tut17).
- -export([start_ping/1, start_pong/0, ping/2, pong/0]).
- ping(0, Pong_Node) ->
- {pong, Pong_Node} ! finished,
- io:format("ping finished~n", []);
- ping(N, Pong_Node) ->
- {pong, Pong_Node} ! {ping, self()},
- receive
- pong ->
- io:format("Ping received pong~n", [])
- end,
- ping(N - 1, Pong_Node).
- pong() ->
- receive
- finished ->
- io:format("Pong finished~n", []);
- {ping, Ping_PID} ->
- io:format("Pong received ping~n", []),
- Ping_PID ! pong,
- pong()
- end.
- start_pong() ->
- register(pong, spawn(tut17, pong, [])).
- start_ping(Pong_Node) ->
- spawn(tut17, ping, [3, Pong_Node]).
5.在centos-183上执行erl -sname 'pong' ,启动pong节点,进入erl命令行之后输入 tut17:start_pong().
在centos-182上执行 erl -sname 'ping',启动ping节点,进入erl命令行之后输入 tut17:start_ping('pong@centos-183').
命令及输出见下图:
注意在ping节点上的erl命令行启动ping进程的时候如果输入tut17:start_ping(pong@centos-183). 会报错如下:
- ** exception error: bad argument in an arithmetic expression
- in operator -/2
- called as pong@centos - 183
在参考“庄周梦蝶”的http://www.blogjava.net/killme2008/archive/2007/06/15/124547.html 时就出现这个错误,后来在stackoverflow 上找到一个相关问题 http://stackoverflow.com/questions/413736/naming-nodes-in-erlang 才得以解决!