Erlang 进程卡住了



我是第一次在erlang上工作。 每次我尝试运行 erlang 进程时,它都会卡住并且不接受输入。我在 eclipse 中使用 erlide 插件来测试 erlang 代码。

代码是:

-module(message_router).
%% ====================================================================
%% API functions
%% ====================================================================
%%-compile(export_all).
-export([start/0]).
-export([stop/1]).
-export([send_chat_message/3]).
-export([route_messages/0]).

%% ====================================================================
%% Internal functions
%% ====================================================================
start() ->
    spawn(message_router, route_messages, []).
stop(RouterPid) ->
    RouterPid ! shutdown.
send_chat_message(RouterPid, Addressee, MessageBody) ->
    io:format("send_chat_msg FROM:: ~p TO:: ~p ~n", [RouterPid, Addressee]),
    RouterPid ! {send_chat_msg, Addressee, MessageBody}.
route_messages() ->
receive
    {send_chat_msg, Addressee, MessageBody} ->
        io:format("recv_chat_msg PID:: ~p ~n", [Addressee]),
        Addressee ! {recv_chat_msg, MessageBody},
        route_messages();
    {recv_chat_msg, MessageBody} ->
        io:format("Received: ~p~n", [MessageBody]);
    shutdown ->
        io:format("Shutting down ~n");
    Oops ->
        io:format("Warning! Received: ~p~n", [Oops]),
        route_messages()
end.

当我点击尝试像在 shell 中一样运行代码时

Eshell V5.10.4
(nodename@pa)1> P1 = message_router:start().
<0.1308.0>
(nodename@pa)2> P2 = message_router:start().
<0.1373.0>
(nodename@pa)3> chat_client:send_message(P1, P2, "FIRST Msg").
Sending chat message from chat_client
send_chat_msg FROM:: <0.1308.0> TO:: <0.1373.0> 

在此之后,我在外壳中输入的每件事都会生效。谁能解释一下如何在 erlang 和最佳实践中处理循环。

[编辑]

聊天客户端代码:

-module(chat_client).
-export([send_message/3]).
send_message(RouterPid, Addressee, MessageBody) ->
    io:format("Sending chat message from chat_client~n"),
    message_router:send_chat_message(RouterPid, Addressee, MessageBody).

模块中的问题。称之为message_router:send_chat_message(P1, P2, "FIRST Msg")
看看这个例子,并与他的比较:

在注册两个进程loop/0trans/0 observer调用模块

-module(observer).
-export([observer/0, loop/0, trans/0]).
observer() ->
  register(loop, spawn(fun observer:loop/0)),
  register(trans, spawn(fun observer:trans/0)).
loop() ->
  receive
    {'PRINT', Msg} -> 
      io:format("print from ~p~n~p~n", [self(), Msg]), loop();
    {'EXIT', _FromPid} -> 
      io:format("Exit ~nFrom ~p", [_FromPid]), exit(self(), kill)
  end.
trans() ->
  receive
    {Command, Msg} -> io:format("transports from: ~p~n~p~n", [self(), Msg]),
                      loop ! {Command, Msg}
  end.

并具有模块send_messenger一个通过trans发送消息的函数send_message

-module(send_messenger).
-export([send_message/1]).
send_message({Command, Msg}) ->
  trans ! {Command, Msg},
  ok.

我希望这对你有所帮助!

相关内容

  • 没有找到相关文章

最新更新