Elixir:完成函数执行后进程会发生什么

Elixir: What happen to a process after done executing the function

我正在尝试了解 spawnspawn_link 之间的差异,但无法完全理解进程执行的函数结束时会发生什么。

defmodule SendAndDie do
  def send_and_die(target) do
    send(target, "Goodbye")
    # Process.exit(self, :boom)
  end
end

dying_process = spawn_link(SendAndDie, :send_and_die, [self])
:timer.sleep(500)
IO.puts("Dying process is alive: #{Process.alive?(dying_process)}")
receive do
  msg -> IO.puts(msg)
end

我预计主进程会失败,因为它链接到一个在程序结束前明显死亡的进程。但是,打印了 "Goodbye" 消息,然后程序正常退出。将 spawn_link 更改为 spawn 无效。

当我取消注释第 4 行中的 Process.exit 时,我确实看到了 spawnspawn_link 之间的区别(后者停止了整个程序,而前者没有)。但是,Process.exitsend_and_die 函数中的最后一次执行。是不是函数结束了进程就退出了?

来自the erlang manual on processes

The default behaviour when a process receives an exit signal with an exit reason other than normal, is to terminate and in turn emit exit signals with the same exit reason to its linked processes.

当进程的初始函数 returns 终止时,原因是 normal,因此此默认行为不会关闭链接进程。