【发布时间】:2020-02-27 04:59:40
【问题描述】:
我不太确定为什么我不能得到这个,但我确信答案非常简单。我只是在测试一些东西,在我的测试中发现我想在我的gen_server 的handle_info 中生成一个进程。
然而,尽管我尝试了不同的组合,但我从孩子身上得到的最好结果是因错误而死并返回 {undef, [{bob, hello, [], []}]}。
代码:
-module(test).
-behaviour(gen_server).
-export([start_link/1, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
start_link(Args) ->
gen_server:start_link({local, Args}, ?MODULE, Args, []).
init(Args) ->
io:format("Init ~p ~p~n",[self(), Args]),
{ok, Args}.
handle_call(_, _, State) ->
io:format("Call ~p~n",[self()]),
{reply, ok, State}.
handle_cast(_, State) ->
io:format("Cast ~p~n",[self()]),
{noreply, State}.
handle_info(_, State) ->
io:format("Info ~p~n",[self()]),
spawn(?MODULE,fun hello/1,[]),
{noreply, State}.
terminate(_, _) ->
ok.
code_change(_, State, _) ->
{ok, State}.
hello([]) ->
io:format("WOOT ~p~n",[self()]).
我的第一个目标是确定是否可以使用一个模块启动多个服务器。第二个是如果handle_info 在单独的进程中执行......由于某种原因,当我阅读它是异步的时,我认为它在另一个进程中。现在第三个是在该调用中生成一个进程。
我的典型外壳类似于(使用 cmets):
> c(test), {ok, P} = gen_server:start_link(bob)
> %% Warns me the function hello in any incarnation is not used
> P ! woot.
> %% An error of some kind depending on what I've done
> f(P), gen_server:stop(bob).
我已将hello/1 与[] 和_、hello/0 一起使用。以及spawn/1、spawn/3、spawn_link/1 和spawn_link/3...我使用?MODULE、test、State 和笑声{local, State} 作为模块参数。我已经放弃了我在多个网站上看到的内容,并在传递函数时输入了fun hello/0 和fun hello/1。这会产生崩溃,但消除了编译器警告。
我哪里做错了?
【问题讨论】:
标签: erlang