【问题标题】:Why does erlang shell receive exit message from spawned processes only once?为什么 erlang shell 只从生成的进程接收退出消息一次?
【发布时间】:2018-05-23 16:36:20
【问题描述】:

代码如下:

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 没有收到来自第二个衍生进程的退出消息?

【问题讨论】:

    标签: erlang erlang-shell


    【解决方案1】:

    在第一个receive 成功后,X 绑定到它的返回值,即{'EXIT', &lt;...&gt;, reason}。由于您在第二个receive 中使用了相同的变量Xreceive 等待与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(这只适用于 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}
    

    【讨论】:

    • 当然!忘记了模式匹配,感谢您的解释。
    猜你喜欢
    • 2023-03-31
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多