Erlang Undefined Function Global

时间:2017-12-06 06:27:23

标签: erlang message-passing

这是我第一次潜入Erlang,但我来自Prolog世界。

我似乎无法理解为什么在加载模块并告诉它执行一个函数之后,它似乎会运行到另一个单独的函数。

问题Erlang - undefined function似乎有关系,但看起来并不适用于我的情况。我可以编译并加载模块。

这是我的Eshell输出:

Erlang/OTP 20 [erts-9.1] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:10]

Eshell V9.1  (abort with ^G)
1> m(chat_client).
Module: chat_client
MD5: 32e278745489222df841e93620154031
Compiled: No compile time info available
Object file: h:/Program Files/erl9.1/bin/chat_client.beam
Compiler options:  []
Exports: 
         handle_messages/1
         module_info/0
         module_info/1
         register_nickname/1
         send_message/2
         start_router/0
         unregister_nickname/1
ok
2> chat_client:start_router().
yes
3> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
4> l(chat_client).
{module,chat_client}
5> chat_client:start_router().           
ok
6> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
7> l(message_router).                    
{module,message_router}
8> chat_client:start_router().           
ok
9> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
10> 

chat_client.erl 文件中,与send_message/2无匹配:

-module(chat_client).

-compile(export_all).

register_nickname(Nickname) ->
    Pid = spawn(chat_client, handle_messages, [Nickname]),
    message_router:register_nick(Nickname, Pid).

unregister_nickname(Nickname) ->
    message_router:unregister_nick(Nickname).

send_message(Addressee, MessageBody) ->
    message_router:send_chat_message(Addressee, MessageBody).

handle_messages(Nickname) ->
    receive
        { printmsg, MessageBody } ->
            io:format("~p received: ~p~n", [Nickname, MessageBody]),
            handle_messages(Nickname);
        stop ->
            ok
    end.

start_router() ->
message_router:start().

从相关文件 message_router.erl 我可以看到一个全局函数匹配(或者我认为):

send_chat_message(Addressee, MessageBody) ->
    global:send_message(?SERVER, { send_chat_msg, Addressee, MessageBody }).

register_nick(ClientName, ClientPid) ->
    global:send_message(?SERVER, { register_nick, ClientName, ClientPid }).

unregister_nick(ClientName) ->
    global:send_message(?SERVER, { unregister_nick, ClientName }).

在这种情况下,我做错了什么?

1 个答案:

答案 0 :(得分:1)

在模块global中,有一个函数send/2,但没有send_message/2。将您的message_router更改为:

send_chat_message(Addressee, MessageBody) ->
    global:send(?SERVER, { send_chat_msg, Addressee, MessageBody }).

register_nick(ClientName, ClientPid) ->
    global:send(?SERVER, { register_nick, ClientName, ClientPid }).

unregister_nick(ClientName) ->
    global:send(?SERVER, { unregister_nick, ClientName }).