Elixir进程监控:: EXIT vs:DOWN

bsc*_*fer 2 elixir

我通常会看到进程监视的示例,其中处理受监视进程出口的代码如下:

handle_info({:DOWN, ref, :process, pid}, state)
Run Code Online (Sandbox Code Playgroud)

但我也看到过他们匹配:EXIT而不是:DOWN消息的例子.

到目前为止,我只能:DOWN在我自己的示例中触发消息,其中包括标准Process.exitGenServer.stop消息,以及在受监视的进程中引发异常.

:EXIT什么时候会收到消息?

Dog*_*ert 9

:EXIT被发送到另一个进程尝试退出的进程Process.exit(具有除了之外的原因:kill)但该进程正在捕获退出.:DOWN被发送到正在监视另一个进程的进程,并且受监视的进程因任何原因退出.

以下是两者的示例:

pid = spawn(fn ->
  Process.flag(:trap_exit, true)
  receive do
    x -> IO.inspect {:child, x}
  end
end)
Process.monitor(pid)
Process.sleep(500)
Process.exit(pid, :normal)
Process.sleep(500)
# A process cannot trap `:kill`; it _has_ to exit.
Process.exit(pid, :kill)
receive do
  x -> IO.inspect {:parent, x}
end
Run Code Online (Sandbox Code Playgroud)

输出:

{:child, {:EXIT, #PID<0.70.0>, :normal}}
{:parent, {:DOWN, #Reference<0.0.8.223>, :process, #PID<0.73.0>, :normal}}
Run Code Online (Sandbox Code Playgroud)