Skip to content

Erlang erlang (process) API

The erlang module's core concurrency primitives — spawn, message sending, linking, and monitoring for building fault-tolerant systems.

1 class · 8 methods

process functions

8 methods

Functions for creating, observing, and controlling BEAM processes. Processes share no memory and communicate only by asynchronous message passing.

spawn(Module, Function, Args) -> pid()

Create a new BEAM process that calls Module:Function(Args). Returns immediately with the new process's PID.

Parameters

NameTypeDescription
Moduleatom()Module containing the function.
Functionatom()Function name (must be exported).
Args[term()]Argument list passed to the function.

Returns

pid() — the identifier of the newly created process.

Example

erlang
Pid = spawn(fun() -> timer:sleep(1000), io:format("done~n") end).
spawn(pingpong, ping, [3, PongPid]).
% spawn_link/3 spawns AND links atomically (no race window).
% spawn_monitor/3 spawns and monitors atomically.
Pid ! Message -> Message

Send Message asynchronously to the mailbox of the process identified by Pid. Delivery is guaranteed and order is preserved per sender-recipient pair.

Parameters

NameTypeDescription
Pidpid() | atom()Recipient PID or registered name.
Messageterm()Any Erlang term to deliver.

Returns

Returns Message itself, enabling broadcasts: [P ! Msg || P <- Pids].

Example

erlang
Pid ! {hello, self()}.
server ! {call, Ref, self(), Request}.

% Broadcast to all registered workers:
[ P ! {work, X} || P <- Workers ],

% Send to a registered process by atom name:
my_server ! ping.
receive Patterns after Timeout -> Body end

Scan the mailbox in arrival order for the first message matching a Pattern (with optional guard). If none match, block until one arrives or Timeout (ms) elapses.

Parameters

NameTypeDescription
Patternsmatch clausesOne or more Pattern [when Guard] -> Body clauses.
Timeoutinteger() | infinity (optional)Max wait in ms; 0 = non-blocking; infinity = forever.

Returns

The value of the matched clause's Body (or the after clause's Body on timeout).

Example

erlang
loop() ->
    receive
        {ping, From} -> From ! pong, loop();
        stop         -> ok
    end.

% with timeout
receive
    {reply, Ref, V} -> {ok, V}
after 5000 ->
    {error, timeout}
end.
link(Pid) -> true

Create a bidirectional link between the current process and Pid. If either process exits, the other receives an exit signal — by default crashing it too.

Parameters

NameTypeDescription
Pidpid()Process to link to.

Returns

true. Idempotent: linking an already-linked process is a no-op.

Example

erlang
link(WorkerPid).
% If the worker dies abnormally, this process also dies —
% unless it traps exits:
process_flag(trap_exit, true),
link(WorkerPid).
receive {'EXIT', WorkerPid, Reason} -> handle(Reason) end.

% spawn_link does both atomically (no race):
Pid = spawn_link(fun worker/0).
monitor(process, Pid) -> reference()

Create a one-way monitor: the calling process observes Pid, but Pid is unaffected. When Pid dies, the caller receives {'DOWN', Ref, process, Pid, Reason}.

Parameters

NameTypeDescription
processatom()Literal atom — only 'process' is currently supported.
Pidpid()Process to monitor.

Returns

reference() — unique tag used to identify this monitor and match its 'DOWN' message.

Example

erlang
Ref = monitor(process, WorkerPid),
receive
    {'DOWN', Ref, process, WorkerPid, normal} ->
        ok;
    {'DOWN', Ref, process, WorkerPid, Reason} ->
        {error, Reason}
end.
demonitor(Ref, [flush]).  % remove and discard any pending 'DOWN'
exit(Reason) -> no_return() / exit(Pid, Reason) -> true

With one argument, terminate the current process with Reason. With two arguments, send an exit signal to Pid (the current process keeps running).

Parameters

NameTypeDescription
Reasonterm()Exit reason. normal/shutdown don't propagate; kill is untrappable.
Pidpid() (optional)Target process for exit/2.

Returns

exit/1 never returns. exit/2 returns true.

Example

erlang
% terminate self:
exit(normal).
exit({shutdown, "graceful stop"}).

% force-kill another process (untrappable):
exit(Pid, kill).

% signal another process (trappable if it traps exits):
exit(Worker, {bad_input, Why}).
make_ref() -> reference()

Create a unique reference, guaranteed never to be returned again by any call to make_ref on any node in the cluster.

Returns

reference() — unique token used to tag requests, monitors, and replies.

Example

erlang
Ref = make_ref(),
Server ! {call, Ref, self(), Request},
receive
    {Ref, Reply} -> Reply     % match only OUR reply
after 5000 ->
    exit(timeout)
end.
% Used internally by gen_server:call/2,3 and monitor/2.
process_flag(Flag, Value) -> OldValue

Set a per-process flag for the current process only. The most important is trap_exit, which converts incoming exit signals into messages.

Parameters

NameTypeDescription
Flagatom()Flag name: trap_exit, priority, min_heap_size, etc.
Valueterm()New value (e.g. true/false for trap_exit).

Returns

The previous value of the flag.

Example

erlang
% Become a supervisor — survive child deaths:
process_flag(trap_exit, true),
Pid = spawn_link(fun worker/0),
receive
    {'EXIT', Pid, Reason} -> restart_child()
end.

% Priority: low | normal | high | max
process_flag(priority, high).

% Pin garbage-collection min heap (perf-critical workers):
process_flag(min_heap_size, 10000).