当我学习Erlang的时候,我正在尝试解决ex。4.1 "Erlang Programming“一书(O‘’Reilly)中的”一个Echo服务器“,我有一个问题。我的代码看起来像这样:
-module(echo).
-export([start/0, print/1, stop/0, loop/0]).
start() ->
register(echo, spawn(?MODULE, loop, [])),
io:format("Server is ready.~n").
loop() ->
receive
{print, Msg} ->
io:format("You sent a message: ~w.~n", [Msg]),
start();
stop ->
io:format("Server is off.~n");
_ ->
io:format("Unidentified command.~n"),
loop()
end.
print(Msg) -> ?MODULE ! {print, Msg}.
stop() -> ?MODULE ! stop.不幸的是,我有一些问题。打开后,它会产生一个新的进程,并显示"Server is ready“消息。但是当我尝试使用打印函数(例如echo:print("Some message."). )时,我得到了结果,但它并不像我想要的那样工作。它将我的消息打印为列表(而不是字符串),并生成
=ERROR REPORT==== 18-Jul-2010::01:06:27 ===
Error in process <0.89.0> with exit value: {badarg,[{erlang,register,[echo,<0.93.0>]},{echo,start,0}]}错误消息。此外,当我尝试通过echo:stop()停止服务器时,我得到了另一个错误
** exception error: bad argument
in function echo:stop/0有没有人能解释一下,这是怎么回事?我刚接触Erlang,现在似乎很难掌握它。
发布于 2010-07-18 08:45:04
当您的loop/0函数收到print消息时,您将再次调用start/0,这将产生新的进程,并再次尝试将其注册为echo。它会导致你的服务器死机,新的服务器没有注册为echo,所以你不能再通过print/1函数向它发送消息了。
loop() ->
receive
{print, Msg} ->
io:format("You sent a message: ~w.~n", [Msg]),
loop(); % <-- just here!
stop ->
io:format("Server is off.~n");
_ ->
io:format("Unidentified command.~n"),
loop()
end.https://stackoverflow.com/questions/3273623
复制相似问题