0

考虑下面的代码:

-module(add_two).
-compile(export_all).

start()->
    process_flag(trap_exit, true),
    Pid = spawn_link(add_two, loop, []),
    register(add_two, Pid),
    ok.

request()->
    add_two ! bad,
    receive
        {'EXIT', _Pid, Reason} -> io:format("self:~w~n", [{error, Reason}]);
        {Result}               -> io:format("result:~w~n", [Result])
    after
        1000->timeout
    end.

loop()->
    receive
        bad                 -> exit(nogoodreason_bad);
        {request, Pid, Msg} -> Pid ! {result, Msg + 2}
    end,
    loop().

当我在 shell 中测试上面的代码时,我得到了两个不同输入顺序的不同结果,但是为什么呢?

第一个输入顺序:

Eshell V5.9.1  (abort with ^G)
1> add_two:request(ddd).
** exception error: undefined function add_two:request/1
2> add_two:start().
ok
3> add_two:request(). 
self:{error,nogoodreason_bad}
ok

第二个输入顺序:

Eshell V5.9.1  (abort with ^G)
1> add_two:start().
ok
2> add_two:request(ddd).
** exception error: undefined function add_two:request/1
3> add_two:request().
** exception error: bad argument
     in function  add_two:request/0 (add_two.erl, line 11)
4

1 回答 1

1

由于该调用,该调用add_two:request(ddd)使 shell 进程死亡,并带走了 add_two spawn_link()。您可以通过在异常前后检查 shell 的 pid 来确认这一点。它甚至不必涉及add_two模块:

12> self().
<0.61.0>
13> 2+2.
4
14> self().
<0.61.0>
15> 1/0.
** exception error: bad argument in an arithmetic expression
     in operator  '/'/2
        called as 1 / 0
16> self().
<0.69.0>
17> 

您可以通过调用spawn而不是spawn_link,或者在生成的进程中捕获和处理退出来避免这种影响。

于 2012-09-02T14:08:41.870 回答