第一个erlang application

1、创建目录结构 doc、ebin、include、priv、src

2、在ebin下创建应用描述文件,这里应用取名为 first_app,则创建的描述文件为first_app.app

{application, first_app,
  [{description,  "hello world,first app"},
   {id,           "first_app"},
   {vsn,          "0.1.0"},
   {modules,      [
                        first_app,
                        first_app_sup
                        ]},
   {registered,   "first_app_sup"},
   {applications, [kernel,stdlib]},
   {mod,          {first_app,[]}},
   {start_phases, []}
  ]
}.

3、下面编写 src/first_app.erl,此文件的唯一任务就是启动根监督者。

-module(first_app).

-behaviour(application).

-export([start/2,stop/1]).

start(_StartType,_StartArgs)->
        case first_app_sup:start_link() of
                {ok,Pid} -> {ok,Pid};
                Other    -> {error,Other}
        end.

stop(_State)->
        ok.

4、实现监督者 src/first_app_sup.erl

-module(first_app_sup).

-behaviour(supervisor).

-export([start_link/0,start_child/2]).

-export([init/1]).

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

start_child(Value,LeaseTime)->
        supervisor:start_child(?SERVER,[Value,LeaseTime]).

init([])->
        Element={
                first_app_tcp_listener,
                        {first_app_tcp_listener,start_link,[]},
                        permanent,10000,worker,
                        [first_app_tcp_listener]
                },
        Children=[Element],
        RestartStrategy={simple_one_for_one,0,1},
        {ok,{RestartStrategy,Children}}.

5、尝试运行:

先编译为beam

erlc -o ebin src/*.erl

再运行。

在erl中输入

application:start(first_app).

注意:simple_one_for_one需要手动去调用start_child才会产生子进程。

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /opt/wordpress/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048