为什么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不从第二个产生过程中接收退出消息?

第一个receive成功后,X绑定到其返回的值,即{'EXIT', <...>, reason}。由于您在第二个receive中使用相同的变量X,因此receive等待一条与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}

或者您可以使用f/1"忘记" X的值,然后再次使用X(这仅在REPP中起作用):

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}

最新更新