erlang link 與 monitor

erlang設計中,一般會有這樣一個需求: 某一個進程必須依賴於令一個進程的概念,在這樣的狀況下就必須對兩個進程之間創建一個監控或者說鏈接關係,以監聽對方的死亡狀況。

erlang 提供了兩個這樣的方法:link/1  monitor/2node

一、雙向監聽設計

-spec link(PidOrPort) -> true when
PidOrPort :: pid() | port().server

link(_PidOrPort) ->
erlang:nif_error(undefined).進程

把調用的此方法的進程跟_PidOrPort 連接起來,他們之間的連接是相互的。若是一條進程被退出另外一條進程會受到退出消息,格式爲{'EXIT', Pid, Reason}文檔

若是彼此都是gen_server,能夠這樣截取信息:源碼

  handle_info({'EXIT', _PID, _Reason}, State) ->it

    ok.監控

 

二、單向監聽:即當前調用進程去監聽另外一個進程。module

-spec monitor(Type, Item) -> MonitorRef when
Type :: process,
Item :: pid() | RegName | {RegName, Node},
RegName :: module(),
Node :: node(),
MonitorRef :: reference().erlang

monitor(_Type, _Item) ->
erlang:nif_error(undefined).

eg:  monitor(process, Pid), 即當前進程監聽 Pid 的退出銷燬信息,若是Pid被退出或者銷燬, 你的當前進程會收到{'DOWN', _Ref, _Msg, _PID, _Reason} 這樣的信息

若是你的進程是gen_server 能夠這樣截取信息:

  handle_info({'DOWN', _Ref, _, _PID, _Reason}, State) ->
    ok.

簡單的使用就是如此,若是須要繼續深刻能夠看看源碼,或這樣官方文檔。

相關文章
相關標籤/搜索