iT邦幫忙

DAY 17
1

蠻可愛的 Erlang 與 Elixir系列 第 17

Concurrent程式設計之捕捉process離開信號 #1

昨天介紹到了捕捉process離開信號,今天要來看一下,
捕捉到了以後process的行為.

先看以下的程式:

-module(e1017a).
-export([start/2,
       status/2]).

%%
start(Bool, M) ->
  A = spawn(fun() -> a() end),
  B = spawn(fun() -> b(A, Bool) end),
  C = spawn(fun() -> c(B, M) end),
  sleep(1000),
  status(b, B),
  status(c, C).
%
a() ->
  process_flag(trap_exit, true),
  wait(a).
%
b(A, Bool) ->
  process_flag(trap_exit, Bool),
  link(A),
  wait(b).
%
c(B, M) ->
  link(B),
  case M of
    {die, Reason} ->
      exit(Reason);
    {divide, N} ->
      1/N,
      wait(c);
    normal ->
      exit(normal)
  end.
%
wait(Prog) ->
  receive
    Any ->
      io:format("Process ~p received ~p~n", [Prog, Any]),
      wait(Prog)
  end.
%
sleep(T) ->
  receive
  after T -> true
  end.
%
status(Name, Pid) ->
  case erlang:is_process_alive(Pid) of
    true ->
      io:format("Process ~p (~p) is alive~n", [Name, Pid]);
    false ->
      io:format("Process ~p (~p) is dead~n", [Name, Pid])
  end.
%

編譯:

1> c(e1017a).
e1017a.erl:29: Warning: the result of the expression is ignored 
(suppress the warning by assigning the expression to the _ variable)
{ok,e1017a}

編譯時發出警告: 1/N, 這有可能會發生錯誤.例如除以0,或是null.
我們實際上就是要讓他們發生這類的錯誤,所以不用擔心.

執行:

情境1

[A] <--> [B](Non-System) <--> [C]

2> e1017a:start(false, {die, by_command}).
Process a received {'EXIT',<0.41.0>,by_command}
Process b (<0.41.0>) is dead
Process c (<0.42.0>) is dead
ok

我們在start 傳入 false,所以 [B] 是屬於 Non-System.

過程如:

[A] <--> [B](Non-System) <-- dead [C]
[A] <--> [B] dead
[A] <-- Reason: by_command [B]

A是System_process會收到系統協助[B]廣播送來的C的離開原因.
start經過sleep後,將[B],[C]的狀況顯示出來,都是dead.

情境2

[A] <--> [B](Non-System) <--> [C]

這次[C]將正常離開.

3> e1017a:start(false, normal).           
Process b (<0.45.0>) is alive
Process c (<0.46.0>) is dead
ok

過程如:

[A] <--> [B](Non-System) <-- Normal Exit
[A] <--> [B](Non-System)

start經過sleep後,將[B],[C]的狀況顯示出來, [C] dead, [B] alive.

情境3

[A] <--> [B](Non-System) <--> [C]

這次[C]會發生除以0錯誤.

4> e1017a:start(false, {divide, 0}).
Process a received {'EXIT',<0.49.0>,
                       {badarith,
                           [{e1017a,c,2,[{file,"e1017a.erl"},{line,29}]}]}}

=ERROR REPORT==== 17-Oct-2014::14:54:57 ===
Error in process <0.50.0> with exit value: {badarith,[{e1017a,c,2,[{file,"e1017a.erl"},{line,29}]}]}

Process b (<0.49.0>) is dead
Process c (<0.50.0>) is dead
ok

過程:

[A] <--> [B](Non-System) <-- dead(Reason:badarith) [C]
[A] <--> [B] dead =ERROR REPORT====
[A] <-- dead(Reason:badarith)

start經過sleep後,將[B],[C]的狀況顯示出來,都是dead.

而且除以0會產生System Error report.

透過上面3個情境,可以了解一部分捕捉離開信號,各processes之間的互動關係.
明天我們繼續介紹.


上一篇
Concurrent程式設計之Processes錯誤狀況處理
下一篇
Concurrent程式設計之捕捉process離開信號 #2
系列文
蠻可愛的 Erlang 與 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言