Spawn and links

A process that is started and forgotten is a loose end: nobody owns its failure. A link is the ownership. It ties two processes together, and when one dies the other hears the reason, either as its own death or, if it traps exits, as a message. The processes lesson started a process; this one makes its failure part of the caller.

spawn and spawn/3

spawn/1 takes a fun and spawn/3 takes a module, a function and its argument list. Both answer a pid at once; the child runs the code with no link and no owner. The three-argument form is the same start with a named function instead of a fun:

erl

1> is_pid(spawn(io, format, ["worker~n"])). worker true

The pid is not printed because it changes on every run; the shell checks its type. A bare spawn is right for a process that owns itself, such as the own helper of the shell; a process that belongs to a failure unit is started with a link.

link

link(Pid) ties the caller and the target together and answers true. The link is symmetric: each side watches the other, and no agreement from the target is needed. unlink(Pid) removes it and also answers true. A link is the primitive that a supervisor builds on, and it exists only between live processes.

spawn_link

spawn_link/1 starts the process and links it before the child runs a line, so there is no moment in which the child could die unlinked. This program traps the exit, starts a child that fails, and reads the reason from the message the link delivers:

links.erl

-module(links). -export([main/0]). main() -> process_flag(trap_exit, true), Pid = spawn_link(fun() -> exit(kaboom) end), receive {'EXIT', Pid, Reason} -> io:format("~p~n", [Reason]) end.

erlc links.erl

erl -noshell -eval 'links:main(), halt().'

kaboom

The receive matches the pid of the child on purpose: an EXIT message from some other linked process would not satisfy the pattern and would stay in the mailbox. In a real process the clause usually matches {'EXIT', _Pid, Reason} and decides from the reason.

A normal exit

A link does not turn every death into a disaster. A child that returns normally sends normal, and a linked process that does not trap exits ignores it. This program links a child that returns at once and proves that the parent is still there:

normal.erl

-module(normal). -export([main/0]). main() -> Pid = spawn_link(fun() -> ok end), timer:sleep(10), io:format("~p~n", [is_process_alive(Pid)]), io:format("alive~n").

erlc normal.erl

erl -noshell -eval 'normal:main(), halt().'

false alive

The child is gone and the parent is alive, which is the rule that lets a supervisor keep a temporary worker without restarting the world when it finishes.

trap_exit

process_flag(trap_exit, true) turns exit signals into ordinary messages of the form {'EXIT', Pid, Reason}. The call answers the previous value of the flag. A new process starts with the flag off, but the process that runs erl -noshell -eval starts with it on, so a program that shows the toggle sets it off first:

trap.erl

-module(trap). -export([main/0]). main() -> process_flag(trap_exit, false), Old = process_flag(trap_exit, true), New = process_flag(trap_exit, false), io:format("~p~n", [Old]), io:format("~p~n", [New]).

erlc trap.erl

erl -noshell -eval 'trap:main(), halt().'

false true

The first answer is the value before switching the flag on, and the second is the value before switching it off. In a fresh child process both are the same as here; in the shell the first call usually answers false because the shell starts with trapping off.

The link that kills the parent

The mistake is to link a worker and not decide who survives its failure. With trapping off, the abnormal reason travels the link and kills the parent with the same reason: the failure is now shared, which is right for a unit that must restart together and wrong for one request that should fail alone.

A supervisor links to its children on purpose, because the restart is the repair; a request handler that spawns a helper usually does not link, and reports the failure to its caller instead. The supervisors lesson shows the first choice, and the monitors lesson the second: a monitor reports a death without sharing it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does spawn/3 take?

    Answer

    A module, a function, and an argument list

    spawn(Module, Function, Args) names the code to run, as in spawn(io, format, ["worker~n"]).

  2. What does link(Pid) answer?

    Answer

    true

    Linking succeeds silently and answers true.

  3. Is a link symmetric?

    Answer

    Yes, each process watches the other

    A link ties both sides, with no agreement needed from the other process.

  4. Why is spawn_link safer than spawn followed by link?

    Answer

    The child is linked before it runs, so it cannot die unlinked

    The link exists before the first line of the child runs, closing the race window.

  5. What does this module print? -module(q1). -export([main/0]). main() -> process_flag(trap_exit, true), Pid = spawn_link(fun() -> exit(kaboom) end), receive {'EXIT', Pid, Reason} -> io:format("~p~n", [Reason]) end.

    Answer

    kaboom

    The trap turns the exit signal into an EXIT message, and the receive prints its reason.

  6. What does this module print? -module(q2). -export([main/0]). main() -> Pid = spawn_link(fun() -> ok end), timer:sleep(10), io:format("~p~n", [is_process_alive(Pid)]).

    Answer

    false

    The child returned and is gone; a normal exit does not kill the linked parent.

  7. What does this module print? -module(q3). -export([main/0]). main() -> process_flag(trap_exit, false), Old = process_flag(trap_exit, true), New = process_flag(trap_exit, false), io:format("~p~n", [Old]), io:format("~p~n", [New]).

    Answer

    false / true

    Each call answers the previous value, and the first line set the flag off.

  8. What does this module print? -module(q4). -export([main/0]). main() -> Pid = spawn(fun() -> receive stop -> ok end end), Link = link(Pid), Unlink = unlink(Pid), io:format("~p~n", [{Link, Unlink}]), Pid ! stop.

    Answer

    {true,true}

    Both link/1 and unlink/1 answer true, whatever the pid.

  9. What does a linked process receive when its partner dies abnormally?

    Answer

    An exit signal with the same reason

    The exit reason travels along the link; the receiver dies of it unless it traps exits.

  10. What happens after process_flag(trap_exit, false)?

    Answer

    Exit signals kill the process again

    With trapping off, an abnormal exit reason from a link kills the process as usual.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev