为什么erlang shell只从生成的进程接收退出消息一次?

时间:2017-12-09 17:24:37

标签: erlang erlang-shell

这是代码:

Erlang/OTP 20 [erts-9.1] [source] [64-bit] [smp:2:2] [ds:2:2:10] [async-threads:10] [kernel-poll:false]

Eshell V9.1  (abort with ^G)
1> process_flag(trap_exit, true).
false
2> spawn_link(fun() -> exit(reason) end).
<0.63.0>
3> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.63.0>,reason}
4> spawn_link(fun() -> exit(reason) end).
<0.66.0>
5> receive X -> X after 0 -> 'end' end.  
'end'

为什么erlang shell不会从第二个衍生进程接收退出消息?

1 个答案:

答案 0 :(得分:7)

在第一个receive成功后,X绑定到其返回值,即{'EXIT', <...>, reason}。由于您在第二个X中使用相同的变量receivereceive会等待与X的旧值完全匹配的消息,该消息不会与第二条消息,因为它的PID与第一条消息不同。

要解决此问题,您可以使用其他变量名称:

1> process_flag(trap_exit, true).
false
2> spawn_link(fun() -> exit(reason) end).
<0.67.0>
3> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.67.0>,reason}
4> X.
{'EXIT',<0.67.0>,reason}
5> spawn_link(fun() -> exit(reason) end).
<0.71.0>
6> receive X2 -> X2 after 0 -> 'end' end.
{'EXIT',<0.71.0>,reason}

或者你可以忘记&#34; X的值使用f/1,然后再次使用X(这只适用于REPL):

7> spawn_link(fun() -> exit(reason) end).
<0.74.0>
8> f(X).
ok
9> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.74.0>,reason}