Processes and message passing
An Erlang process is a function running in its own memory, with its own mailbox. It shares nothing with the process that started it, and the only way to affect it is a message. That sounds like a restriction and is the reason a system built this way keeps running: no lock, no shared pointer, and a crash stays inside the process that met it.
spawn and the pid
spawn/1 starts a process from a fun and answers its pid at once. The caller keeps running, and the new process has its own heap, stack and mailbox. The pid changes on every run, so a session checks its type rather than printing its value:
erl
1> is_pid(spawn(fun() -> ok end)). true 2> self() ! {greet, "Ada"}. {greet,"Ada"} 3> receive {greet, Who} -> Who after 0 -> timeout end. "Ada" 4> receive stop -> yes after 0 -> timeout end. timeout
The second line sends a message to the shell itself, and the third receives it. The fourth shows the timeout: with after 0 the receive checks the mailbox once and runs the timeout branch if nothing matches, so a test never hangs.
Send with !
Pid ! Message copies the message into the mailbox of the target and answers the message. The sender does not wait, and the send cannot fail for a live pid, however busy the receiver is. A reply is a separate message, which is why a request carries the pid of the sender. The message protocols lesson turns that into a call with a reference and a timeout.
Selective receive
receive scans the mailbox for the first message that matches a pattern; messages that do not match stay where they are, in order. A process can therefore wait for the answer it needs and leave an unrelated message for later. This module queues two messages and takes the second one first:
mailbox.erl
-module(mailbox). -export([main/0]). main() -> self() ! first, self() ! second, A = receive second -> second_seen end, B = receive first -> first_seen end, io:format("~p~n", [A]), io:format("~p~n", [B]).
erlc mailbox.erl
erl -noshell -eval 'mailbox:main(), halt().'
second_seen first_seen
The first receive skips first and takes second; the second receive then finds the message that was skipped. The scan is linear in the number of queued messages, so a mailbox that keeps thousands of unmatched messages makes every receive slower. The selective receive lesson measures that cost.
A server loop
A process that owns state is a loop: receive a request, answer the sender, call itself with the new state. This echo server registers a name so a caller can find it, and the name disappears when the process stops:
echo.erl
-module(echo). -export([main/0, start/0, say/1, stop/0]). start() -> Pid = spawn(fun loop/0), register(echo, Pid), ok. say(Msg) -> echo ! {say, Msg, self()}, receive {echo, Reply} -> Reply end. stop() -> echo ! stop, ok. loop() -> receive {say, Msg, From} -> From ! {echo, Msg}, loop(); stop -> ok end. main() -> ok = start(), hello = say(hello), ok = stop(), io:format("done~n").
erlc echo.erl
erl -noshell -eval 'echo:main(), halt().'
done
The request carries self() so the server knows where to answer, and the answer is tagged echo so the receive of the caller matches it and not some other message. A loop with no state is the simplest server; the processes in depth lesson adds state and sys introspection.
A name that is not registered
Sending to a pid is safe, but sending to a name that no process registered raises badarg at once. A program that assumes a server is running and sends to its name crashes on the line of the send, with the name in the reason. The module catches it to show the class:
missing.erl
-module(missing). -export([main/0]). main() -> Result = try not_registered ! hello of _ -> sent catch error:badarg -> no_server end, io:format("~p~n", [Result]).
erlc missing.erl
erl -noshell -eval 'missing:main(), halt().'
no_server
The usual fix is not a catch but a lookup: whereis(echo) answers the pid or undefined, and a caller can return {error, not_running} before it sends. The process registry lesson covers names, global and the via tuple.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
spawn/1answer?Answer
The pid of the new process
It answers at once with the pid, and the caller keeps running.
-
What does a spawned process share with its parent?
Answer
Nothing
Each process has its own heap, stack, and mailbox, and messages are copied between them.
-
Why does the lesson call
is_pid(spawn(...))instead of printing the pid?Answer
A pid changes on every run, so a fixed transcript would not replay
The pid is new on every node, so the transcript checks its type, not its value.
-
What does
self() ! {greet, "Ada"}answer?Answer
{greet,"Ada"}The send operator answers the message it sent, so the shell echoes the tuple.
-
What does this module print?
-module(q1). -export([main/0]). main() -> self() ! first, self() ! second, A = receive second -> second_seen end, B = receive first -> first_seen end, io:format("~p~n", [A]), io:format("~p~n", [B]).Answer
second_seen/first_seenThe first receive skips
firstand takessecond; the next one findsfirststill queued. -
What does this module print?
-module(q2). -export([main/0]). main() -> Result = try not_registered ! hello of _ -> sent catch error:badarg -> no_server end, io:format("~p~n", [Result]).Answer
no_serverA send to an unregistered name raises badarg, and the catch names that case.
-
What does this module print?
-module(q3). -export([main/0]). main() -> Parent = self(), spawn(fun() -> Parent ! {hello, from_child} end), A = receive {hello, From} -> From after 1000 -> timeout end, B = receive {hello, From2} -> From2 after 0 -> already_taken end, io:format("~p~n", [A]), io:format("~p~n", [B]).Answer
from_child/already_takenThe first receive takes the message, so the second, with
after 0, finds nothing. -
What does this module print?
-module(q4). -export([main/0]). main() -> self() ! one, R = receive one -> got after 0 -> none end, io:format("~p~n", [R]).Answer
gotThe message is in the mailbox before the receive, so the pattern matches at once.
-
What happens to messages that do not match a
receivepattern?Answer
They stay queued for a later receive
receive is selective: skipped messages remain in the mailbox in their original order.
-
What does
register(echo, Pid)do?Answer
Binds the atom
echoto the pid for sending by nameAfter registration,
echo ! Msgreaches that process, and the name is released when it stops.
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.
Автор статьи: Arthur Isaev