Erlang:列出所有记录

时间:2014-09-14 21:21:11

标签: erlang

请帮帮我,(顺便说一下,我的英语不是很好)。我想列出为gen_server创建的所有记录,例如,如果a具有以下代码:

-module(mod).
-record(person, {name, phone}).
start_link(Param1, Param2) -> 
    gen_server:start_link(?MODULE, [Param1, Param2], []).

init([Param1, Param2]) ->
   {ok, #person{name=Param1,phone=Param2}}.

我可以打电话:

mod:start_link(Maria,22222).
mod:start_link(Jose,9348).
mod:start_link(lol,232).

之后我想查看我创建的所有记录并将其放在列表中。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

没有机会以这种方式获取信息:每个gen_server有一条记录,一旦服务器死亡,信息就会丢失。如果您需要此信息,请添加一个专用流程来保存信息({Pid,Record}或记录号...)。可以通过诸如record_manager:create / 1和record_manager:delete / 1之类的函数在init和terminate函数期间更新信息。您也可以将它们存储在共享的地方。

答案 1 :(得分:0)

您应该阅读此文档:http://www.erlang.org/doc/man/gen_server.html#start_link-3

start_link/3只需启动gen_server,然后存储记录数据。

-module(record_make).
-compile(export_all).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-behaviour(gen_server).
-define(SERVER, ?MODULE). 

-record(state, {persons = []}).
-record(person, {name, phone}).

start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

init([]) ->
    {ok, #state{}}.

handle_call({create, Name, Phone}, _Frome, State = #state{persons = Persons}) ->
    NewPerson = #person{name = Name, phone = Phone},
    {reply, ok, State#state{persons = [NewPerson | Persons]}};
handle_call(list, _From, State = #state{persons = Persons}) ->
    io:format("~p~n", [Persons]),
    {reply, ok, State};
handle_call(_Request, _From, State) ->
    Reply = ok, 
    {reply, Reply, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok. 

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.



create(Name, Phone) ->
    gen_server:call(?MODULE, {create, Name, Phone}).
list() ->
    gen_server:call(?MODULE, list).

你可以这样做:

1> c(record_make)
1> .
{ok,record_make}
2> record_make:start_link().
{ok,<0.41.0>}
3> record_make:create("yang", "123").
ok
4> record_make:create("zhang", "456").
ok
5> record_make:list().
[{person,"zhang","456"},{person,"yang","123"}]
ok
6>