Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

process

elixir

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?

like image 401
Nagasaki45 Avatar asked Mar 12 '23 06:03

Nagasaki45


1 Answers

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.

like image 167
Paweł Obrok Avatar answered Apr 26 '23 03:04

Paweł Obrok