Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Processes and Message Passing

Registered processes and the process dictionary

Give Erlang processes names with register/2 and whereis/1, send to names, learn the limits of the name registry, and why the process dictionary is best avoided.

To send a message you need a pid. Passing pids around works, but sometimes a service should be reachable by a well-known name: a logger, a cache, a configuration server. Erlang provides a small local name registry for that, and every process also has a hidden, mutable process dictionary that you should know about, mostly so that you can recognise when not to use it.

Registering a name

register(Name, Pid) associates an atom with a pid on the current node.

ERLANG
1> Pid = spawn(fun() -> receive ping -> io:format("pong~n") end end).
<0.110.0>
2> register(pinger, Pid).
true
3> pinger ! ping.
pong
ping

The shell prints ping as the value of the send expression. Now any process on this node can write pinger ! Message without knowing the pid. The related functions:

ERLANG
whereis(pinger)      % returns the pid, or undefined
registered()         % list of all registered names
unregister(pinger)   % remove the name

A name is released automatically when the process dies, so a restarted process can register the same name again. Registering a name that is taken, or a pid that already has a name, raises badarg. Names must be atoms, and undefined is not allowed.

Why names help

A registered name survives restarts of the process behind it: clients keep writing to pinger, and the supervisor's new child takes over the name. This is why OTP servers are usually started with {local, Name}:

ERLANG
gen_server:start_link({local, kv_store}, kv_store, [], []).

Without a name every client would have to learn the new pid after each crash.

Wrapping a registered service

ERLANG
-module(logger_srv).
-export([start/0, log/1]).

start() ->
    Pid = spawn(fun loop/0),
    register(?MODULE, Pid),
    {ok, Pid}.

log(Text) ->
    ?MODULE ! {log, Text},
    ok.

loop() ->
    receive
        {log, Text} -> io:format("[log] ~s~n", [Text]), loop();
        stop        -> ok
    end.

?MODULE is the current module name as an atom, a convenient choice for a singleton service. Be aware of a race: between whereis(Name) and sending, the process can die. Prefer sending straight to the name and accept that Name ! Msg raises badarg if the name is unknown (it does not for pids). If you need safety, catch it or use a call with a timeout.

Limits of the local registry

  • It is per node; names are not visible on other nodes (use {Name, Node} ! Msg to reach one, see distributed nodes).
  • Names are atoms, and atoms are never garbage collected. Never create names from user input such as list_to_atom(UserText); you could exhaust the atom table (default limit about a million).
  • One name per process at a time, one process per name.

For dynamic names, large registries or cluster-wide lookup, OTP offers global, pg (process groups) and the community library gproc.

The process dictionary

Every process has a private key-value store, accessed with put/2, get/1 and erase/1:

ERLANG
put(color, blue),
blue = get(color),
undefined = get(missing),
[{color, blue}] = get(),    % everything
erase(color).

It is mutable, hidden and not part of the function arguments, so functions that use it are no longer pure: the same call can return different values. That hurts testing and reasoning. The Erlang community treats it as a last resort. Legitimate uses are narrow: logger metadata, tracing contexts, the rand module keeping its seed (that is why rand:uniform() needs no seed argument), and performance hot spots proven by measurement.

Do not use the process dictionary as a shortcut for passing state around. Put the state in the loop argument (process loops and state) or, for shared data, in ETS.

Process information

You can inspect any process with process_info/2, handy with names:

ERLANG
process_info(whereis(pinger), [registered_name, message_queue_len, status]).
%% [{registered_name,pinger},{message_queue_len,0},{status,waiting}]

The exact output depends on the state at the moment of the call.

Name or pid?

Registered name Well-known services, survives restarts
Pid Anonymous workers, per-connection state
Local only Names do not cross nodes
Atoms are never freed Never make names from user input
1 / 2

Run it: a name registry stand-in

This is JavaScript, not Erlang. A Map plays the registry. Notice how a name is freed when its process ends, and how registering a taken name fails like badarg.

JS Stand-in: register and whereis

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A process dictionary stand-in

The same idea in JavaScript: a hidden per-process object. The second function looks pure but is not, which makes it surprising.

JS Stand-in: hidden state surprises

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a registered name when its process terminates?

    The registry drops the name when the process dies, so a restarted process can register it again.
  2. 2. Why should you not build registered names from user input?

    Every new atom stays in memory forever; user-controlled atoms are a denial-of-service risk.
  3. 3. What does Name ! Msg do when Name is not registered?

    Sending to an unknown name raises badarg, unlike sending to a dead pid.
  4. 4. Why is the process dictionary discouraged?

    Functions reading it can return different results for the same arguments.

Summary

  • register/2, whereis/1 and unregister/1 manage a per-node name registry; names are atoms.
  • A name is freed automatically when its process dies, so supervisors can restart services under the same name.
  • Never create atoms from untrusted input.
  • Use global, pg or a library for cluster-wide or dynamic naming.
  • The process dictionary is mutable hidden state; avoid it in ordinary code.

Next: Links, monitors and exit signals