在Erlang/OTP ,Application表示作為一個單元,可以啟動和停止,執行一些特定功能的元件,并可以在其它系統中重新使用。Application控制器的子產品接口,是在每一個Erlang運作時系統啟動的程序,并包含用于控制Application(例如啟動和停止Application),以及通路Application的資訊(例如配置參數)的功能。
Erlang/OTP Application基本結構:
一個 Application 至少包含了3部分的内容:應用子產品、監督者子產品、資源檔案。
應用子產品(test_app.erl) :
-module(test_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_Type, StartArgs) ->
io:format("test app start~n"),
case test_sup:start_link(StartArgs) of
{ok, Pid} ->
{ok, Pid};
Error ->
Error
end.
stop(_State) ->
ok.
監督者子產品(test_sup.erl):
-module(test_sup).
-behaviour(supervisor).
-export([start_link/1, init/1]).
start_link(_) ->
io:format("test sup start link~n"),
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
io:format("test sup init~n"),
{ok,{
{one_for_one, 1, 60},
[]}
}.
資源檔案(test.app) :
{application,test,
[{description,"Test application"},
{vsn,"1.0.0"},
{modules,[test_app,test_sup]},
{registered,[test_app]},
{mod,{test_app,[]}},
{env,[]},
{applications,[kernel,stdlib]}]}.
erl編譯以上代碼後,執行指令啟動這個Application
1> application:start(test).
test app start
test sup start link
test sup init
ok
檢視這個Application有沒有加載
2> application:loaded_applications().
[{kernel,"ERTS CXC 138 10","2.16.2"},
{stdlib,"ERTS CXC 138 10","1.19.2"},
{test,"Test application","1.0.0"}]
Erlang/OTP Application啟動流程:
1、當erlang 執行application:start(test) 時,erlang會查找工作目錄有沒有 test.app 這個資源檔案,沒找到就報錯,如果找到,就按照 test.app 這個檔案的訓示,啟動 test 應用。
%% 比較完整的資源檔案:
{application,test, % 名稱
[{description,"Test application"}, % 描述
{vsn, "1.0.0"}, % 版本
{id, Id}, % id 同 erl -id ID
{modules, [test_app,test_sup]}, % 所有子產品,systools用來生成script/tar檔案
{maxP, Num}, % 最大程序數
{maxT, Time}, % 運作時間 機關毫秒
{registered, [test_app]}, % 指定名稱,systools用來解決名字沖突
{included_applictions, []}, % 指定子app,加載但不啟動
{mod, {test_app,[]}}, % 啟動子產品,[]為參數
{env, []}, % 配置env,可以使用application:get_env擷取
{applications,[kernel,stdlib]}]}. % 依賴項,啟動app前,必須有啟動的app
2、這裡重點看 {mod, {test_app,[]}} 參數,意思是告訴 erlang 要調用應用子產品(test_app)的start/2 函數。
-module(test_app).
start(_Type, StartArgs) ->
io:format("test app start~n"),
case test_sup:start_link(StartArgs) of
{ok, Pid} ->
{ok, Pid};
Error ->
Error
end.
3、緊接着,到了監督者子產品(test_sup),監督者子產品啟動了一個監督者程序,該程序會回調監督者子產品的 init/1 函數,根據這個函數的傳回值來啟動子程序。
%% 比較完整的監督者子產品 init/1 函數,僅參考,下篇再介紹參數意義
init([]) ->
{ok,
{{one_for_one, 1, 60}, % Strategy = {How, Max, Within}
[{ test_handler_worker, % Id = internal id
{test_server, start, []}, % StartFun = {M, F, A}
permanent, % Restart = permanent | transient | temporary
2000, % Shutdown = brutal_kill | int() >= 0 | infinity
worker, % Type = worker | supervisor
[test_server] % Modules = [Module] | dynamic
}]
}
}.
文章完整例子下載下傳 http://download.csdn.net/detail/cwqcwk1/6398337