🎓 A1Learner
🔍
0 of 46 lessons completed

Elixir Process Links

A process link is a two-way connection between two processes. When one linked process ends with an error, the other linked process also ends.

A link connects two processes

The worker reports one connection after the link is made.

worker = spawn(fn ->
  loop = fn loop ->
    receive do
      {:links, caller} ->
        {:links, links} = Process.info(self(), :links)
        send(caller, length(links))
        loop.(loop)
      :stop -> :ok
    end
  end
  loop.(loop)
end)
Process.link(worker)
send(worker, {:links, self()})
count = receive do n -> n end
IO.puts(count)
send(worker, :stop)

A normal end does not spread

The linked worker ends normally, and the main process keeps running.

worker = spawn(fn -> receive do :stop -> :ok end end)
Process.link(worker)
send(worker, :stop)
:timer.sleep(100)
IO.puts(Process.alive?(worker))
IO.puts(Process.alive?(self()))

An error end spreads to the linked process

A watcher links to a child that ends with an error, and the watcher ends too.

watcher = spawn(fn ->
  receive do
    :go ->
      child = spawn(fn ->
        receive do :go -> exit(:boom) end
      end)
      Process.link(child)
      send(child, :go)
      receive do :stop -> :ok end
  end
end)
send(watcher, :go)
:timer.sleep(200)
IO.puts(Process.alive?(watcher))

Example

parent = self()
watcher = spawn(fn ->
  receive do
    :go ->
      child = spawn(fn ->
        receive do :go -> exit(:boom) end
      end)
      Process.link(child)
      {:links, links} = Process.info(self(), :links)
      send(parent, length(links))
      send(child, :go)
      receive do :stop -> :ok end
  end
end)
send(watcher, :go)
count = receive do n -> n end
IO.puts(count)
:timer.sleep(200)
IO.puts(Process.alive?(watcher))

Key points

  • Link: Process.link connects the calling process to another process.
  • Two-way: Each linked process records the other process in its list of connections.
  • Normal end: A linked process that ends normally does not end the other process.
  • Error end: A linked process that ends with an error ends the other linked process too.
  • Making: Call Process.link with the other process to make a link.

In this example, a watcher links to a child and reports one connection. The child then ends with an error, and the watcher ends too, so the watcher is no longer alive.

Note

Sending a message does not create a link between two processes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A linked process ends with an error. What happens to the other linked process?