I'm trying to understand the differences between spawn
and spawn_link
, but can't quite grasp what happens when the function the process executes ends.
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
I expected the main process to fail, as it linked to a process that clearly died before the end of the program. However, the "Goodbye" message is printed and then the program exits normally. Changing spawn_link
to spawn
have no effect.
When I uncomment the Process.exit
in line 4 I do see the difference between spawn
and spawn_link
(the later stops the whole program while the former doesn't). But, the Process.exit
is the last execution in the send_and_die
function. Isn't the process going to exit anyway when the function ends?
From 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.
When the initial function of the process returns it terminates with reason normal
, so this default behaviour does not bring down the linked process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With