我在Eclipse Erlide上运行了以下Erlang代码:
%% @author gakuo
%% @doc @todo Add description to links.
-module(links).
%% ====================================================================
%% API functions
%% ====================================================================
-export([start/1, test/1,middle/2]).
%% ====================================================================
%% Internal functions
%% ====================================================================
start(N)->
register(first,spawn_link(links,make,[N-1])).
make(0)->
last();
make(N)->
middle(spawn_link(links,make,[N-1]),N).
middle(Next,N)->
receive
Msg->
Next ! Msg,
io:format("Process ~w received ~w~n",[N,Msg]),
middle(Next,N)
end.
last()->
receive
stop->
io:format("last process now exiting ~n", []),
exit(finished);
Msg->
io:format("last process received ~w ~n", [Msg]),
last()
end.
test(Msg)->
first ! Msg.
我按如下方式运行:
links:start(3).
此时,我收到以下错误:
Eshell V9.0.4
(processlinking@GAKUO)1> links:start(3).
** exception exit: undef
in function links:make/1
called as links:make(2)
这是在我运行下一个命令之前发生的:
links:test(stop).
在两个命令之后,我期待以下内容:
Process 2 received stop
Process 1 received stop
Last process now exiting
stop
经过一番研究,我发现Undef被引发是因为在评估函数调用时找不到该函数。针对类似错误的StackOverflow的进一步研究没有帮助。解决方案涉及升级已安装的Erlang版本,但我的问题似乎是合乎逻辑的。作为Erlang的新手,我无法指出它是什么。像往常一样,我们将非常感谢您的帮助。
答案 0 :(得分:2)
spawn_link
(以及接受模块名+函数名+参数列表的其他函数)只能调用该模块导出的函数。未导出的函数只能从模块中调用,需要在没有模块名称前缀的情况下调用。因此,您需要导出make/1
才能使此代码正常工作:
-export([start/1, test/1, middle/2, make/1]).
^^^^^^