为什么这段代码得到不同的结果,在shell中输入不同的顺序?

时间:2012-09-02 13:42:59

标签: erlang

考虑代码漏洞:

-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)

1 个答案:

答案 0 :(得分:1)

由于add_two:request(ddd)调用,调用spawn_link()使shell进程死亡,并将add_two向下移动。您可以通过在异常之前和之后检查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,或在生成的流程中捕获和处理退出来避免此效果。