这是我的代码,当我运行:gen_server_test:alloc,它给了我错误,请帮帮我
-module(gen_server_test).
-behaviour(gen_server).
-export([start_link/0]).
-export([alloc/0, free/1]).
-export([init/1, handle_call/3, handle_cast/2]).
start_link() ->
gen_server:start_link({local, gen_server_test}, gen_server_test, [], []).
alloc() ->
io:format("allocing"),
gen_server:call(?MODULE, {alloc}).
free(Ch) ->
gen_server:cast(gen_server_test, {free, Ch}).
init(_Args) ->
{ok, channels()}.
handle_call({alloc}, _From, LoopData) ->
io:format("handle alloc").
handle_cast({free, Ch}, LoopData) ->
io:format(Ch).
free() ->
io:format("free").
channels() ->
io:format("channels").
错误:
23> gen_server_test:alloc().
allocinghandle alloc
=ERROR REPORT==== 6-May-2011::18:05:48 ===
** Generic server gen_server_test terminating
** Last message in was {alloc}
** When Server state == ok
** Reason for termination ==
** {'function not exported',
[{gen_server_test,terminate,[{bad_return_value,ok},ok]},
{gen_server,terminate,6},
{proc_lib,init_p_do_apply,3}]}
** exception exit: undef
in function gen_server_test:terminate/2
called as gen_server_test:terminate({bad_return_value,ok},ok)
in call from gen_server:terminate/6
in call from proc_lib:init_p_do_apply/3
答案 0 :(得分:10)
以下是错误报告的重要部分:{bad_return_value,ok}
handle_call/3的有效返回值为:
{reply,Reply,NewState}
| {reply,Reply,NewState,Timeout}
| {reply,Reply,NewState,hibernate}
| {noreply,NewState}
| {noreply,NewState,Timeout}
| {noreply,NewState,hibernate}
| {stop,Reason,Reply,NewState}
| {stop,Reason,NewState}
将handle_call重写为:
handle_call({alloc}, _From, LoopData) ->
Reply = io:format("handle alloc"),
{reply, Reply, LoopData}
现在会“解决”这个问题。但是我建议你查看gen_server的文档,因为你还有其他一些奇怪的东西。例如,您的州是ìo:format("channels")
的结果。这根本没有任何意义。
我想你正在学习gen_servers,这很棒,我保证documentation将帮助你解决你的知识之路上的许多小问题。
答案 1 :(得分:1)
您的handle_call
和handle_cast
方法需要返回{reply, Response, NewState}
或{noreply, NewState}
类型的元组。请查看gen_server文档,了解有关允许返回值的更多信息。
io:format(..)
函数仅返回ok
..这就是您看到此错误的原因..