Skip to content

Erlang erlang (process) API

erlang 模块的核心并发原语 —— spawn、消息发送、链接和监视,用于构建容错系统。

1 class · 8 methods

process functions

8 methods

用于创建、观察和控制 BEAM 进程的函数。进程不共享内存,仅通过异步消息传递通信。

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

创建调用 Module:Function(Args) 的新 BEAM 进程。立即返回新进程的 PID。

Parameters

NameTypeDescription
Moduleatom()包含函数的模块。
Functionatom()函数名(必须已导出)。
Args[term()]传递给函数的参数列表。

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

异步发送 Message 到 Pid 标识进程的邮箱。保证投递,且同一发送者-接收者对之间顺序不变。

Parameters

NameTypeDescription
Pidpid() | atom()接收者 PID 或注册名。
Messageterm()要投递的任意 Erlang 项。

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

按到达顺序扫描邮箱,寻找第一个匹配 Pattern(带可选 guard)的消息。若无匹配,阻塞直到收到或超时。

Parameters

NameTypeDescription
Patternsmatch clauses一个或多个 Pattern [when Guard] -> Body 子句。
Timeoutinteger() | infinity (optional)最大等待毫秒;0 = 非阻塞;infinity = 永久。

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

在当前进程和 Pid 之间创建双向链接。任一进程退出时,另一方收到退出信号 —— 默认也会使其崩溃。

Parameters

NameTypeDescription
Pidpid()要链接的进程。

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()

创建单向监视:调用进程观察 Pid,但 Pid 不受影响。Pid 死亡时调用者收到 {'DOWN', Ref, process, Pid, Reason}。

Parameters

NameTypeDescription
processatom()字面原子 —— 目前仅支持 'process'。
Pidpid()要监视的进程。

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

单参数时,以 Reason 终止当前进程。双参数时,向 Pid 发送退出信号(当前进程继续运行)。

Parameters

NameTypeDescription
Reasonterm()退出原因。normal/shutdown 不传播;kill 不可捕获。
Pidpid() (optional)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()

创建唯一引用,保证集群中任何节点的任何 make_ref 调用都不会再次返回它。

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

仅为当前进程设置进程标志。最重要的是 trap_exit,它将传入的退出信号转为消息。

Parameters

NameTypeDescription
Flagatom()标志名:trap_exit、priority、min_heap_size 等。
Valueterm()新值(如 trap_exit 的 true/false)。

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).