erlang(3)
erlang(3) — The Erlang BIFs and predefined types ✨💖
okay bestie, welcome to the manual page for erlang — section 3, Erlang Module Definition. This is where the BIFs and the predefined types live. It's giving "core of the language" energy, periodt. 👑
NAME
erlang — The Erlang BIFs and predefined types. 💖
DESCRIPTION
By convention, most Built-In Functions (BIFs) and all predefined types are bundled into this module. Some of the BIFs and every single predefined type are basically treated as part of the Erlang programming language itself and are auto-imported. So you literally don't have to specify the module name. Like, atom_to_list(erlang) and erlang:atom_to_list(erlang) are identical. no cap. 💅
Auto-imported BIFs are annotated with auto-imported, and predefined types are annotated with predefined. 🏷️
Some auto-imported BIFs are also allowed in guard expressions. Those BIFs are annotated with both auto-imported and guard-bif. 🔥
BIFs can fail for various reasons. All BIFs fail with reason badarg if they are called with arguments of an incorrect type. The other reasons are described in the description of each individual BIF. (So like, read the fine print, bestie.) 💀
DATA TYPES
Here's the whole squad of predefined types. Don't skip — they're all iconic in their own way. 🌈
any()
any() :: any().
All possible Erlang terms. Synonym for term/0. ✨
arity()
arity() :: arity().
The arity of a function, type or callback. 🔢
atom()
atom() :: atom().
An Erlang atom. 💎
binary()
binary() :: <<_:_*8>>.
An Erlang binary, that is, a bitstring with a size divisible by 8. 🧬
bitstring()
bitstring() :: <<_:_*1>>.
An Erlang bitstring. 🪢
bitstring_list()
bitstring_list() ::
maybe_improper_list(byte() | bitstring() | bitstring_list(),
bitstring() | []).
boolean()
boolean() :: true | false.
A boolean value. ✅
byte()
byte() :: 0..255.
A byte of data represented by an integer. 🧱
char()
char() :: 0..1114111.
An ASCII character or a unicode codepoint presented by an integer. 🅰️
cpu_topology()
cpu_topology() :: [LevelEntry :: level_entry()] | undefined.
The current cpu topology. 🖥️
node refers to Non-Uniform Memory Access (NUMA) nodes. thread refers to hardware threads (for example, Intel hyper-threads). 🧵
A level in term CpuTopology can be omitted if only one entry exists and InfoList is empty.
thread can only be a sublevel to core. core can be a sublevel to processor or node. processor can be on the top level or a sublevel to node. node can be on the top level or a sublevel to processor. That is, NUMA nodes can be processor internal or processor external. A CPU topology can consist of a mix of processor internal and external NUMA nodes, as long as each logical CPU belongs to one NUMA node. Cache hierarchy is not part of the CpuTopology type, but will be in a future release. Other things can also make it into the CPU topology in a future release. So, expect the CpuTopology type to change. 👀
deprecated_time_unit()
deprecated_time_unit() ::
seconds | milli_seconds | micro_seconds | nano_seconds.
The time_unit/0 type also consist of the following deprecated symbolic time units:
seconds— Same assecond.milli_seconds— Same asmillisecond.micro_seconds— Same asmicrosecond.nano_seconds— Same asnanosecond.
(they're deprecated, so like, noted.) ⏳
dist_handle() (opaque)
-opaque dist_handle()
An opaque handle identifying a distribution channel. 📡
dynamic()
dynamic() :: dynamic().
The dynamic type, which represents a statically unknown type. 🌀
ext_binary()
ext_binary() :: binary().
A binary data object, structured according to the Erlang external term format. 📦
ext_iovec()
ext_iovec() :: iovec().
A term of type iovec/0, structured according to the Erlang external term format. 🧳
float()
float() :: float().
An Erlang float. 🫧
fun_info_item()
fun_info_item() ::
arity | env | index | name | module | new_index | new_uniq |
pid | type | uniq.
function()
function() :: fun().
An Erlang fun. 🎉
garbage_collection_defaults()
garbage_collection_defaults() ::
[{max_heap_size, non_neg_integer()} |
{min_bin_vheap_size, non_neg_integer()} |
{min_heap_size, non_neg_integer()} |
{fullsweep_after, non_neg_integer()}].
A list with the system wide garbage collection defaults. 🗑️
halt_options()
halt_options() ::
[{flush, boolean()} |
{flush_timeout, Timeout :: 0..2147483647 | infinity}].
identifier()
identifier() :: pid() | port() | reference().
An unique identifier for some entity, for example a process, port or monitor. 🆔
info_list()
info_list() :: [].
integer()
integer() :: integer().
An Erlang integer. 🔢
iodata()
iodata() :: iolist() | binary().
A binary or list containing bytes and/or iodata. 📝
This datatype is used to represent data that is meant to be output using any I/O module. For example: file:write/2 or gen_tcp:send/2.
To convert an iodata/0 term to binary/0 you can use iolist_to_binary/2. To transcode a string/0 or unicode:chardata/0 to iodata/0 you can use unicode:characters_to_binary/1. 🔁
iolist()
iolist() ::
maybe_improper_list(byte() | binary() | iolist(),
binary() | []).
A list containing bytes and/or iodata. 📋
This datatype is used to represent data that is meant to be output using any I/O module. For example: file:write/2 or gen_tcp:send/2.
In most use cases you want to use iodata/0 instead of this type. 💡
iovec()
iovec() :: [binary()].
A list of binaries. This datatype is useful to use together with enif_inspect_iovec. 🧊
level_entry()
level_entry() ::
{LevelTag :: level_tag(), SubLevel :: sub_level()} |
{LevelTag :: level_tag(),
InfoList :: info_list(),
SubLevel :: sub_level()}.
level_tag()
level_tag() :: core | node | processor | thread.
link_option()
link_option() :: priority.
See link/2. 🔗
list()
list() :: [any()].
An Erlang list containing terms of any type. 📜
list(ContentType)
list(ContentType) :: [ContentType].
An Erlang list containing terms of the type ContentType. 📃
map()
map() :: #{any() => any()}.
An Erlang map containing any number of key and value associations. 🗺️
match_variable()
match_variable() :: atom().
max_heap_size()
max_heap_size() ::
Size ::
non_neg_integer() |
#{size => non_neg_integer(),
kill => boolean(),
error_logger => boolean(),
include_shared_binaries => boolean()}.
Process max heap size configuration. For more info see process_flag(max_heap_size, MaxHeapSize). 📈
maybe_improper_list()
maybe_improper_list() :: maybe_improper_list(any(), any()).
An Erlang list that is not guaranteed to end with a [], and where the list elements can be of any type. 🤷♀️
maybe_improper_list(ContentType, TerminationType)
maybe_improper_list(ContentType, TerminationType) ::
maybe_improper_list(ContentType, TerminationType).
An Erlang list, that is not guaranteed to end with a [], and where the list elements are of the type ContentType. 📎
memory_type()
memory_type() ::
total | processes | processes_used | system | atom |
atom_used | binary | code | ets.
message_queue_data()
message_queue_data() :: off_heap | on_heap.
See process_flag(message_queue_data, MQD). 📨
Process message queue data configuration. For more information, see process_flag(message_queue_data, MQD). 📬
mfa()
mfa() :: {module(), atom(), arity()}.
A three-tuple representing a Module:Function/Arity function signature. 🧩
module()
module() :: atom().
An Erlang module represented by an atom. 📦
monitor_option()
monitor_option() ::
{alias, explicit_unalias | demonitor | reply_demonitor} |
{tag, term()} |
priority.
See monitor/3. 👀
monitor_port_identifier()
monitor_port_identifier() :: port() | registered_name().
monitor_process_identifier()
monitor_process_identifier() ::
pid() | registered_process_identifier().
neg_integer()
neg_integer() :: neg_integer().
A negative integer. ➖
nif_resource() (opaque)
-opaque nif_resource()
An opaque handle identifying a NIF resource object . 🧿
nil()
nil() :: [].
The empty list/0. 🕳️
no_return()
no_return() :: none().
The type used to show that a function will never return a value, that is it will always throw an exception. 🚫
node()
node() :: atom().
An Erlang node represented by an atom. 🛰️
non_neg_integer()
non_neg_integer() :: non_neg_integer().
A non-negative integer, that is any positive integer or 0. 0️⃣
none()
none() :: none().
This type is used to show that a function will never return a value; that is it will always throw an exception. 🙅♀️
In a spec, use no_return/0 for the sake of clarity. 📝
nonempty_binary()
nonempty_binary() :: <<_:8, _:_*8>>.
A binary/0 that contains some data. 📦
nonempty_bitstring()
nonempty_bitstring() :: <<_:1, _:_*1>>.
A bitstring/0 that contains some data. 🧶
nonempty_improper_list(ContentType, TerminationType)
nonempty_improper_list(ContentType, TerminationType) ::
nonempty_improper_list(ContentType, TerminationType).
A maybe_improper_list/2 that contains some items. 🧺
nonempty_list()
nonempty_list() :: [any(), ...].
A list/0 that contains some items. 📚
nonempty_list(ContentType)
nonempty_list(ContentType) :: [ContentType, ...].
A list(ContentType) that contains some items. 📖
nonempty_maybe_improper_list()
nonempty_maybe_improper_list() ::
nonempty_maybe_improper_list(any(), any()).
A maybe_improper_list/0 that contains some items. 🧳
nonempty_maybe_improper_list(ContentType, TerminationType)
nonempty_maybe_improper_list(ContentType, TerminationType) ::
nonempty_maybe_improper_list(ContentType, TerminationType).
A maybe_improper_list(ContentType, TerminationType) that contains some items. 🧺
nonempty_string()
nonempty_string() :: [char(), ...].
A string/0 that contains some characters. 🔤
number()
number() :: integer() | float().
An Erlang number. 🔢
pid()
pid() :: pid().
An Erlang process identifier. 🆔
port()
port() :: port().
An Erlang port identifier. 🔌
pos_integer()
pos_integer() :: pos_integer().
An integer greater than zero. ➕
prepared_code() (opaque)
-opaque prepared_code()
priority_level()
priority_level() :: low | normal | high | max.
Process priority level. For more info see process_flag(priority, Level). ⚡
process_info_item()
process_info_item() ::
async_dist | backtrace | binary | catchlevel |
current_function | current_location | current_stacktrace |
dictionary |
{dictionary, Key :: term()} |
error_handler | garbage_collection | garbage_collection_info |
group_leader | heap_size | initial_call | links | label |
last_calls | memory | message_queue_len | messages |
min_heap_size | min_bin_vheap_size | monitored_by | monitors |
message_queue_data | parent | priority | priority_messages |
reductions | registered_name | sequential_trace_token |
stack_size | status | suspending | total_heap_size | trace |
trap_exit.
🌸 process_info_result_item()
process_info_result_item() ::
{async_dist, Enabled :: boolean()} |
{backtrace, Bin :: binary()} |
{binary,
BinInfo ::
[{non_neg_integer(),
non_neg_integer(),
non_neg_integer()}]} |
{catchlevel, CatchLevel :: non_neg_integer()} |
{current_function,
{Module :: module(), Function :: atom(), Arity :: arity()} |
undefined} |
{current_location,
{Module :: module(),
Function :: atom(),
Arity :: arity(),
Location ::
[{file, Filename :: string()} |
{line, Line :: pos_integer()}]}} |
{current_stacktrace, Stack :: [stack_item()]} |
{dictionary, Dictionary :: [{Key :: term(), Value :: term()}]} |
{{dictionary, Key :: term()}, Value :: term()} |
{error_handler, Module :: module()} |
{garbage_collection, GCInfo :: [{atom(), non_neg_integer()}]} |
{garbage_collection_info,
GCInfo :: [{atom(), non_neg_integer()}]} |
{group_leader, GroupLeader :: pid()} |
{heap_size, Size :: non_neg_integer()} |
{initial_call, mfa()} |
{links, PidsAndPorts :: [pid() | port()]} |
{label, term()} |
{last_calls, false | (Calls :: [mfa()])} |
{memory, Size :: non_neg_integer()} |
{message_queue_len, MessageQueueLen :: non_neg_integer()} |
{messages, MessageQueue :: [term()]} |
{min_heap_size, MinHeapSize :: non_neg_integer()} |
{min_bin_vheap_size, MinBinVHeapSize :: non_neg_integer()} |
{max_heap_size, MaxHeapSize :: max_heap_size()} |
{monitored_by,
MonitoredBy :: [pid() | port() | nif_resource()]} |
{monitors,
Monitors ::
[{process | port,
Pid ::
pid() |
port() |
{RegName :: atom(), Node :: node()}}]} |
{message_queue_data, MQD :: message_queue_data()} |
{parent, pid() | undefined} |
{priority, Level :: priority_level()} |
{priority_messages, Enabled :: boolean()} |
{reductions, Number :: non_neg_integer()} |
{registered_name, [] | (Atom :: atom())} |
{sequential_trace_token,
[] | (SequentialTraceToken :: term())} |
{stack_size, Size :: non_neg_integer()} |
{status,
Status ::
exiting | garbage_collecting | waiting | running |
runnable | suspended} |
{suspending,
SuspendeeList ::
[{Suspendee :: pid(),
ActiveSuspendCount :: non_neg_integer(),
OutstandingSuspendCount :: non_neg_integer()}]} |
{total_heap_size, Size :: non_neg_integer()} |
{trace, InternalTraceFlags :: non_neg_integer()} |
{trap_exit, Boolean :: boolean()}.
Bestie this one is long — it's every single little thing process_info/1 can hand back about a process. Every key you can ask for lives in here. 💅
🦋 processes_iter_ref()
-opaque processes_iter_ref()
An opaque ref, so like… don't peek inside, just pass it around. 🙈
✨ raise_stacktrace()
raise_stacktrace() ::
[{module(), atom(), arity() | [term()]} |
{function(), arity() | [term()]}] |
stacktrace().
It's giving stacktrace/0 but ✨extra✨ — a beefed-up stacktrace you can hand straight to raise/3. Ngl, this is the one you want when you're re-raising with style.
💖 record()
record() :: record().
A native record. That's it, that's the whole vibe. 🎀
🌈 reference()
reference() :: reference().
An Erlang reference. Iconic, unique, never repeats itself (fr fr). ✨
🍓 registered_name()
registered_name() :: atom().
Literally just an atom, but it's the atom a process is registered under. 💫
🧚 registered_process_identifier()
registered_process_identifier() ::
registered_name() | {registered_name(), node()}.
Either a cute little local registered name, or the name plus the node it lives on. 🫶
👑 scheduler_bind_type()
scheduler_bind_type() ::
no_node_processor_spread | no_node_thread_spread | no_spread |
processor_spread | spread | thread_spread |
thread_no_node_processor_spread | unbound.
The requested scheduler bind type — aka how the schedulers get glued to your CPUs. 🧵
💜 send_destination()
send_destination() ::
pid() |
reference() |
port() |
(RegName :: atom()) |
{RegName :: atom(), Node :: node()}.
The destination for a send operation — where your message is headed, basically your message's ✈️ boarding pass.
And it can be, in order:
- a remote or local process identifier (
pid()), - a (local) port,
- a reference denoting a process alias,
- a locally registered name,
- or a tuple
{RegName, Node}for a registered name sitting over on another node.
🎀 spawn_opt_option()
spawn_opt_option() ::
link |
{link, LinkOpts :: [link_option()]} |
monitor |
{monitor, MonitorOpts :: [monitor_option()]} |
{priority, Level :: priority_level()} |
{fullsweep_after, Number :: non_neg_integer()} |
{min_heap_size, Size :: non_neg_integer()} |
{min_bin_vheap_size, VSize :: non_neg_integer()} |
{max_heap_size, Size :: max_heap_size()} |
{message_queue_data, MQD :: message_queue_data()} |
{async_dist, Enabled :: boolean()}.
These are the options for spawn_opt(). So many knobs, lowkey obsessed. 🔧
⭐ stack_item()
stack_item() ::
{Module :: module(),
Function :: atom(),
Arity :: arity() | (Args :: [term()]),
Location ::
[{file, Filename :: string()} |
{line, Line :: pos_integer()}]}.
One single frame on the stack. Cute little tuple doing a lot of work. 💅
🌸 stacktrace()
stacktrace() ::
[{module(),
atom(),
arity() | [term()],
[stacktrace_extrainfo()]} |
{function(), arity() | [term()], [stacktrace_extrainfo()]}].
An Erlang stacktrace, exactly as described by the Errors and Error Handling chapter in the Erlang Reference Manual. Read that if you want the full lore. 📖
🦋 stacktrace_extrainfo()
stacktrace_extrainfo() ::
{line, pos_integer()} |
{file, unicode:chardata()} |
{error_info,
#{module => module(), function => atom(), cause => term()}} |
{atom(), term()}.
The little bonus bits riding along with a stack frame. ✨
🍓 string()
string() :: [char()].
A character string represented by a list of ASCII characters or unicode codepoints. Yes bestie, Erlang strings are lists, we've all cried about it, it's fine. 😭
🧚 sub_level()
sub_level() ::
[LevelEntry :: level_entry()] |
(LogicalCpuId :: {logical, non_neg_integer()}).
Either a list of level entries or a logical CPU id. CPU core moment. 🧠
💜 system_monitor_option()
system_monitor_option() ::
busy_port | busy_dist_port |
{long_gc, non_neg_integer()} |
{long_message_queue,
{Disable :: non_neg_integer(), Enable :: pos_integer()}} |
{long_schedule, non_neg_integer()} |
{large_heap, non_neg_integer()}.
All the stuff the system monitor can watch for. Eyes 👀 everywhere.
🌈 system_profile_option()
system_profile_option() ::
exclusive | runnable_ports | runnable_procs | scheduler |
timestamp | monotonic_timestamp | strict_monotonic_timestamp.
The flavas you can pick from when profiling the system. Pick your poison. 💅
💖 term()
term() :: any().
All possible Erlang terms. Yes, all of them. It's literally just a synonym for any/0. Main character energy. 👑
✨ time_unit()
time_unit() ::
pos_integer() |
second | millisecond | microsecond | nanosecond | native |
perf_counter |
deprecated_time_unit().
The time unit used by the erlang time APIs. Okay so here are all the supported ways to represent a time unit, and I need you to focus bestie because there's a lot:
PartsPerSecond :: integer() >= 1 Time unit expressed in parts per second. That is, the time unit equals 1/PartsPerSecond second.
second Symbolic representation of the time unit represented by the integer 1.
millisecond Symbolic representation of the time unit represented by the integer 1000.
microsecond Symbolic representation of the time unit represented by the integer 1000_000.
nanosecond Symbolic representation of the time unit represented by the integer 1000_000_000.
native Symbolic representation of the native time unit used by the Erlang runtime system.
The native time unit is determined when the runtime system starts, and it stays the same until the runtime system terminates. But — and this is the messy part — if a runtime system is stopped and then started again (even on the exact same machine), the native time unit of the new runtime system instance can differ from the old one. 🙃
You can get an approximation of the native time unit by calling erlang:convert_time_unit(1, second, native). The result equals the number of whole native time units per second. If the number of native time units per second doesn't add up to a whole number, the result gets rounded downwards.
NOTE: The value of the native time unit gives you more or less no information about the quality of time values. It sets a limit for the resolution and for the precision of time values, but it tells you nothing about the accuracy of time values. The resolution of the native time unit and the resolution of time values can differ significantly. So don't come for me with "but the unit is tiny" — that is not the same thing, bestie. 💀
perf_counter Symbolic representation of the performance counter time unit used by the Erlang runtime system.
The perf_counter time unit behaves much in the same way as the native time unit. That is, it can differ between runtime restarts. To get values of this type, call os:perf_counter/0.
deprecated_time_unit/0 Deprecated symbolic representations kept for backwards-compatibility.
And one last thing: the time_unit/0 type can be extended. To convert time values between time units, use erlang:convert_time_unit/3.
🎀 timeout()
timeout() :: infinity | non_neg_integer().
A timeout value that you can pass to a receive expression. infinity means you're waiting forever (romantic), or give it a number. ⏳
🌸 timestamp()
timestamp() ::
{MegaSecs :: non_neg_integer(),
Secs :: non_neg_integer(),
MicroSecs :: non_neg_integer()}.
See erlang:timestamp/0 for the whole story. 🕰️
🦋 trace_flag()
trace_flag() ::
all | send | 'receive' | procs | ports | call | arity |
return_to | silent | running | exiting | running_procs |
running_ports | garbage_collection | timestamp |
cpu_timestamp | monotonic_timestamp |
strict_monotonic_timestamp | set_on_spawn |
set_on_first_spawn | set_on_link | set_on_first_link |
{tracer, pid() | port()} |
{tracer, module(), term()}.
Every flag you can flick when you're tracing. So many switches, so little time. 🔥
🍓 trace_info_flag()
trace_info_flag() ::
send | 'receive' | set_on_spawn | call | return_to | procs |
set_on_first_spawn | set_on_link | running |
garbage_collection | timestamp | monotonic_timestamp |
strict_monotonic_timestamp | arity.
The subset of flags that trace_info cares about. Keep these in your notes bestie. 📝
trace_info_item_result() ::
{traced, global | local | false | undefined} |
{match_spec, trace_match_spec() | false | undefined} |
{meta, pid() | port() | false | undefined | []} |
{meta, module(), term()} |
{meta_match_spec, trace_match_spec() | false | undefined} |
{call_count, non_neg_integer() | boolean() | undefined} |
{call_time | call_memory,
[{pid(),
non_neg_integer(),
non_neg_integer(),
non_neg_integer()}] |
boolean() |
undefined}.
okay so this one is the "what did I actually get back" shape for one single trace-info item 💅 it's a union of tagged tuples, one per thing you might have asked about.
trace_info_return() ::
undefined |
{flags, [trace_info_flag()]} |
{tracer, pid() | port() | []} |
{tracer, module(), term()} |
trace_info_item_result() |
{all, [trace_info_item_result()] | false | undefined}.
the full return of a trace_info call, bestie — either nothing, or your flags, or your tracer, or one item, or literally everything wrapped in an {all, ...} 💖
trace_match_spec() ::
[{[term()] | '_' | match_variable(), [term()], [term()]}].
match specs but for tracing. iconic little triplets: head, conditions, body. periodt ✨
trace_pattern_flag() ::
global | local | meta |
{meta, Pid :: pid()} |
{meta, TracerModule :: module(), TracerState :: term()} |
call_count | call_time | call_memory.
the flags you can pass when you're setting up trace patterns 🌸
trace_pattern_mfa() :: {atom(), atom(), arity() | '_'} | on_load.
either a {Module, Function, Arity} (and yeah, '_' is allowed for the arity, she's flexible like that) or the atom on_load 💫
tuple() :: tuple().
An Erlang tuple. yes it's just a tuple, we love a self-describing type definition, no notes 💀
✨ FUNCTIONS ✨
abs
abs(Float) -> float() when Float :: float();
(Int) -> non_neg_integer() when Int :: integer().
hands you back the absolute value of Float or Int — as an integer or a float, matching what you gave her 🫶
Examples
1> abs(-3.33).
3.33
2> abs(-3).
3
3> abs(5).
5
adler32(Data)
adler32(Data) -> non_neg_integer() when Data :: iodata().
computes and returns the adler32 checksum for Data. that's it, that's the whole vibe 🔥
Examples
1> Data = ~"abc".
2> erlang:adler32(Data).
38600999
adler32(OldAdler, Data)
adler32(OldAdler, Data) -> non_neg_integer()
when OldAdler :: non_neg_integer(), Data :: iodata().
keeps the checksum train rolling 🚂 — it continues computing the adler32 checksum by combining the previous checksum, OldAdler, with the checksum of Data.
this code:
1> Data1 = ~"abc", Data2 = ~"def".
2> X = erlang:adler32(Data1).
38600999
3> Y = erlang:adler32(X,Data2).
136184406
assigns the same value to Y as this:
1> Data1 = ~"abc", Data2 = ~"def".
2> Y = erlang:adler32([Data1,Data2]).
136184406
yes bestie, same number, different route, both slay 💅
adler32_combine(FirstAdler, SecondAdler, SecondSize)
adler32_combine(FirstAdler, SecondAdler, SecondSize) ->
non_neg_integer()
when
FirstAdler :: non_neg_integer(),
SecondAdler :: non_neg_integer(),
SecondSize :: non_neg_integer().
combines two previously computed adler32 checksums into one 🎀
this computation requires the size of the data object for the second checksum to be known — so yeah, you gotta bring SecondSize along, no skipping it.
the following code:
1> Data1 = ~"abc", Data2 = ~"def".
2> X = erlang:adler32(Data1).
38600999
3> Z = erlang:adler32(X,Data2).
136184406
assigns the same value to Z as this:
1> Data1 = ~"abc", Data2 = ~"def".
2> X = erlang:adler32(Data1).
38600999
3> Y = erlang:adler32(Data2).
39780656
4> Z = erlang:adler32_combine(X,Y,iolist_size(Data2)).
136184406
alias(Opts)
alias(Opts) -> Alias
when
Alias :: reference(),
Opts :: [explicit_unalias | reply | priority].
creates an alias you can use when sending messages to the process that created the alias 💖 once the alias has been deactivated, messages sent using the alias get dropped. absolutely ghosted. you can deactivate an alias with unalias/1.
currently available options for alias/1:
explicit_unalias— the alias can only be deactivated via a call tounalias/1. this is also the default behaviour if you pass no options at all, or ifalias/0is called. no sneaky auto-off, you're in charge 👑reply— the alias gets automatically deactivated when a reply message sent via the alias is received. you can still also deactivate it via a call tounalias/1— both paths work.priority— Since OTP 28.0 — the alias can be used for sending priority messages to the process that created this alias. an alias created with this option is also known as a priority process alias, or shorter, a priority alias.
WARNING: you very seldom need to resort to using priority messages and you may cause issues instead of solving issues if not used with care. fr fr, be careful with this one 😭
for more information see, the Enabling Priority Message Reception section of the Erlang Reference Manual.
Example
server() ->
receive
{request, AliasReqId, Request} ->
Result = perform_request(Request),
AliasReqId ! {reply, AliasReqId, Result}
end,
server().
client(ServerPid, Request) ->
AliasReqId = alias([reply]),
ServerPid ! {request, AliasReqId, Request},
%% Alias will be automatically deactivated if we receive a reply
%% since we used the 'reply' option...
receive
{reply, AliasReqId, Result} -> Result
after 5000 ->
unalias(AliasReqId),
%% Flush message queue in case the reply arrived
%% just before the alias was deactivated...
receive {reply, AliasReqId, Result} -> Result
after 0 -> exit(timeout)
end
end.
note that both the server and the client in this example must be executing on at least OTP 24 systems in order for this to work 👀
for more information on process aliases see the Process Aliases section of the Erlang Reference Manual.
append_element(Tuple1, Term)
append_element(Tuple1, Term) -> Tuple2
when
Tuple1 :: tuple(),
Tuple2 :: tuple(),
Term :: term().
returns a shiny new tuple that has one element more than Tuple1, and contains the elements in Tuple1 followed by Term as the last element 🦋
semantically equivalent to list_to_tuple(tuple_to_list(Tuple1) ++ [Term]), but faster. same energy, more speed ✨
Examples
1> erlang:append_element({one, two}, three).
{one,two,three}
apply(Fun, Args)
apply(Fun, Args) -> term()
when Fun :: function(), Args :: [term()].
calls a fun, passing the elements in Args as arguments 💫
if the number of elements in the arguments are known at compile time, the call is better written as Fun(Arg1, Arg2, ... ArgN) — like, just call it normally bestie.
WARNING: earlier,Funcould also be specified as{Module, Function}, equivalent toapply(Module, Function, Args). this use is deprecated and will stop working in a future release. don't do it. it's giving legacy 💀
apply(Module, Function, Args)
apply(Module, Function, Args) -> term()
when
Module :: module(),
Function :: atom(),
Args :: [term()].
returns the result of applying Function in Module to Args. the applied function must be exported from Module. the arity of the function is the length of Args. simple math 💅
for example:
1> apply(lists, reverse, [[a, b, c]]).
[c,b,a]
2> apply(erlang, atom_to_list, ['Erlang']).
"Erlang"
if the number of arguments are known at compile time, the call is better written as Module:Function(Arg1, Arg2, ..., ArgN).
Failure: error_handler:undefined_function/3 is called if the applied function is not exported. the error handler can be redefined (see process_flag/2). if error_handler is undefined, or if the user has redefined the default error_handler so the replacement module is undefined, an error with reason undef is generated. so basically: no function, no mercy 😭
atom_to_binary(Atom, Encoding)
atom_to_binary(Atom, Encoding) -> binary()
when
Atom :: atom(),
Encoding :: latin1 | unicode | utf8.
returns a binary corresponding to the text representation of Atom 🌈
if Encoding is latin1, each character in the text representation is stored as a single byte. if Encoding is utf8 or unicode, the characters are encoded using UTF-8, where some characters may require multiple bytes. multi-byte girlies, we see you 🧚
CHANGE: as from Erlang/OTP 20, atoms can contain any Unicode character and atom_to_binary(Atom, latin1) may fail if the text representation for Atom contains a Unicode character > 255. yeah, latin1 can't hold the whole alphabet anymore, she tried her best 🙈
Examples
1> atom_to_binary('Erlang', latin1).
<<"Erlang">>
2> atom_to_binary('π', unicode).
<<207,128>>
3> atom_to_binary('π', latin1).
** exception error: bad argument
in function atom_to_binary/2
called as atom_to_binary('π',latin1)
*** argument 1: contains a character not expressible in latin1
atom_to_list(Atom)
atom_to_list(Atom) -> string() when Atom :: atom().
returns a list of unicode code points corresponding to the text representation of Atom 💜
see the unicode module for instructions on converting the resulting list into different formats — she hands you the code points, the unicode module does the glow-up ✨
Examples
1> atom_to_list('Erlang').
"Erlang"
2> atom_to_list('π').
[960]
3> atom_to_list('你好').
[20320,22909]
binary_part(Subject, Start, Length)
binary_part(Subject, Start, Length) -> binary()
when
Subject :: binary(),
Start :: non_neg_integer(),
Length :: integer().
extracts the part of the binary described by Start and Length 🎀
a negative Length can be used to extract bytes at the end of a binary. cute little trick for reading from the back, iykyk 💅
Start is zero-based. count from zero, not from one, bestie.
Failure: badarg if Start and Length in any way reference outside the binary. step outside the binary and she will throw hands 🚫
for details about the semantics of Start and Length, see binary:part/3.
Examples for binary_part/3 ✨
1> Bin = <<1,2,3,4,5,6,7,8,9,10>>.
2> binary_part(Bin, 0, 2).
<<1,2>>
3> binary_part(Bin, 2, 3).
<<3,4,5>>
4> binary_part(Bin, byte_size(Bin), -5).
<<6,7,8,9,10>>
binary_to_atom(Binary, Encoding) -> atom()
when
Binary :: binary(),
Encoding :: latin1 | unicode | utf8.
okay bestie so this one hands you back the atom whose text representation is Binary — and if that atom doesn't exist yet, it straight up creates a new one for you. 💅
If Encoding is utf8 or unicode, then the binary has to contain valid UTF-8 sequences, no exceptions.
NOTE: once an atom is created, it cannot be deleted. Like, ever. The Erlang system has a configurable limit on how many atoms can exist, so to avoid slamming into that ceiling, pls consider whetherbinary_to_existing_atom/2is a better choice thanbinary_to_atom/2. Also the number of characters permitted in an atom name is limited. 👑
CHANGE: as from Erlang/OTP 20,binary_to_atom(Binary, utf8)is capable of decoding any Unicode character. Earlier versions would just fail if the binary contained Unicode characters> 255. glow-up fr fr 🌈
Examples
1> binary_to_atom(<<"Erlang">>, latin1).
2> binary_to_atom(<<960/utf8>>, utf8).
binary_to_existing_atom(Binary, Encoding) -> atom()
when
Binary :: binary(),
Encoding :: latin1 | unicode | utf8.
Returns the atom whose text representation is Binary — provided that such atom already exists. yes queen, it will NOT make a new one for you. 🚫
The Erlang system has a configurable limit for the total number of atoms that can exist, and once an atom is created it cannot be deleted. So it is not safe to create many atoms from binaries that come from an untrusted source (for example a file fetched from the Internet) — like, say, by using binary_to_atom/2. That's exactly why this function is the appropriate option when your input binary comes from an untrusted source. 🛡️
An atom exists in an Erlang system when it's included in a loaded Erlang module or when it was created programmatically (for example by binary_to_atom/2). See the next note for an example of when an atom exists in the source code for an Erlang module but not in the compiled version of that same module. tricky!!
Failure: badarg if the atom does not exist.
NOTE: the compiler may optimize atoms away. For example, the compiler will rewriteatom_to_list(some_atom)to"some_atom". If that expression is the only mention of the atomsome_atomin the containing module, the atom will not be created when the module is loaded, and a subsequent call tobinary_to_existing_atom(<<"some_atom">>, utf8)will fail. 💀 the compiler really said "never met her".
NOTE: the number of characters that are permitted in an atom name is limited. The default limits can be found in the Efficiency Guide (section System Limits).
Examples
1> binary_to_existing_atom(~"definitely_not_existing_at_all", utf8).
** exception error: bad argument
in function binary_to_existing_atom/2
called as binary_to_existing_atom(<<"definitely_not_existing_at_all">>,utf8)
*** argument 1: not an already existing atom
2> hello.
hello
3> binary_to_existing_atom(~"hello", utf8).
hello
binary_to_float(Binary) -> float()
when Binary :: binary().
Returns the float whose text representation is Binary. 🍓
The float string format is the same as the format for Erlang float literals, except that underscores are not permitted. sorry bestie, 1_0.0 is not the vibe here.
Failure: badarg if Binary contains an invalid representation of a float.
Examples
1> binary_to_float(~"10.5").
10.5
2> binary_to_float(~"17.0").
17.0
3> binary_to_float(<<"2.2017764e+1">>).
22.017764
binary_to_integer(Binary) -> integer()
when Binary :: binary().
Returns an integer whose text representation is Binary.
binary_to_integer/1 accepts the same string formats as list_to_integer/1. same energy, different container. 💖
Failure: badarg if Binary contains an invalid representation of an integer.
Examples
1> binary_to_integer(<<"123">>).
123
2> binary_to_integer(<<"-99">>).
-99
3> binary_to_integer(<<"+33">>).
33
binary_to_integer(Binary, Base) -> integer()
when Binary :: binary(), Base :: 2..36.
Returns an integer whose text representation in base Base is Binary. base 36 go brrr 🔥
Example
1> binary_to_integer(<<"3FF">>, 16).
1023
2> binary_to_integer(<<"101">>, 2).
5
binary_to_integer/2 accepts the same string formats as list_to_integer/2.
Failure: badarg if Binary contains a invalid representation of an integer.
binary_to_list(Binary) -> [byte()]
when Binary :: binary().
Returns a list of integers corresponding to the bytes of Binary. simple. iconic. 💅
Examples
1> binary_to_list(<<1,2,3>>).
[1,2,3]
binary_to_list(Binary, Start, Stop) -> [byte()]
when
Binary :: binary(),
Start :: pos_integer(),
Stop :: pos_integer().
Same as binary_to_list/1, but returns a list of integers corresponding to the bytes from position Start to position Stop in Binary.
The positions in the binary are numbered starting from 1. yes, ONE. not zero. 🫠
NOTE: the one-based indexing for binaries used by this function is deprecated. New code should usebinary:bin_to_list/3. All functions in modulebinaryconsistently use zero-based indexing. so like... this one's giving heritage, not future. deprecated bestie, don't start anything new with it.
Examples
1> binary_to_list(~"abcdef", 2, 3).
"bc"
binary_to_term(Binary) -> term()
when Binary :: ext_binary().
Returns an Erlang term that is the result of decoding binary object Binary, which must be encoded according to the Erlang external term format. it's the un-squish. 🦋
WARNING: when decoding binaries from untrusted sources, the untrusted source may submit data in a way to create resources, such as atoms and remote references, that cannot be garbage collected and lead to a Denial of Service (DoS) attack. In such cases, usebinary_to_term/2with thesafeoption. seriously bestie, do not raw-dog untrusted binaries. 😭
Examples
1> Bin = term_to_binary(hello).
<<131,119,5,104,101,108,108,111>>
2> hello = binary_to_term(Bin).
hello
See also term_to_binary/1 and binary_to_term/2.
binary_to_term(Binary, Opts) -> term() | {term(), Used}
when
Binary :: ext_binary(),
Opt :: safe | used,
Opts :: [Opt],
Used :: pos_integer().
Equivalent to binary_to_term(Binary), but can be configured to fit special purposes. it's the same girl with options. ✨
The allowed options are:
safe— use this option when receiving binaries from an untrusted source.
When enabled, it prevents decoding data that can be used to attack the Erlang runtime. In the event of receiving unsafe data, decoding fails with a badarg error.
The safe option prevents direct and indirect creation of new atoms (such as those embedded in certain structures like process identifiers) and creation of new external function references. None of these resources are garbage collected, so unchecked creation can exhaust available memory.
WARNING: the safe option ensures data is safely processed by the Erlang runtime, but it does not guarantee that the data is safe for your application. Always validate data from untrusted sources. If a binary is stored or transmitted through untrusted sources, consider cryptographically signing it. 🔐
Examples
1> Bin = <<131,119,8,"tjenixen">>.
2> binary_to_term(Bin, [safe]).
** exception error: bad argument
in function binary_to_term/2
called as binary_to_term(<<131,119,8,116,106,101,110,105,120,101,110>>,[safe])
*** argument 1: invalid or unsafe external representation of a term
3> tjenixen.
tjenixen
4> binary_to_term(Bin, [safe]).
tjenixen
used— changes the return value to{Term, Used}whereUsedis the number of bytes actually read fromBinary. 📏
Examples
1> Input = <<(term_to_binary(hello))/binary, "world">>.
<<131,119,5,104,101,108,108,111,119,111,114,108,100>>
2> {Term, Used} = binary_to_term(Input, [used]).
{hello, 8}
3> split_binary(Input, Used).
{<<131,119,5,104,101,108,108,111>>, <<"world">>}
Failure: badarg if safe is specified and unsafe data is decoded.
See also term_to_binary/1, binary_to_term/1, and list_to_existing_atom/1.
bit_size(Bitstring) -> non_neg_integer()
when Bitstring :: bitstring().
Returns an integer that is the size in bits of Bitstring. not bytes, bits. iykyk 🧚
Examples
1> bit_size(<<433:16,3:3>>).
19
2> bit_size(<<1,2,3>>).
24
bitstring_to_list(Bitstring) -> [byte() | bitstring()]
when Bitstring :: bitstring().
Returns a list of integers corresponding to the bytes of Bitstring.
If the number of bits in the binary is not a multiple of 8, the last element of the list is a bitstring containing the remaining 1 to 7 bits. so the leftovers get their own little moment 💅
Examples
1> bitstring_to_list(<<433:16>>).
[1,177]
2> bitstring_to_list(<<433:16,3:3>>).
[1,177,<<3:3>>]
bump_reductions(Reductions) -> true
when Reductions :: pos_integer().
This implementation-dependent function increments the reduction counter for the calling process. 👑
In the Beam emulator, the reduction counter is normally incremented by one for each function and BIF call. A context switch is forced when the counter reaches the maximum number of reductions for a process (4000 reductions in Erlang/OTP 19.2 and later).
WARNING: this BIF can be removed in a future version of the Beam machine without prior warning. It is unlikely to be implemented in other Erlang implementations. so don't build your whole personality around it, bestie 😭
byte_size(Bitstring) -> non_neg_integer()
when Bitstring :: bitstring().
...so yeah, that integer it hands back is literally the number of bytes you need to hold Bitstring.</bold> And if the bit count isn't a clean multiple of 8? It rounds up, bestie — no partial bytes in this house. 💅
Examples
1> byte_size(<<433:16,3:3>>).
3
2> byte_size(<<1,2,3,4>>).
4
cancel_timer(TimerRef, Options) -> Result | ok
when
TimerRef :: reference(),
Async :: boolean(),
Info :: boolean(),
Option :: {async, Async} | {info, Info},
Options :: [Option],
Time :: non_neg_integer(),
Result :: Time | false.
Okay so this one cancels a timer that you made earlier with erlang:start_timer or erlang:send_after. 🌸 TimerRef is the thing that identifies your timer, and it's the exact reference that the BIF which created it handed back to you. Keep it safe, don't lose it. 🙈
Options
{async, Async}— an asynchronous request for cancellation.Asyncdefaults tofalse, which means the cancel gets done synchronously. When you setAsynctotrue, the cancel operation happens asynchronously — meaningcancel_timer()fires off an async cancellation request to the timer service that manages the timer, and then immediately returnsok. 💫{info, Info}— asks for info about theResultof the cancellation.Infodefaults totrue, which means you do get theResult. SetInfotofalseand you get told nothing about how the cancellation went. 🤫- When
Asyncisfalse: ifInfoistrue, theResultis returned byerlang:cancel_timer(). Otherwiseokis returned. - When
Asyncistrue: ifInfoistrue, a message on the form{cancel_timer, TimerRef, Result}is sent to the caller oferlang:cancel_timer()once the cancellation operation has been performed. Otherwise no message is sent.
- When
More Options may be added in the future. 👀
If Result is an integer, it's the time in milliseconds left until the canceled timer would have expired. ⏳
If Result is false, a timer matching TimerRef could not be found. That could be because the timer had already expired, or had already been canceled, or because TimerRef never corresponded to a timer in the first place. And even if the timer had expired, this doesn't tell you whether the time-out message has actually arrived at its destination yet. 😭
NOTE: The timer service that manages the timer can be co-located with a different scheduler than the scheduler your calling process is running on. If that happens, talking to the timer service takes way longer than if it were local. So if your calling process is on a critical path, and it can do other stuff while waiting for the result, or it genuinely doesn't care about the result — you want option{async, true}. If you use{async, false}, the calling process blocks until the operation has been performed. Periodt.
See also erlang:send_after/4, erlang:start_timer/4, and erlang:read_timer/2. 🫶
ceil(Number) -> integer()
when Number :: number().
Returns the smallest integer that is not less than Number. So it rounds up. ⬆️✨
See also trunc/1.
Examples
1> ceil(5.5).
6
2> ceil(-2.3).
-2
3> ceil(10.0).
10
check_old_code(Module) -> boolean()
when Module :: module().
Returns true if Module has old code, otherwise false. Iconic little vibe check for your modules. 👑
See also code.
check_process_code(Pid, Module, OptionList) -> CheckResult | async
when
Pid :: pid(),
Module :: module(),
RequestId :: term(),
Option ::
{async, RequestId} |
{allow_gc, boolean()},
OptionList :: [Option],
CheckResult :: boolean() | aborted.
Checks if the node-local process identified by Pid is executing old code for Module. 🔍
Options
{allow_gc, boolean()}— decides whether garbage collection is allowed while performing the operation. If you pass{allow_gc, false}and a garbage collection is needed to figure out the result, the operation gets aborted (see whatCheckResultsays below). Default is to allow garbage collection, i.e.{allow_gc, true}.{async, RequestId}— the functioncheck_process_code/3returns the valueasyncimmediately after the request has been sent. Once the request has been processed, the process that called this function gets a message on the form{check_process_code, RequestId, CheckResult}. 💌
If Pid equals self/0, and no async option was passed, the operation is performed right away. Otherwise a request for the operation is sent to the process identified by Pid, and it gets handled when appropriate. If no async option was passed, the caller blocks until CheckResult is available and can be returned. 😴
CheckResult tells you how the request went:
true— the process identified byPidexecutes old code forModule. That is, the current call of the process executes old code for this module, or the process has references to old code for this module, or the process contains funs that reference old code for this module.false— the process identified byPiddoes not execute old code forModule.aborted— the operation was aborted, because the process needed to be garbage collected to determine the result, and the operation was requested by passing option{allow_gc, false}.
CHANGE: Up until ERTS version 8.*, the check process code operation checked for all types of references to the old code. That is, direct references (e.g. return addresses on the process stack), indirect references (funs in process context), and references to literals in the code. As of ERTS version 9.0, the check process code operation only checks for direct references to the code. Indirect references via funs will be ignored. If such funs exist and are used after a purge of the old code, an exception will be raised upon usage (same as the case when the fun is received by the process after the purge). Literals will be taken care of (copied) at a later stage. This behavior can as of ERTS version 8.1 be enabled when building OTP, and will automatically be enabled if dirty scheduler support is enabled. 💀
See also code.
Failures:
badarg— ifPidis not a node local process identifier.badarg— ifModuleis not an atom.badarg— ifOptionListis an invalid list of options.
convert_time_unit(Time, FromUnit, ToUnit) -> ConvertedTime
when
Time :: integer(),
ConvertedTime :: integer(),
FromUnit :: time_unit(),
ToUnit :: time_unit().
Converts the Time value in time unit FromUnit into the corresponding ConvertedTime value in time unit ToUnit. The result is rounded using the floor/1 function. 🧮
WARNING: You can lose accuracy and precision when converting between time units. To minimize that loss, collect all your data at the native time unit and do the conversion on the end result. 🫶
crc32(Data) -> non_neg_integer()
when Data :: iodata().
Computes and returns the crc32 (IEEE 802.3 style) checksum for Data. ✨
Examples:
1> Data = ~"abc".
2> erlang:crc32(Data).
891568578
crc32(OldCrc, Data) -> non_neg_integer()
when OldCrc :: non_neg_integer(), Data :: iodata().
Continues computing the crc32 checksum by combining the previous checksum, OldCrc, with the checksum of Data. 🔗
The following code:
1> Data1 = ~"abc", Data2 = ~"def".
2> X = erlang:crc32(Data1).
891568578
3> Y = erlang:crc32(X,Data2).
1267612143
assigns the same value to Y as this:
1> Data1 = ~"abc", Data2 = ~"def".
2> Y = erlang:crc32([Data1,Data2]).
1267612143
crc32_combine(FirstCrc, SecondCrc, SecondSize) -> non_neg_integer()
when
FirstCrc :: non_neg_integer(),
SecondCrc :: non_neg_integer(),
SecondSize :: non_neg_integer().
Combines two previously computed crc32 checksums. 🎀
This computation requires the size of the data object for the second checksum to be known.
The following code:
1> Data1 = ~"abc", Data2 = ~"def".
2> X = erlang:crc32(Data1).
891568578
3> Y = erlang:crc32(X,Data2).
1267612143
assigns the same value to Z as this:
1> Data1 = ~"abc", Data2 = ~"def".
2> X = erlang:crc32(Data1).
891568578
3> Y = erlang:crc32(Data2).
214229345
4> Z = erlang:crc32_combine(X,Y,iolist_size(Data2)).
1267612143
date() -> Date
when Date :: calendar:date().
Returns the current date as {Year, Month, Day}. 📅
The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time. 🕰️
For example:
> date().
{1995,2,19}
bestie. this one is the packet decoder and it comes with a type spec that is genuinely a whole novel, but it slays, ok? here we go 💅
decode_packet(Type, Bin, Options) ->
{ok, Packet, Rest} |
{more, Length} |
{error, Reason}
when
Type ::
raw | 0 | 1 | 2 | 4 | asn1 | cdr |
sunrm | fcgi | tpkt | line | http |
http_bin | httph | httph_bin,
Bin :: binary(),
Options :: [Opt],
Opt ::
{packet_size, non_neg_integer()} |
{line_length, non_neg_integer()},
Packet :: binary() | HttpPacket,
Rest :: binary(),
Length :: non_neg_integer() | undefined,
Reason :: term(),
HttpPacket ::
HttpRequest | HttpResponse | HttpHeader |
http_eoh | HttpError,
HttpRequest ::
{http_request, HttpMethod, HttpUri,
HttpVersion},
HttpResponse ::
{http_response, HttpVersion,
integer(),
HttpString},
HttpHeader ::
{http_header,
integer(),
HttpField,
UnmodifiedField :: HttpString,
Value :: HttpString},
HttpError :: {http_error, HttpString},
HttpMethod ::
'OPTIONS' | 'GET' | 'HEAD' | 'POST' |
'PUT' | 'DELETE' | 'TRACE' | HttpString,
HttpUri ::
'*' |
{absoluteURI,
http | https,
Host :: HttpString,
Port :: inet:port_number() | undefined,
Path :: HttpString} |
{scheme,
Scheme :: HttpString,
HttpString} |
{abs_path, HttpString} |
HttpString,
HttpVersion ::
{Major :: non_neg_integer(),
Minor :: non_neg_integer()},
HttpField ::
'Cache-Control' | 'Connection' | 'Date' |
'Pragma' | 'Transfer-Encoding' |
'Upgrade' | 'Via' | 'Accept' |
'Accept-Charset' | 'Accept-Encoding' |
'Accept-Language' | 'Authorization' |
'From' | 'Host' | 'If-Modified-Since' |
'If-Match' | 'If-None-Match' |
'If-Range' | 'If-Unmodified-Since' |
'Max-Forwards' | 'Proxy-Authorization' |
'Range' | 'Referer' | 'User-Agent' |
'Age' | 'Location' |
'Proxy-Authenticate' | 'Public' |
'Retry-After' | 'Server' | 'Vary' |
'Warning' | 'Www-Authenticate' |
'Allow' | 'Content-Base' |
'Content-Encoding' | 'Content-Language' |
'Content-Length' | 'Content-Location' |
'Content-Md5' | 'Content-Range' |
'Content-Type' | 'Etag' | 'Expires' |
'Last-Modified' | 'Accept-Ranges' |
'Set-Cookie' | 'Set-Cookie2' |
'X-Forwarded-For' | 'Cookie' |
'Keep-Alive' | 'Proxy-Connection' |
HttpString,
HttpString :: string() | binary().
So this decodes the binary Bin according to whichever packet protocol you picked in Type. It's literally the same energy as the packet handling sockets do with the {packet,Type} option. same vibe, different entrance ✨
If Bin has a whole packet in it, congrats, you get it back with whatever's left over as {ok,Packet,Rest}. 🎀
If Bin does not have the whole packet yet, you get {more,Length} back instead. Length is either the expected total size of the packet, or undefined when the expected packet size is genuinely unknown. Then you just call decode_packet again with more data piled on. no big deal, she's patient 💖
And if the packet just does not conform to the protocol format at all? {error,Reason}. periodt.
🎀 Types 🎀
raw | 0— no packet handling whatsoever. The entire binary comes back to you, unless it's empty.1 | 2 | 4— packets are built like: a header that says how many bytes are in the packet, then exactly that many bytes. The header is one, two, or four bytes long, and the byte order is big-endian. The header gets stripped off before the packet is handed back to you. 🫶line— a packet is a line, terminated by a delimiter byte, and the default delimiter is the latin-1 newline character. That delimiter byte is included in the returned packet, unless the line got truncated according to theline_lengthoption.asn1 | cdr | sunrm | fcgi | tpkt— !!! the header is not stripped off here. iconic behaviour. the meanings of these packet types are:asn1- ASN.1 BERsunrm- Sun's RPC encodingcdr- CORBA (GIOP 1.1)fcgi- Fast CGItpkt- TPKT format [RFC1006]
http | httph | http_bin | httph_bin— the Hypertext Transfer Protocol, obviously 💅. Packets come back in the format fromHttpPacketthat we described earlier. A packet is either a request, a response, a header, or an end-of-header mark. Invalid lines come back asHttpError.
Recognized request methods and header fields come back as atoms. Everything else comes back as strings. Strings of unrecognized header fields get formatted with only capital letters at the start and after hyphen characters — like "Sec-Websocket-Key". Header field names are also returned in UnmodifiedField as strings, with zero conversion or formatting, untouched. ✨
The protocol type http is only for that first line, when you're expecting an HttpRequest or an HttpResponse. After that, your following calls use httph to get HttpHeaders, until http_eoh shows up — which marks the end of the headers and the beginning of whatever message body follows. 🦋
The variants http_bin and httph_bin return strings (HttpString) as binaries instead of lists.
Since OTP 26.0, Host may be an IPv6 address enclosed in [], as defined in RFC2732 .
💖 Options 💖
{packet_size, integer() >= 0}— sets the maximum allowed size of the packet body. If the packet header says the packet length is longer than that max, the packet is considered invalid. Defaults to0, which means no size limit at all, go wild 🌈{line_length, integer() >= 0}— for packet typeline, lines longer than the indicated length get truncated.
Option line_length also applies to http* packet types as an alias for option packet_size, but only if packet_size itself isn't set. this use is only intended for backward compatibility — iykyk.
{line_delimiter, 0 =< byte() =< 255}— for packet typeline, sets the delimiting byte. Default is the latin-1 character$\n.
✨ Examples ✨
1> erlang:decode_packet(1, <<3,"abcd">>, []).
{ok,<<"abc">>,<<"d">>}
2> erlang:decode_packet(1, <<5,"abcd">>, []).
{more,6}
delete_element(Index, Tuple1) -> Tuple2
when
Index :: pos_integer(),
Tuple1 :: tuple(),
Tuple2 :: tuple().
Returns a brand new tuple with the element at Index removed from tuple Tuple1. bye bestie 👋 she's gone, she's not coming back
✨ Examples ✨
1> erlang:delete_element(2, {one, two, three}).
{one,three}
delete_module(Module) -> true | undefined when Module :: module().
Makes the current code for Module become old code, and deletes every reference to this module from the export table. Returns undefined if the module doesn't exist — otherwise true.
WARNING: This BIF is intended for the code server (see code) and is not to be used elsewhere. for real, this is not your function to be playing with 🙈
Failure: badarg if there already is an old version of Module.
demonitor(MonitorRef) -> true when MonitorRef :: reference().
If MonitorRef is a reference that the calling process got from calling monitor/2, this monitoring gets turned off. And if the monitoring is already turned off, nothing happens. no drama, no error 💅
Once demonitor(MonitorRef) has returned, it is guaranteed that no {'DOWN', MonitorRef, _, _, _} message, for that monitor, will land in the caller's message queue in the future. ok but here's the thing 👑 — a {'DOWN', MonitorRef, _, _, _} message could already have been placed in the caller's message queue before the call happened. So it's usually advisable to remove such a 'DOWN' message from the message queue after you've stopped monitoring. And if you want that cleanup handled for you, demonitor(MonitorRef, [flush]) can be used instead of demonitor(MonitorRef). slay, built-in tidy-up 🧚
NOTE: For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.
okay so this is a CHANGE note, meaning the old behaviour was kinda messy and the new one is the glow-up ✨
Before Erlang/OTP R11B (ERTS 5.5) demonitor/1 behaved completely asynchronously, like, it literally just yeeted the signal and moved on. So the monitor stayed active until that "demonitor signal" actually reached the monitored entity. And bestie, that had one truly undesirable side effect: you could never know for sure when you were guaranteed to not get a DOWN message from that monitor. <emotion>😭</emotion> The current behaviour is basically two moves stacked together: asynchronously send a "demonitor signal" to the monitored entity, and ignore any future results of the monitor. periodt.
Failure: it is an error if MonitorRef refers to a monitoring started by another process. And not all such cases are cheap to check, ngl. If the checking is cheap, the call fails with badarg — for example if MonitorRef is a remote reference.
demonitor(MonitorRef, OptionList) -> boolean()
demonitor(MonitorRef, OptionList) -> boolean()
when
MonitorRef :: reference(),
OptionList :: [Option],
Option :: flush | info.
The returned value is true unless info is part of OptionList. Simple as that 💅
demonitor(MonitorRef, []) is equivalent to demonitor(MonitorRef).
Options — the little extras:
flush— removes (one){_, MonitorRef, _, _, _}message, if there is one, from the caller message queue after monitoring has been stopped.
Calling demonitor(MonitorRef, [flush]) is equivalent to the following, but more efficient:
demonitor(MonitorRef),
receive
{_, MonitorRef, _, _, _} ->
true
after 0 ->
true
end
info— the returned value is one of the following:true— the monitor was found and removed. In this case, no'DOWN'message corresponding to this monitor has been delivered and will not be delivered. 🎀false— the monitor was not found and could not be removed. This probably because someone already has placed a'DOWN'message corresponding to this monitor in the caller message queue.
If option info is combined with option flush, false is returned if a flush was needed, otherwise true.
CHANGE: more options can be added in a future release. (so don't get too attached to this list, bestie)
Failures:
badarg— ifOptionListis not a list.badarg— ifOptionis an invalid option.badarg— the same failure as fordemonitor/1.
disconnect_node(Node) -> boolean() | ignored
disconnect_node(Node) -> boolean() | ignored when Node :: node().
Forces the disconnection of a node. Just, like, ripping the cord out 🔌
Doing this makes it appear to the node Node as if the local node has crashed. This BIF is mainly used in the Erlang network authentication protocols.
Returns true if disconnection succeeds, otherwise false. If the local node is not alive, ignored is returned.
NOTE: this function may return before nodedown messages have been delivered. So don't go thinking everything's settled the second it returns, okay? 🙈
display(Term) -> true
display(Term) -> true when Term :: term().
Prints a text representation of Term on the standard output. ✨
WARNING: this BIF is intended for debugging only. The printed representation may contain internal details that do not match the high-level representation of the term in Erlang. So like, it's giving backstage access, not the polished cover version 👑
dist_ctrl_get_data(DHandle) -> {Size, Data} | Data | none
dist_ctrl_get_data(DHandle) -> {Size, Data} | Data | none
when
Size :: non_neg_integer(),
DHandle :: dist_handle(),
Data :: iovec().
Get distribution channel data from the local node that is to be passed to the remote node. 📦
The distribution channel is identified by DHandle. If no data is available, the atom none is returned. You can request to be informed by a message when more data is available by calling erlang:dist_ctrl_get_data_notification(DHandle).
The returned value when there are data available depends on the value of the get_size option configured on the distribution channel identified by DHandle. For more information see the documentation of the get_size option for the erlang:dist_ctrl_set_opt/3 function.
NOTE: only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function.
This function is used when implementing an alternative distribution carrier using processes as distribution controllers. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module. 🦋
dist_ctrl_get_data_notification(DHandle) -> ok
dist_ctrl_get_data_notification(DHandle) -> ok
when DHandle :: dist_handle().
Request notification when more data is available to fetch using erlang:dist_ctrl_get_data(DHandle) for the distribution channel identified by DHandle. It's basically "bestie, text me when you're free" 💌
When more data is present, the caller will be sent the message dist_data. Once a dist_data message has been sent, no more dist_data messages will be sent until the dist_ctrl_get_data_notification/1 function has been called again. One ping, one notification, no spam 🔔
NOTE: only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function.
This function is used when implementing an alternative distribution carrier using processes as distribution controllers. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module.
dist_ctrl_get_opt(DHandle, get_size) -> Value
dist_ctrl_get_opt(DHandle, get_size) -> Value
when
DHandle :: dist_handle(),
Value :: boolean().
Returns the value of the get_size option on the distribution channel identified by DHandle. For more information see the documentation of the get_size option for the erlang:dist_ctrl_set_opt/3 function.
NOTE: only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function.
This function is used when implementing an alternative distribution carrier using processes as distribution controllers. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module. 🌸
dist_ctrl_input_handler(DHandle, InputHandler) -> ok
dist_ctrl_input_handler(DHandle, InputHandler) -> ok
when
DHandle :: dist_handle(),
InputHandler :: pid().
Register an alternate input handler process for the distribution channel identified by DHandle. 👑 (it's giving "you're the main character now")
Once this function has been called, InputHandler is the only process allowed to call erlang:dist_ctrl_put_data(DHandle, Data) with the DHandle identifying this distribution channel.
NOTE: when the distribution controller for the distribution channel identified byDHandleis a process, it is the only process allowed to call this function. This function is also allowed to be called when the distribution controller for the distribution channel identified byDHandleis a port. The data received by the port should in this case be delivered to the process identified byInputHandler, which in turn should callerlang:dist_ctrl_put_data/2.
This function is used when implementing an alternative distribution carrier. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module.
dist_ctrl_put_data(DHandle, Data) -> ok
dist_ctrl_put_data(DHandle, Data) -> ok
when
DHandle :: dist_handle(),
Data :: iodata().
Deliver distribution channel data from a remote node to the local node. 📬
NOTE: only the process registered as distribution controller for the distribution channel identified byDHandleis allowed to call this function unless an alternate input handler process has been registered usingerlang:dist_ctrl_input_handler(DHandle, InputHandler). If an alternate input handler has been registered, only the registered input handler process is allowed to call this function.
This function is used when implementing an alternative distribution carrier. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module.
dist_ctrl_set_opt(DHandle, get_size, Value) -> OldValue
dist_ctrl_set_opt(DHandle, get_size, Value) -> OldValue
when
DHandle :: dist_handle(),
Value :: boolean(),
OldValue :: boolean().
Sets the value of the get_size option on the distribution channel identified by DHandle. 🎀
This option controls the return value of calls to erlang:dist_ctrl_get_data(DHandle) where DHandle equals the DHandle used when setting this option. When the get_size option is:
false— and there are distribution data available, a call toerlang:dist_ctrl_get_data(DHandle)will just returnDatato pass over the channel. This is the default value of theget_sizeoption.true— and there are distribution data available, a call toerlang:dist_ctrl_get_data(DHandle)will returnDatato pass over the channel as well as theSizeofDatain bytes. This is returned as a tuple of the form{Size, Data}. 🔥
All options are set to default when a channel is closed. 🌈
NOTE: Only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function.
So like… this one is for when you're out here building your own alternative distribution carrier, using processes as distribution controllers. You get DHandle handed to you from the callback f_handshake_complete — cute, right? More deets live in the docs under ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module. Go read it bestie, it's giving homework but it's important homework. 📚
💅 element(N, Tuple) -> term()
element(N, Tuple) -> term()
when N :: pos_integer(), Tuple :: tuple().
Hands you back the *N*th element of Tuple, and yes we start counting at 1 because that's just how we do it here. No zero-indexing, not today. 🙅♀️
Examples
1> element(2, {a, b, c}).
b
🧽 erase() -> [{Key, Val}]
erase() -> [{Key, Val}] when Key :: term(), Val :: term().
Returns the entire process dictionary and then deletes it. Like, nukes the whole thing. Gone. Not a single key survives. 💀
For example:
1> put(key1, {1, 2, 3}).
2> put(key2, [a, b, c]).
3> lists:sort(erase()).
[{key1,{1,2,3}},{key2,[a,b,c]}]
🗑️ erase(Key) -> Val | undefined
erase(Key) -> Val | undefined when Key :: term(), Val :: term().
Returns the value Val that's tied to Key, and then yeets that key out of the process dictionary. If nothing was vibing with that Key, you get undefined back. 🤷♀️
Okay so performance tea: the average time complexity for the current implementation of this function is O(1) and the worst case time complexity is O(N), where N is the number of items in the process dictionary. Slay.
For example:
1> put(key1, {merry, lambs, are, playing}).
2> X = erase(key1).
{merry,lambs,are,playing}
3> erase(key1).
undefined
💥 error(Reason) -> no_return()
error(Reason) -> no_return() when Reason :: term().
Raises an exception of class error with the reason Reason. ✨
Since evaluating this function throws an exception, it has no return value. Like, it never comes back. It said "I don't do returns, I do drama." 🎭
The whole point of the exception class error is to signal that something unexpected happened — for example, some function got called with a parameter that has a wrong type. See the guide about errors and error handling for additional info. Example:
1> catch error(foobar).
{'EXIT',{foobar, _StackTrace}}
💥 error(Reason, Args) -> no_return()
error(Reason, Args) -> no_return()
when Reason :: term(), Args :: [term()] | none.
Raises an exception of class error with the reason Reason. Args is expected to be the list of arguments for the current function, or the atom none.
If Args is a list, it gets used to provide the arguments for the current function in the stack back-trace. If it's none, the arity of the calling function gets used in the stacktrace instead. And since evaluating this throws an exception, it has no return value. Bye bestie, no return, only no_return. 💅
Same energy as before: the intent of the exception class error is to signal that an unexpected error has happened (for example, a function is called with a parameter that has an incorrect type). See the guide about errors and error handling for additional information.
Examples
test.erl:
-module(test).
-export([example_fun/2]).
example_fun(A1, A2) ->
erlang:error(my_error, [A1, A2]).
Erlang shell:
1> test:example_fun(arg1, "this is the second argument").
** exception error: my_error
in function test:example_fun/2
called as test:example_fun(arg1,"this is the second argument")
💥 error(Reason, Args, Options) -> no_return()
error(Reason, Args, Options) -> no_return()
when
Reason :: term(),
Args :: [term()] | none,
Options :: [Option],
Option :: {error_info, ErrorInfoMap},
ErrorInfoMap ::
#{cause => term(),
module => module(),
function => atom()}.
Raises an exception of class error with the reason Reason. Args is expected to be the list of arguments for the current function, or the atom none.
If Args is a list, it's used to provide the arguments for the current function in the stack back-trace. If it's none, the arity of the calling function is used in the stacktrace. And yeah — evaluating this raises an exception, so no return value. Ever. 🫶
Okay now the fun part: if the error_info option is given, the ErrorInfoMap gets inserted into the stacktrace. That info is meant to be used by error formatters like erl_error so they can provide more context around an error. Iconic, honestly.
The default module of the ErrorInfoMap is the module where the call to error/3 is made. The default function is format_error. See format_error/2 for more details on how this Module:Function/2 is to be used.
And once more for the people in the back: the intent of the exception class error is to signal that an unexpected error has happened (for example, a function is called with a parameter that has an incorrect type). See the guide about errors and error handling for additional information.
🚪 exit(Reason) -> no_return()
exit(Reason) -> no_return() when Reason :: term().
Raises an exception of class exit with exit reason Reason.
Since evaluating this causes an exception, it has no return value.
The whole intent behind the exception class exit is that the current process should be stopped — like when a message telling a process to stop comes in. "You're done here, queen." 👑
This function differs from error/1,2,3 in two ways: it causes an exception of a different class, and its reason does not include the list of functions from the call stack. So like, less reciepts, more exit.
See the guide about errors and error handling for additional information.
Example:
1> exit(foobar).
** exception exit: foobar
2> catch exit(foobar).
{'EXIT',foobar}
NOTE: If a process callsexit(kill)and does not catch the exception, it will terminate with exit reasonkilland also emit exit signals with exit reasonkill(notkilled) to all linked processes. Those exit signals with exit reasonkillcan be trapped by the linked processes. Which means — heads up — signals with exit reasonkillbehave differently depending on how they're sent, because the signal will be untrappable if a process sends such a signal to another process witherlang:exit_signal/2. 😭
🚪 exit(Dest, Reason) -> true
exit(Dest, Reason) -> true
when
Dest :: pid() | port() | reference(), Reason :: term().
Old form of exit_signal/2, with a quirk when sender and receiver are the same. 👀
NOTE: The functionerlang:exit/2is named similarly toerlang:exit/1but provides very different functionality. Theerlang:exit/1function should be used when the intent is to stop the current process by raising an exception of classexit. Theerlang:exit_signal/2function, or the old formerlang:exit/2, should be used when the intent is to send an exit signal to another process. Also note thaterlang:exit/1raises an exception that can be caught, whileerlang:exit_signal/2does not cause any exception to be raised.
WARNING: This function has a quirk: When a process P sends an exit signal with reasonnormalto itself using this function, that is,erlang:exit(self(), normal), the behavior is as follows: - P exits with reasonnormalif P is not trapping exits. - If P is trapping exits, the exit signal is transformed into a message{'EXIT', From, normal}, whereFromis P's process identifier, and delivered to P's message queue. Note that this differs from when a process sends an exit signal with reasonnormalto another process than itself (seeexit_signal/2for details). This behavior is kept for backward compatibility reasons. Useexit_signal/2for new code.
🚪 exit(Dest, Reason, OptList) -> true
exit(Dest, Reason, OptList) -> true
when
Dest :: pid() | port() | reference(),
Reason :: term(),
OptList :: [priority].
Deprecated form of exit_signal/3, with a quirk when sender and receiver are the same. Bestie, it's deprecated, so like… don't start anything new with it, mkay? 🙈
This allows passing options to exit/2, which preserves the behavior when a process P sends an exit signal with reason normal to itself; see exit/2 for details. For new code, use exit_signal/3.
📡 exit_signal(Pid, Reason) -> true
exit_signal(Pid, Reason) -> true
when
Pid :: pid() | port() | reference(),
Reason :: term().
Sends an exit signal with exit reason Reason to the process or port identified by Dest. If Dest is a reference, the exit signal will only affect the identified process if the reference is an active process alias of a process executing on an OTP 28.0 node or newer.
Let P be the process or port identified by Dest. The following behavior applies if Reason is any term except normal or kill:
- If P is not trapping exits, P exits with exit reason
Reason. - If P is trapping exits, the exit signal is transformed into a message
{'EXIT', From, Reason}, whereFromis the process identifier of the process that sent the exit signal, and delivered to the message queue of P.
The following behavior applies if Reason is the term normal:
- The signal has no effect if P is not trapping exits.
- If P is trapping exits, the exit signal is transformed into a message
{'EXIT', From, normal}, whereFromis the process identifier of the process that sent the exit signal, and delivered to P's message queue.
If Reason is the atom kill — that is, if exit(Dest, kill) is called — an untrappable exit signal is sent to the process identified by Dest, which unconditionally exits with exit reason killed. The exit reason is changed from kill to killed to hint to linked processes that the killed process got killed by a call to exit(Dest, kill). 💀 Periodt. There is no trapping your way out of that one.
NOTE: For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.
exit_signal(Dest, Reason, OptList) -> true— whenDest :: pid() | port() | reference(),Reason :: term(),OptList :: [priority].
Okay so this one hands you an option list so you can tweak how the exit_signal/2 BIF does its thing. The Dest and Reason args mean exactly what they mean when you pass them to exit_signal/2 — no plot twist there.
Here's what you can actually put in that list rn:
priority— since OTP 28.0
This sends the exit signal out as a priority exit signal. For the receiver to actually treat it like a priority EXIT message, three things gotta line up: you pass this option, Dest is an active priority alias, and the receiver is trapping exits.
And bestie, listen — if Dest is an active priority alias but you don't pass this option, the exit signal just gets handled like an ordinary exit signal. Same energy the other way: if you pass this option but Dest isn't an active priority alias, ordinary exit signal, no priority arc for you.
⚠️ WARNING: You very seldom need to resort to using priority messages, and you may cause issues instead of solving issues if not used with care. Like, fr fr, be careful. 💀
Wanna know more? Go read the Adding Messages to the Message Queue and the Enabling Priority Message Reception sections of the Erlang Reference Manual. iykyk 💅
external_size(Term) -> non_neg_integer()— whenTerm :: term().
So this calculates the maximum byte size for a term encoded in the Erlang external term format, and it does it without actually doing the encoding. Iconic, honestly. ✨
This condition always holds, no cap:
Size1 = byte_size(term_to_binary(Term)),
Size2 = erlang:external_size(Term),
true = Size1 =< Size2.
Examples 🌸
1> Term = {ok,"abc"}.
2> erlang:external_size(Term).
13
3> byte_size(term_to_binary(Term)).
13
external_size(Term, Options) -> non_neg_integer()— whenTerm :: term(),Options :: [compressed | {compressed, Level :: 0..9} | deterministic | {minor_version, Version :: 0..2} | local].
Same vibe as the one-arg version: max byte size for a term encoded in the Erlang external term format, calculated without doing the encoding. 🦋
And this always holds too:
Size1 = byte_size(term_to_binary(Term, Options)),
Size2 = erlang:external_size(Term, Options),
true = Size1 =< Size2.
Wanna know what the options actually do? Head to term_to_binary/2, it's all described over there. 🫶
Examples ✨
1> Term = {ok,lists:duplicate(50, $A)}.
{ok,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
2> erlang:external_size(Term, [compressed]).
60
3> byte_size(term_to_binary(Term, [compressed])).
26
float(Number) -> float()— whenNumber :: number().
Returns a float by converting Number to a float. Simple as that, slay. 💖
Examples 🎀
1> float(55).
55.0
NOTE: If you use this on the top level in a guard, it tests whether the argument is a floating point number. For clarity, useis_float/1instead — it's giving clearer bestie. Whenfloat/1is used in an expression in a guard, like'float(A) == 4.0', it converts a number as described earlier.
float_to_binary(Float, Options) -> binary()— whenFloat :: float(),Options :: [Option],Option :: {decimals, Decimals :: 0..253} | {scientific, Decimals :: 0..249} | compact | short.
Returns a binary corresponding to the text representation of Float, using fixed decimal point formatting. 💅
Options behaves in the same way as for float_to_list/2.
Examples 👑
1> float_to_binary(7.12, [{decimals, 4}]).
<<"7.1200">>
2> float_to_binary(7.12, [{decimals, 4}, compact]).
<<"7.12">>
3> float_to_binary(7.12, [{scientific, 3}]).
<<"7.120e+00">>
4> float_to_binary(7.12, [short]).
<<"7.12">>
5> float_to_binary(0.1+0.2, [short]).
<<"0.30000000000000004">>
6> float_to_binary(0.1+0.2).
<<"3.00000000000000044409e-01">>
float_to_list(Float, Options) -> string()— whenFloat :: float(),Options :: [Option],Option :: {decimals, Decimals :: 0..253} | {scientific, Decimals :: 0..249} | compact | short.
Returns a string corresponding to the text representation of Float, using fixed decimal point formatting. 🌈
Here's the options menu, bestie:
- If option
decimalsis specified, the returned value contains at mostDecimalsnumber of digits past the decimal point. If the number does not fit in the internal static buffer of 256 bytes, the function throwsbadarg. 😭 (yeah, 256 bytes, that's the limit, don't fight it) - If option
compactis specified, the trailing zeros at the end of the list are truncated. This option is only meaningful together with optiondecimals— it's giving conditional ✨ - If option
scientificis specified, the float is formatted using scientific notation withDecimalsdigits of precision. 🧚 - If option
shortis specified, the float is formatted with the smallest number of digits that still guarantees thatF =:= list_to_float(float_to_list(F, [short])). When the float is inside the range (-2⁵³, 2⁵³), the notation that yields the smallest number of characters is used (scientific notation or normal decimal notation). Floats outside the range (-2⁵³, 2⁵³) are always formatted using scientific notation to avoid confusing results when doing arithmetic operations. 💀 No confusing math for us, periodt. - If
Optionsis[], the function behaves asfloat_to_list/1. 🫶
Examples 💜
1> float_to_list(7.12, [{decimals, 4}]).
"7.1200"
2> float_to_list(7.12, [{decimals, 4}, compact]).
"7.12"
3> float_to_list(7.12, [{scientific, 3}]).
"7.120e+00"
4> float_to_list(7.12, [short]).
"7.12"
5> float_to_list(0.1+0.2, [short]).
"0.30000000000000004"
6> float_to_list(0.1+0.2).
"3.00000000000000044409e-01"
In the last example, float_to_list(0.1+0.2) evaluates to "3.00000000000000044409e-01". The reason for this is explained in Representation of Floating Point Numbers. 😌 yes, there's a whole explanation, go look.
floor(Number) -> integer()— whenNumber :: number().
Returns the largest integer not greater than Number. Basically it rounds down, bestie, no cap. 🔥
See also trunc/1.
Examples ⭐
1> floor(-10.5).
-11
2> floor(5.5).
5
3> floor(10.0).
10
fun_info(Fun) -> [{Item, Info}]— whenFun :: function(),Item :: arity | env | index | name | module | new_index | new_uniq | pid | type | uniq,Info :: term().
Returns a list with information about the fun Fun. 🎀
Every element in that list is a tuple. The order of the tuples is undefined, and more tuples can be added in a future release — so don't you dare rely on the order, bestie. 🙈
⚠️ WARNING: This BIF is intended for debugging. Library functions that need to check some property of a fun should use fun_info/2. That's the move, okay? 💅
Two types of funs have slightly different semantics:
- A fun created by
fun M:F/Ais called an external fun. Calling it will always call the functionFwith arityAin the latest code for moduleM. Notice that moduleMdoes not even need to be loaded when the funfun M:F/Ais created. Wild, right? ✨ - All other funs are called local. When a local fun is called, the same version of the code that created the fun is called (even if a newer version of the module has been loaded). It's giving loyalty, honestly. 💖
These elements are always present in the list for both local and external funs:
{type, Type}
Type is local or external.
{module, Module}
Module (an atom) is the module name.
If Fun is a local fun, Module is the module in which the fun is defined.
If Fun is an external fun, Module is the module that the fun refers to.
{name, Name}
Name (an atom) is a function name.
If Fun is a local fun, Name is the name of the local function that implements the fun. (This name was generated by the compiler, and is only of informational use. As it is a local function, it cannot be called directly.) If no code is currently loaded for the fun, [] is returned instead of an atom. 💀
If Fun is an external fun, Name is the name of the exported function that the fun refers to.
{arity, Arity}
Arity is the number of arguments that the fun is to be called with.
{env, Env}
Env (a list) is the environment or free variables for the fun. For external funs, the returned list is always empty. 🍓
And these elements are only present in the list if Fun is local:
{pid, Pid}
Pid is the process identifier of init process on the local node.
CHANGE: Starting in Erlang/OTP 27, Pid always points to the local init process, regardless of which process or node the fun was originally created on. See Upcoming Potential Incompatibilities. 👀
{index, Index}
Index (an integer) is an index into the module fun table.
{new_index, Index}
Index (an integer) is an index into the module fun table.
{new_uniq, Uniq}
Uniq (a binary) is a unique value for this fun. It is calculated from the compiled code for the entire module. 🌸
{uniq, Uniq}
Uniq (an integer) is a unique value for this fun. As from Erlang/OTP R15, this integer is calculated from the compiled code for the entire module. Before Erlang/OTP R15, this integer was based on only the body of the fun. History lesson, bestie, take notes. 📝
See also fun_info/2 and is_function/2.
fun_info(Fun, Item) -> {Item, Info}
when
Fun :: function(),
Item :: fun_info_item(),
Info :: term().
Returns info about Fun as specified by Item, in the form {Item,Info}.
For literally any fun, Item can be any of the atoms module, name, arity, env, or type.
For a local fun, Item can also be any of the atoms index, new_index, new_uniq, uniq, and pid. For an external fun, the value of any of these items is always the atom undefined. Love that for them 💅
See erlang:fun_info/1 for a description of the items.
🌸 Examples 🌸
1> erlang:fun_info(fun() -> ok end, type).
{type,local}
2> erlang:fun_info(fun lists:sum/1, type).
{type,external}
fun_to_list(Fun) -> String :: string() when Fun :: function().
Returns String that represents the code that created Fun.
String has the following form, if Fun was created by a fun expression of the form fun ModuleName:FuncName/Arity:
"fun ModuleName:FuncName/Arity"
The form of String when Fun is created from other types of fun expressions differs depending on if the fun expression was executed while executing compiled code or if the fun expression was executed while executing uncompiled code (uncompiled escripts, the Erlang shell, and other code executed by the erl_eval module):
- compiled code —
"#Fun<M.I.U>", whereM,IandUcorrespond to the values namedmodule,indexanduniqin the result oferlang:fun_info(Fun). - uncompiled code — All funs created from fun expressions in uncompiled code with the same arity are mapped to the same list by
fun_to_list/1.
NOTE: Generally, one can not usefun_to_list/1to check if two funs are equal asfun_to_list/1does not take the fun's environment into account. Seeerlang:fun_info/1for how to get the environment of a fun.
CHANGE: The output of fun_to_list/1 can differ between Erlang implementations and may change in future versions.
🌈 Examples 🌈
-module(test).
-export([add/1, add2/0, fun_tuple/0]).
add(A) -> fun(B) -> A + B end.
add2() -> fun add/1.
fun_tuple() -> {fun() -> 1 end, fun() -> 1 end}.
> {fun test:add/1, test:add2()}.
{fun test:add/1,#Fun<test.1.107738983>}
Explanation: fun test:add/1 is upgradable but test:add2() is not upgradable.
> {test:add(1), test:add(42)}.
{#Fun<test.0.107738983>,#Fun<test.0.107738983>}
Explanation: test:add(1) and test:add(42) has the same string representation as the environment is not taken into account.
> test:fun_tuple().
{#Fun<test.2.107738983>,#Fun<test.3.107738983>}
Explanation: The string representations differ because the funs come from different fun expressions.
> {fun() -> 1 end, fun() -> 1 end}.
{#Fun<erl_eval.45.97283095>,#Fun<erl_eval.45.97283095>}
Explanation: All funs created from fun expressions of this form in uncompiled code with the same arity are mapped to the same list by fun_to_list/1.
function_exported(Module, Function, Arity) -> boolean()
when
Module :: module(),
Function :: atom(),
Arity :: arity().
Returns true if the module Module is current and contains an exported function Function/Arity, or if there is a BIF (a built-in function implemented in C) with the specified name, otherwise returns false. ✨
garbage_collect() -> true.
Forces an immediate garbage collection of the executing process.
The function is not to be used unless it has been noticed (or there are good reasons to suspect) that the spontaneous garbage collection will occur too late or not at all.
WARNING: Improper use can seriously degrade system performance. 💀 Like, do not just be calling this for funsies, bestie.
garbage_collect(Pid, OptionList) -> GCResult | async
when
Pid :: pid(),
RequestId :: term(),
Option ::
{async, RequestId} |
{type, major | minor},
OptionList :: [Option],
GCResult :: boolean().
Garbage collects the node local process identified by Pid.
Option:
{async, RequestId}— The functiongarbage_collect/2returns the valueasyncimmediately after the request has been sent. When the request has been processed, the process that called this function is passed a message on the form{garbage_collect, RequestId, GCResult}.{type, 'major' | 'minor'}— Triggers garbage collection of requested type. Default value is'major', which would trigger a fullsweep GC. The option'minor'is considered a hint and may lead to either minor or major GC run.
If Pid equals self/0, and no async option has been passed, the garbage collection is performed at once, that is, the same as calling garbage_collect/0. Otherwise a request for garbage collection is sent to the process identified by Pid, and will be handled when appropriate. If no async option has been passed, the caller blocks until GCResult is available and can be returned.
GCResult informs about the result of the garbage collection request as follows:
true— The process identified byPidhas been garbage collected.false— No garbage collection was performed, as the process identified byPidterminated before the request could be satisfied.
Notice that the same caveats apply as for garbage_collect/0. 👀
Failures:
badarg— IfPidis not a node local process identifier.badarg— IfOptionListis an invalid list of options.
get() -> [{Key, Val}] when Key :: term(), Val :: term().
Returns the process dictionary as a list of {Key, Val} tuples. The items in the returned list can be in any order. 🦋
For example:
1> put(key1, merry).
2> put(key2, lambs).
3> put(key3, {are, playing}).
4> lists:sort(get()).
[{key1,merry},{key2,lambs},{key3,{are,playing}}]
5> erase().
6> get().
[]
get(Key) -> Val | undefined when Key :: term(), Val :: term().
Returns the value Val associated with Key in the process dictionary, or undefined if Key does not exist.
The expected time complexity for the current implementation of this function is O(1) and the worst case time complexity is O(N), where N is the number of items in the process dictionary. O(1) bestie, it's giving instant.
For example:
1> put(key1, merry).
2> put(key2, lambs).
3> put({any, [valid, term]}, {are, playing}).
4> get({any, [valid, term]}).
{are,playing}
5> erase().
6> get({any, [valid, term]}).
undefined
get_cookie() -> Cookie | nocookie when Cookie :: atom().
Returns the magic cookie of the local node if the node is alive, otherwise the atom nocookie. This value is set by set_cookie/1. 🍪✨
get_cookie(Node) -> Cookie | nocookie
when Node :: node(), Cookie :: atom().
Returns the magic cookie for node Node if the local node is alive, otherwise the atom nocookie. This value is set by set_cookie/2.
get_keys() -> [Key] when Key :: term().
Returns a list of all keys present in the process dictionary. The items in the returned list can be in any order.
For example:
1> put(dog, '🐶').
2> put(cow, '🐄').
3> put(lamb, '🐑').
4> lists:sort(get_keys()).
[cow,dog,lamb]
5> erase().
6> get_keys().
[]
get_keys(Val) -> [Key] when Val :: term(), Key :: term().
Returns a list of keys that are associated with the value Val in the process dictionary. The items in the returned list can be in any order. 🦕🦊
For example:
1> put(allosaurus, '🦕').
2> put(brachiosaurus, '🦕').
3> put(carnotaurus, '🦕').
4> put(diplodocus, '🦕').
5> put(euoplocephalus, '🦕').
6> put(fox, '🦊').
7> lists:sort(get_keys('🦕')).
[allosaurus,brachiosaurus,carnotaurus,diplodocus,euoplocephalus]
8> erase().
9> get_keys('🦕').
[]
group_leader() -> pid().
Returns the process identifier of the group leader for the process evaluating the function.
Every process is a member of some process group and all groups have a group leader. All I/O from the group is channeled to the group leader. When a new process is spawned, it gets the same group leader as the spawning process. It's giving ✨inherited vibes✨.
Initially, at system startup, init is both its own group leader and the group leader of all processes. During the boot of a system the group leader for processes will be changed depending on the need of the system. Some examples where this is done are:
- When an application is started, the top supervisor of that application will have its group leader set to the application master. See
application:start/2for more details. - When running tests, both
common_testandeunitset the group leader in order to capture any I/O from the testcase. - The interactive shell sets the group leader to intercept I/O.
group_leader(GroupLeader, Pid) -> true
when GroupLeader :: pid(), Pid :: pid().
Sets the group leader of Pid to GroupLeader. Typically, this is used when a process started from a certain shell is to have another group leader than init.
The group leader should be rarely changed in applications with a supervision tree, because OTP assumes the group leader of their processes is their application master. 🫶 Don't fight OTP on this one, she knows what she's doing.
Setting the group leader follows the signal ordering guarantees described in the Processes Chapter in the Erlang Reference Manual.
Also peep group_leader/0 and the OTP design principles stuff about starting and stopping applications, bestie.
NOTE: For some important info about distributed signals, go read the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual. 🫶
halt() -> no_return().
Same energy as calling halt(0, []). Slay.
Example time:
> halt().
os_prompt%
halt(Status :: non_neg_integer()) -> no_return();
halt(Abort :: abort) -> no_return();
halt(CrashDumpSlogan :: string()) -> no_return().
Equivalent to calling halt(HaltType, []).
Like, for example:
> halt(17).
os_prompt% echo $?
17
os_prompt%
halt(Status :: non_neg_integer(), Options :: halt_options()) -> no_return();
halt(Abort :: abort, Options :: halt_options()) -> no_return();
halt(CrashDumpSlogan :: string(), Options :: halt_options()) -> no_return().
Say bye to the runtime system. 👋
halt(Status :: non_neg_integer(), Options :: halt_options())
Halt the runtime system with status code Status.
NOTE: On many platforms, the OS only supports status codes 0-255. A too-large status code gets truncated by clearing the high bits. 💀
Currently the following options are valid:
{flush, EnableFlushing}IfEnableFlushingequalstrue, which is also the default behavior, the runtime system will do all of this before terminating:- Flush all outstanding output.
- Send all Erlang ports exit signals and wait for them to exit.
- Wait for all async threads to complete all outstanding async jobs.
- Call all installed NIF on halt callbacks.
- Wait for all ongoing NIF calls with the delay halt setting enabled to return.
- Call all installed
atexit/on_exitcallbacks.
If EnableFlushing equals false, the runtime system terminates immediately without doing any of the above. Not a single one. Bye. 🦋
CHANGE: Runtime systems before OTP 26.0 called all installedatexit/on_exitcallbacks even when flush was disabled, but as of OTP 26.0 that is no longer the case bestie.
{flush_timeout, Timeout :: 0..2147483647 | infinity}Sets a limit on the time allowed for flushing prior to termination of the runtime system.Timeoutis in milliseconds. The default value is determined by theerl +zhft <Timeout>command line flag.
If flushing has been ongoing for Timeout milliseconds, flushing operations will be interrupted and the runtime system will immediately be terminated with exit code 255. If flushing is not enabled, the timeout has no effect on the system.
Also see the erl +zhft <Timeout> command line flag. Heads up that the shortest timeout set by the command line flag and the flush_timeout option will be the actual timeout value in effect. Whichever one is shorter wins fr fr.
Since: OTP 27.0 ✨
halt(Abort :: abort, Options :: halt_options())
Halt the Erlang runtime system by aborting and produce a core dump if core dumping has been enabled in the environment the runtime system is executing in.
NOTE: The {flush, boolean()} option gets ignored, and flushing is disabled. 🙈
halt(CrashDumpSlogan :: string(), Options :: halt_options())
Halt the Erlang runtime system and generate an Erlang crash dump. The string CrashDumpSlogan will be used as the slogan in the Erlang crash dump created. The slogan gets truncated if CrashDumpSlogan is longer than 1023 characters.
NOTE: The {flush, boolean()} option gets ignored, and flushing is disabled. 💅
CHANGE: Behavior changes compared to earlier versions: - Before OTP 24.2, the slogan was truncated ifCrashDumpSloganwas longer than200characters. Now it gets truncated if longer than1023characters. - Before OTP 20.1, only code points in the range0-255were accepted in the slogan. Now any Unicode string is valid. Iconic glow-up. 👑
hd(List) -> Head
when List :: nonempty_maybe_improper_list(), Head :: term().
Returns the first element of List. The actual first one. The head. The main character. 🎀
It works with improper lists too, no cap.
Failure: badarg if List is the empty list [].
Examples
1> hd([1,2,3,4,5]).
1
2> hd([first, second, third, so_on | improper_end]).
first
3> hd([]).
** exception error: bad argument
in function hd/1
called as hd([])
*** argument 1: not a nonempty list
hibernate() -> ok.
Puts the calling process into a wait state where its memory allocation has been reduced as much as possible. Super useful if the process does not expect to receive any messages soon. Nap time. 😴
The process is awakened when a message is sent to it, and control resumes normally to the caller. Unlike erlang:hibernate/3, it does not discard the call stack.
hibernate(Module, Function, Args) -> no_return()
when Module :: module(), Function :: atom(), Args :: [term()].
Puts the calling process into a wait state where its memory allocation has been reduced as much as possible. Useful if the process does not expect to receive any messages soon. 🌸
The process is awakened when a message is sent to it, and control resumes in Module:Function with the arguments specified by Args with the call stack emptied, meaning that the process terminates when that function returns. So erlang:hibernate/3 never returns to its caller. The resume function Module:Function/Arity must be exported (Arity =:= length(Args)).
If the process has any message in its message queue, the process is awakened immediately in the same way as described earlier.
In more technical terms, erlang:hibernate/3 discards the call stack for the process, and then garbage collects the process. After this, all live data is in one continuous heap. The heap is then shrunken to the exact same size as the live data that it holds (even if that size is less than the minimum heap size for the process).
If the size of the live data in the process is less than the minimum heap size, the first garbage collection happening after the process is awakened ensures that the heap size is changed to a size not smaller than the minimum heap size.
Notice that emptying the call stack means that any surroundingcatchis removed and must be re-inserted after hibernation. One effect of this is that processes started usingproc_lib(also indirectly, such asgen_serverprocesses), are to useproc_lib:hibernate/3instead, to ensure that the exception handler continues to work when the process wakes up. Don't skip this one, it's a whole mood. 💜
insert_element(Index, Tuple1, Term) -> Tuple2
when Index :: pos_integer(), Tuple1 :: tuple(), Tuple2 :: tuple(), Term :: term().
Returns a new tuple with element Term inserted at position Index in tuple Tuple1.
All elements from position Index and upwards get pushed one step higher in the new tuple Tuple2. Little glow-up for your tuple. ✨
Examples
1> erlang:insert_element(2, {one, two, three}, new).
{one,new,two,three}
integer_to_binary(Integer) -> binary() when Integer :: integer().
Returns a binary corresponding to the text representation of Integer.
Examples
1> integer_to_binary(77).
<<"77">>
integer_to_binary(Integer, Base) -> binary()
when Integer :: integer(), Base :: 2..36.
Returns a binary corresponding to the text representation of Integer in base Base.
Examples
1> integer_to_binary(1023, 16).
<<"3FF">>
integer_to_list(Integer) -> string() when Integer :: integer().
Returns a string corresponding to the text representation of Integer.
Examples
1> integer_to_list(77).
"77"
integer_to_list(Integer, Base) -> string()
when Integer :: integer(), Base :: 2..36.
Returns a string corresponding to the text representation of Integer in base Base.
Examples
1> integer_to_list(1023, 16).
"3FF"
iolist_size(Item) -> non_neg_integer()
when Item :: iolist() | binary().
Returns the size in bytes of the binary that would result from iolist_to_binary(Item). Basically a sneak peek at how big it'd be. 👀
Examples
1> iolist_size([1,2|<<3,4>>]).
4
iolist_to_binary(IoListOrBinary) -> binary()
when IoListOrBinary :: iolist() | binary().
Returns a binary constructed from the integers and binaries in IoListOrBinary.
Examples
1> Bin1 = <<1,2,3>>.
<<1,2,3>>
2> Bin2 = <<4,5>>.
<<4,5>>
3> Bin3 = <<6>>.
<<6>>
4> iolist_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6>>
iolist_to_iovec(IoListOrBinary) -> iovec()
when IoListOrBinary :: iolist() | binary().
Returns an iovec that is made from the integers and binaries in IoListOrBinary.
This function is useful when you need to flatten an iolist but do not require a single binary. It can be beneficial for passing data to NIF functions such as enif_inspect_iovec or for more efficient message passing. The advantage of using this function over iolist_to_binary/1 is that it does not need to copy off-heap binaries. Efficiency queen. 👑
Examples 💅
okay so when you pass small binaries and integers, it literally behaves like iolist_to_binary/1:
1> Bin1 = <<1,2,3>>.
<<1,2,3>>
2> Bin2 = <<4,5>>.
<<4,5>>
3> Bin3 = <<6>>.
<<6>>
4> erlang:iolist_to_iovec([Bin1,1,[2,3,Bin2],4|Bin3]).
[<<1,2,3,1,2,3,4,5,4,6>>]
but bestie, once you're passing larger binaries, they get split up and handed back in a form that's optimized for calling the C function writev(). it's giving syscall efficiency ✨
1> erlang:iolist_to_iovec([<<1>>,<<2:8096>>,<<3:8096>>]).
[<<1>>,
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
...>>,
<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...>>]
is_alive() -> boolean().
returns true if the local node is alive — like, if the node can be part of a distributed system — and false otherwise. and a node counts as alive if it was started with:
"erl -name LONGNAME", or"erl -sname SHORTNAME".
a node can also be alive if it got a name from a call to net_kernel:start/2 and hasn't been stopped by a call to net_kernel:stop/0. 💖
is_atom(Term) -> boolean() when Term :: term().
returns true if Term is an atom, otherwise it returns false. no notes, it's simple, we love her 🎀
Examples
1> is_atom(42).
false
2> is_atom(ok).
true
is_binary(Term) -> boolean() when Term :: term().
returns true if Term is a binary, otherwise false.
and ngl, a binary always contains a complete number of bytes. that's the whole vibe check on that one. 🦋
Examples
1> is_binary(42).
false
2> is_binary(<<1,2,3>>).
true
3> is_binary(<<7:12>>).
false
is_bitstring(Term) -> boolean() when Term :: term().
returns true if Term is a bitstring (and yeah, that includes a binary), otherwise false. bitstrings are the main character and binaries are their very well-behaved subset. 👑
Examples
1> is_bitstring(42).
false
2> is_bitstring(<<1,2,3>>).
true
3> is_bitstring(<<7:12>>).
true
is_boolean(Term) -> boolean() when Term :: term().
returns true if Term is the atom true or false, otherwise false. like, only the actual booleans, bestie, not your random ok. 💀
Examples
1> is_boolean(true).
true
2> is_boolean(false).
true
3> is_boolean(ok).
false
4> is_boolean(42).
false
is_builtin(Module, Function, Arity) -> boolean() when Module :: module(), Function :: atom(), Arity :: arity().
this BIF is lowkey a gift to anyone building cross-reference tools. 🛠️
it returns true if Module:Function/Arity is a BIF implemented in C, otherwise false.
Examples
1> erlang:is_builtin(lists, keyfind, 3).
true
2> erlang:is_builtin(lists, reverse, 1).
false
is_float(Term) -> boolean() when Term :: term().
returns true if Term is a floating point number, otherwise false. yes, 42 is not 42.0, the decimal point is doing unpaid emotional labour. 🌸
Examples
1> is_float(42).
false
2> is_float(42.0).
true
3> is_float(zero).
false
is_function(Term) -> boolean() when Term :: term().
returns true if Term is a fun, otherwise false.
Examples
1> is_function(fun() -> ok end).
true
2> is_function(fun lists:sum/1).
true
3> is_function({lists,sum}).
false
is_function(Term, Arity) -> boolean() when Term :: term(), Arity :: arity().
returns true if Term is a fun that can be applied with Arity number of arguments, otherwise false.
watch out bestie: a bad Arity will blow up in your face with a badarg exception. this function is not here to coddle you. 😭
Examples
1> is_function(fun() -> ok end, 0).
true
2> is_function(fun lists:sum/1, 1).
true
3> is_function({lists,sum}, 1).
false
4> is_function(fun lists:sum/1, -1).
** exception error: bad argument
in function is_function/2
called as is_function(fun lists:sum/1,-1)
*** argument 2: out of range
5> is_function(fun lists:sum/1, bad_arity).
** exception error: bad argument
in function is_function/2
called as is_function(fun lists:sum/1,bad_arity)
*** argument 2: not an integer
is_integer(Term) -> boolean() when Term :: term().
returns true if Term is an integer, otherwise false. and she does not care how long that integer is, she will hold it for you. 💜
Examples
1> is_integer(1).
true
2> is_integer(-1234567890123456789012345678901234567890).
true
3> is_integer(1.0).
false
4> is_integer(zero).
false
is_integer(Term, LB, UB) -> boolean() when Term :: integer(), LB :: integer(), UB :: integer().
returns true if Term, LB, and UB all evaluate to integers, and Term is between LB and UB inclusive, otherwise false.
Failure: badarg if LB or UB does not evaluate to an integer. don't test her. 🙈
Examples
1> is_integer(15, 0, 1024).
true
2> is_integer(-1, 0, 1).
false
is_list(Term) -> boolean() when Term :: term().
returns true if Term is a list with zero or more elements, otherwise false. yes, [] counts, empty is still a list, and honestly that's very her. 🫶
Examples
1> is_list({a,b,c}).
false
2> is_list([]).
true
3> is_list([1]).
true
4> is_list([1,2]).
true
5> is_list([1,2|3]).
true
is_map(Term) -> boolean() when Term :: term().
returns true if Term is a map, otherwise false.
Examples
1> is_map(#{}).
true
2> is_map(#{key => value}).
true
3> is_map([]).
false
is_map_key(Key, Map) -> boolean() when Key :: term(), Map :: map().
returns true if the map Map contains Key, and false if it does not contain the Key. it's the "are you in the group chat" check of Erlang. 💅
Failure: a{badmap,Map}exception is raised if Map is not a map. nope,no_mapis very much not a map, and she said that loudly.
Examples
1> Map = #{"42" => value}.
#{"42" => value}
2> is_map_key("42", Map).
true
3> is_map_key(value, Map).
false
4> is_map_key(value, no_map).
** exception error: bad map: no_map
in function is_map_key/2
called as is_map_key(value,no_map)
*** argument 2: not a map
is_number(Term) -> boolean() when Term :: term().
returns true if Term is an integer or a floating point number, otherwise false. she's inclusive like that, both are welcome. 🌈
Examples
1> is_number(10.0).
true
2> is_number(7).
true
3> is_number(zero).
false
is_pid(Term) -> boolean() when Term :: term().
returns true if Term is a process identifier, otherwise false. yes, self() is a real one. ⭐
Examples
1> is_pid(self()).
true
2> is_pid(ok).
false
is_port(Term) -> boolean() when Term :: term().
returns true if Term is a port identifier, otherwise false.
Examples
1> APort = hd(erlang:ports()).
2> is_port(APort).
true
3> is_port(self()).
false
is_process_alive(Pid) -> boolean() when Pid :: pid().
Pid must refer to a process at the local node. no long-distance relationships here.
returns true if the process exists and is alive — meaning it's not exiting and hasn't exited. otherwise it returns false.
okay now the serious part, because this one's actually lowkey iconic: if process P1 calls is_process_alive(P2Pid), it is guaranteed that all signals sent from P1 to P2 (P2 is the process with identifier P2Pid) before the call will be delivered to P2 before the aliveness of P2 is checked. this guarantee means you can use is_process_alive/1 to let a process P1 wait until a process P2 — one that got an exit signal with reason kill from P1 — is killed. 🔥
for example:
1> P2Pid = spawn(fun() -> receive after infinity -> ok end end).
2> exit(P2Pid, kill).
true
% P2 might not be killed
3> is_process_alive(P2Pid).
false
% P2 is not alive (the call above always return false)
see the documentation about signals and erlang:exit_signal/2 for more info about signals and exit signals. iykyk 🧚
is_record(Term) -> boolean() when Term :: term().
returns true if Term is a native record, otherwise false. 💖
Examples
1> NR = records:create(test, native, [], #{is_exported => true}).
2> is_record(NR).
true
3> is_record(an_atom).
false
4> is_record({a,b,c}).
false
is_record(Term, Name) -> boolean() when Term :: term(), Name :: atom().
returns true if Term is either a tuple record or a native record named Name, otherwise false.
this is allowed in guard tests if Name is a literal atom.
the compilation will fail with an error message if Name doesn't refer to either a record defined in the same module as the call to is_record/2, or a native record imported into it.
if Name is a variable and Term is a native record, this function returns true if Name refers to a native record named Name in any module, otherwise it returns false.
if Name is a variable and Term is a tuple, this function returns true if the first element of the tuple is Name, otherwise it returns false.
CHANGE: Before OTP 29, this function would only work for tuple records. yeah, she got an upgrade, we're obsessed. ✨
is_record/3 💅
is_record(Term :: dynamic(), Module :: module(), Name :: atom()) ->
boolean();
(Term :: dynamic(),
Name :: atom(),
Arity :: non_neg_integer()) ->
boolean().
returns true either if Term is a native record defined in module Module with name Name, or if Term is a tuple, its first element is Name, and its size is Arity, otherwise false.
this is allowed in guard tests if either Module and Name are literal atoms, or Name is a literal atom and Size is a literal integer.
NOTE: this BIF only checks if Term is a native record created from the given module. it does not check whether Term is still defined in the given module, nor whether it is exported. so don't go assuming, bestie. 🍓
CHANGE: Before Erlang/OTP 29, this function only worked for tuple records.
is_reference(Term) -> boolean()
when Term :: term().
Bestie, it's a vibe check, but make it types. Returns true if Term is a reference; otherwise, returns false. That's literally it, no notes. 💅
Examples
1> is_reference(make_ref()).
true
2> is_reference(self()).
false
is_tuple(Term) -> boolean()
when Term :: term().
Returns true if Term is a tuple; otherwise, returns false. Simple, clean, iconic. 🎀
Examples
1> is_tuple({a, b, c}).
true
2> is_tuple([a, b, c]).
false
length(List) -> non_neg_integer()
when List :: [term()].
Returns the length of List. Counts it. Slays it. 🦋
Examples
1> length([1,2,3,4,5,6,7,8,9]).
9
2> length([a,b|c]).
** exception error: bad argument
in function length/1
called as length([a,b|c])
*** argument 1: not a list
NOTICE:[a,b|c]is not a proper list — it's an improper one (that tailcis giving "no"). It throws, and the error message is very much telling on you. FORMAT ERROR: maybe the manpage originally had this in italics, but whatever — anyway, the important bit: the argument has to be an actual list. 😭
link(PidOrPort) -> true
when PidOrPort :: pid() | port().
Sets up and activates a link between the calling process and another process or a port identified by PidOrPort. Bestie, this is the "we're bonded now, for better or worse" of Erlang. 💖
We will from here on call the identified process or port linkee. If the linkee is a port, it must reside on the same node as the caller.
If one of the participants of a link terminates, it will send an exit signal to the other participant. The exit signal will contain the exit reason of the terminated participant. Other cases when exit signals are triggered due to a link are when no linkee exist (noproc exit reason) and when the connection between linked processes on different nodes is lost or cannot be established (noconnection exit reason).
An existing link can be removed by calling unlink/1. For more info on links and exit signals due to links, see the Processes chapter in the Erlang Reference Manual:
- Links
- Sending Exit Signals
- Receiving Exit Signals
For historical reasons, link/1 has a strange semi-synchronous behavior when it is "cheap" to check if the linkee exists or not, and the caller does not trap exits. If the above is true and the linkee does not exist, link/1 will raise a noproc error exception. The expected behavior would instead have been that link/1 returned true, and the caller later was sent an exit signal with noproc exit reason, but this is unfortunately not the case. The noproc exception is not to be confused with an exit signal with exit reason noproc. Currently it is "cheap" to check if the linkee exists when it is supposed to reside on the same node as the calling process. 🫠
The link setup and activation is performed asynchronously. If the link already exists, or if the caller attempts to create a link to itself, nothing is done. A detailed description of the link protocol can be found in the Distribution Protocol chapter of the ERTS User's Guide.
NOTE: For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual. Do not skip this, bestie, it's load-bearing. 🧚
Failure:
badargifPidOrPortdoes not identify a process or a node local port.noproclinkee does not exist and it is "cheap" to check if it exists as described above.
link(PidOrPort, [link_option()]) -> true
when PidOrPort :: pid() | port().
Provides an option list for modification of the link functionality provided by link/1. The PidOrPort argument has the same meaning as when passed to link/1.
Currently available options:
priority— Since OTP 28.0 ✨
Enables priority message reception of EXIT messages due to the link for the calling process. If the link already exists without priority message reception enabled for the link, priority message reception will be enabled on the existing link. If the link already exists with priority message reception enabled and this option is not passed or link/1 is called, priority message reception for this link will be disabled.
Note that priority message reception due to the link is only enabled for the process that passed this option. If the linked process also wants to enable priority message reception, it needs to call link/2 passing the priority option itself. 👯
WARNING: You very seldom need to resort to using priority messages and you may cause issues instead of solving issues if not used with care. Fr fr, be careful.
For more information see the Adding Messages to the Message Queue section of the Erlang Reference Manual.
list_to_atom(String) -> atom()
when String :: string().
Returns the atom whose text representation is String, creating a new atom if necessary. Making atoms out of thin air? Iconic behavior, honestly. 🌸
As from Erlang/OTP 20, String may contain any Unicode character. Earlier versions allowed only ISO-latin-1 characters as the implementation did not allow Unicode characters above 255.
NOTE: Note that once an atom is created, it cannot be deleted. The Erlang system has a configurable limit on the number of atoms that can exist. To avoid reaching this limit, consider whetherlist_to_existing_atom/1is a better choice thanlist_to_atom/1. The number of characters that are permitted in an atom name is limited. Bestie, atoms are forever. Choose wisely. 💀
Examples
1> list_to_atom("Erlang").
2> list_to_atom([960]).
list_to_binary(IoList) -> binary()
when IoList :: iolist().
Returns a binary made from the integers and binaries in IoList. Gluing it all together, chef's kiss. 🎀
Examples
1> Bin1 = <<1,2,3>>.
<<1,2,3>>
2> Bin2 = <<4,5>>.
<<4,5>>
3> Bin3 = <<6>>.
<<6>>
4> list_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6>>
list_to_bitstring(BitstringList) -> bitstring()
when BitstringList :: bitstring_list().
Returns a bitstring made from the integers and bitstrings in BitstringList.
The last tail in BitstringList is allowed to be a bitstring. (Yes, that's the special little permission slip here — a plain iolist() could never. 🙈)
Examples
1> Bin1 = <<1,2,3>>.
<<1,2,3>>
2> Bin2 = <<4,5>>.
<<4,5>>
3> Bin3 = <<6,7:4>>.
<<6,7:4>>
4> list_to_bitstring([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6,7:4>>
list_to_existing_atom(String) -> atom()
when String :: string().
Returns the atom whose text representation is String, but only if there already exists such atom. No making new friends here — you have to already know them. 👑
An atom exists if it has been created by the run-time system by either loading code or creating a term that the atom is a part of.
Failure: badarg if there does not already exist an atom whose text representation is String.
NOTE: Note that the compiler may optimize away atoms. For example, the compiler will rewriteatom_to_list(some_atom)to"some_atom". If that expression is the only mention of the atomsome_atomin the containing module, the atom will not be created when the module is loaded, and a subsequent call tolist_to_existing_atom("some_atom")will fail. The compiler said "not today" and honestly? same. 😭
Examples
1> list_to_existing_atom("a_blatal_DOS_attack").
** exception error: bad argument
in function list_to_existing_atom/1
called as list_to_existing_atom("a_blatal_DOS_attack")
*** argument 1: not an already existing atom
2> hello.
hello
3> list_to_existing_atom("hello").
hello
list_to_float(String) -> float()
when String :: string().
Returns the float whose text representation is String.
Examples
1> list_to_float("2.2017764e+0").
2.2017764
The float string format is the same as the format for Erlang float literals except for that underscores are not permitted. (So _ in your float string? Not allowed. It's giving "I don't know her". 💅)
Failure: badarg if String contains a invalid representation of a float.
list_to_integer(String) -> integer()
when String :: string().
Returns an integer whose text representation is String.
String must contain at least one digit character and can have an optional prefix consisting of a single "+" or "-" character (that is, String must match the regular expression "^[+-]?[0-9]+$").
Failure: badarg if String contains a invalid representation of an integer.
Examples
1> list_to_integer("123").
123
2> list_to_integer("-123").
-123
3> list_to_integer("+123234982304982309482093833234234").
123234982304982309482093833234234
list_to_integer(String, Base) -> integer()
when String :: string(), Base :: 2..36.
Returns an integer whose text representation in base Base is String.
String must contain at least one digit character and can have an optional prefix consisting of a single "+" or "-" character.
Failure: badarg if String contains an invalid integer representation.
Examples
1> list_to_integer("3FF", 16).
1023
2> list_to_integer("+3FF", 16).
1023
3> list_to_integer("3ff", 16).
1023
4> list_to_integer("-3FF", 16).
-1023
5> list_to_integer("Base36IsFun", 36).
41313437507787071
6> list_to_integer("102", 2).
** exception error: bad argument
in function list_to_integer/2
called as list_to_integer("102",2)
*** argument 1: not a textual representation of an integer
FYI:"102"in base 2? Bestie,2is not a binary digit. That error is literally the system telling you to check your math. 🔥
list_to_pid(String) -> pid()
when String :: string().
Returns a process identifier whose text representation is a String.
Failure: badarg if String contains an invalid representation of a process identifier.
WARNING: This BIF is intended for debugging and is not to be used in application programs. Debugging only, bestie. Do not ship this. 🚫
Examples
1> list_to_pid("<0.1.0>").
<0.1.0>
list_to_port(String) -> port()
when String :: string().
Returns a port identifier whose text representation is a String.
Failure: badarg if String contains a bad representation of a port identifier.
WARNING: This BIF is intended for debugging and is not to be used in application programs. Same energy as above: debug tool, not a lifestyle. 🌈
1> list_to_port("#Port<0.0>").
#Port<0.0>
list_to_ref(String) -> reference() when String :: string().
Hands you back a reference whose text representation is exactly String.
Failure: badarg if String contains a bad representation of a reference.
💀 WARNING: this BIF is for debugging and is not to be used in application programs. Like, at all. It's giving "toy", not "production", bestie.
Examples ✨
1> list_to_ref("#Ref<0.0.0.0>").
#Ref<0.0.0.0>
list_to_tuple(List) -> tuple() when List :: [term()].
Returns a tuple whose elements are the elements of List. Literally the glow-up from list to tuple, no notes 💅
Examples 🌸
1> list_to_tuple([share, ['Ericsson_B', 163]]).
{share, ['Ericsson_B', 163]}
load_module(Module, Binary) -> {module, Module} | {error, Reason}
load_module(Module, Binary) -> {module, Module} | {error, Reason}
when
Module :: module(),
Binary :: binary(),
Reason ::
badfile | not_purged | on_load |
{features_not_allowed, [atom()]}.
Loads Module described by the object code sitting inside Binary.
If the code for module Module already exists, all export references are replaced so they point to the newly loaded code. The previously loaded code is kept in the system as old code, because there can still be processes out there executing that code. Respect the elders 🫶
Returns either {module, Module}, or {error, Reason} if loading fails. Reason is one of these, and each one has lore:
badfile— the object code in Binary has an incorrect format, or the object code contains code for a module other than Module. Rude.not_purged— Binary contains a module that cannot be loaded because old code for this module already exists.on_load— the code in Binary contains anon_loaddeclaration that must be executed before Binary can become the current code. Any previous current code for Module will remain until theon_loadcall has finished. It's giving "wait your turn" ⏳not_allowed— the code in Binary has been compiled with features that are currently not enabled in the runtime system.
⚠️ WARNING: this BIF is for the code server (see code) and is not to be used elsewhere. Not your toy, bestie.
load_nif(Path, LoadInfo) -> ok | Error
load_nif(Path, LoadInfo) -> ok | Error
when
Path :: string(),
LoadInfo :: term(),
Error :: {error, {Reason, Text :: string()}},
Reason ::
load_failed | bad_lib | load | reload |
upgrade | old_code.
Loads and links a dynamic library containing native implemented functions (NIFs) for a module. Okay so this is where Erlang meets C and it's honestly iconic 💖
Path is a file path to the shareable object/dynamic library file minus the OS-dependent file extension (.so for Unix and .dll for Windows). Notice that on most OSs the library has to have a different name on disc when an upgrade of the nif is done. If the name is the same but the contents differ, the old library may be loaded instead. Sneaky 💀 For info on how to actually implement a NIF library, see erl_nif(3).
LoadInfo can be any term. It's passed on to the library as part of the initialization. A good practice is to include a module version number to support future code upgrade scenarios. Future-proofing? We love to see it.
The call to load_nif/2 must be made directly from the Erlang code of the module that the NIF library belongs to. It returns either ok, or {error,{Reason,Text}} if loading fails. Reason is one of these atoms, while Text is a human readable string that can give more information about the failure:
load_failed— the OS failed to load the NIF library. Not the vibe. 😭bad_lib— the library did not fulfill the requirements as a NIF library of the calling module.load|upgrade— the corresponding library callback was unsuccessful.reload— a NIF library is already loaded for this module instance. The previously deprecated reload feature was removed in OTP 20.old_code— the call toload_nif/2was made from the old code of a module that has been upgraded; this is not allowed.
If the -nifs() attribute is used (which is recommended ✨), all NIFs in the dynamic library must be declared as such for load_nif/2 to succeed. On the other hand, all functions declared with the -nifs() attribute do not have to be implemented by the dynamic library. This allows a target independent Erlang file to contain fallback implementations for functions that may lack NIF support depending on target OS/hardware platform. Versatile queen 👑
loaded() -> [Module] when Module :: module().
Returns a list of all loaded Erlang modules (current and old code), including preloaded modules.
See also code.
localtime() -> DateTime when DateTime :: calendar:datetime().
Returns the current local date and time, {{Year, Month, Day}, {Hour, Minute, Second}}.
For example:
> erlang:localtime().
{{1996,11,6},{14,45,17}}
The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time.
localtime_to_universaltime(Localtime) -> Universaltime
localtime_to_universaltime(Localtime) -> Universaltime
when
Localtime ::
calendar:datetime(),
Universaltime ::
calendar:datetime().
Converts local date and time to Universal Time Coordinated (UTC), if supported by the underlying OS. Otherwise no conversion is done and Localtime is returned. No conversion? Fine, we move 🌈
For example:
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}).
{{1996,11,6},{13,45,17}}
Failure: badarg if Localtime denotes an invalid date and time.
localtime_to_universaltime(Localtime, IsDst) -> Universaltime
localtime_to_universaltime(Localtime, IsDst) -> Universaltime
when
Localtime ::
calendar:datetime(),
Universaltime ::
calendar:datetime(),
IsDst ::
true | false | undefined.
Converts local date and time to Universal Time Coordinated (UTC) just like erlang:localtime_to_universaltime/1, but this time the caller decides if Daylight Saving Time is active. You're the main character of this timezone now 👑
If IsDst == true, Localtime is during Daylight Saving Time. If IsDst == false, it is not. If IsDst == undefined, the underlying OS can guess, which is the same as calling erlang:localtime_to_universaltime(Localtime).
Examples:
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, true).
{{1996,11,6},{12,45,17}}
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, false).
{{1996,11,6},{13,45,17}}
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, undefined).
{{1996,11,6},{13,45,17}}
Failure: badarg if Localtime denotes an invalid date and time.
make_ref() -> reference().
Returns a unique reference.
The reference is unique among connected nodes.
⚠️ WARNING: Before OTP 23, if a node was restarted multiple times with the same node name, references created on a newer instance could be mistaken for those created on an older instance with the same name. Yeah, that's a whole identity crisis 💀
Examples 🦋
1> is_reference(make_ref()).
true
make_tuple(Arity, InitialValue) -> tuple()
make_tuple(Arity, InitialValue) -> tuple()
when Arity :: arity(), InitialValue :: term().
Creates a new tuple of the specified Arity, where all elements are InitialValue. Same energy, Arity times ✨
Examples 🎀
1> erlang:make_tuple(4, []).
{[],[],[],[]}
make_tuple(Arity, DefaultValue, InitList) -> tuple()
make_tuple(Arity, DefaultValue, InitList) -> tuple()
when
Arity :: arity(),
DefaultValue :: term(),
InitList ::
[{Position :: pos_integer(), term()}].
Creates a tuple of size Arity, where each element has value DefaultValue, and then fills in values from InitList.
Each list element in InitList must be a two-tuple, where the first element is a position in the newly created tuple and the second element is any term. If a position occurs more than once in the list, the term corresponding to the last occurrence is used. Last one wins, periodt 💅
Examples ⭐
1> erlang:make_tuple(5, [], [{2,ignored},{5,zz},{2,aa}]).
{[],aa,[],[],zz}
map_get(Key, Map) -> Value
map_get(Key, Map) -> Value
when Map :: map(), Key :: any(), Value :: any().
Returns value Value associated with Key if Map contains Key.
The call fails with a {badmap,Map} exception if Map is not a map, or with a {badkey,Key} exception if no value is associated with Key. It will simply not gaslight you about it 😤
Examples 💜
1> Key = 1337.
2> Map = #{42 => value_two,Key => "value one","a" => 1}.
3> map_get(Key, Map).
"value one"
4> map_get(unknown_key, Map).
** exception error: bad key: unknown_key
in function map_get/2
called as map_get(unknown_key,#{42 => value_two,1337 => "value one","a" => 1})
*** argument 1: not present in map
5> map_get(key, no_map).
** exception error: bad map: no_map
in function map_get/2
called as map_get(key,no_map)
*** argument 2: not a map
map_size(Map) -> non_neg_integer() when Map :: map().
Returns the number of key-value pairs in Map. Just the count, bestie, nothing deeper 🔢
Examples 🌈
1> map_size(#{a=>1, b=>2, c=>3}).
3
match_spec_test(MatchAgainst, MatchSpec, Type) -> TestResult
match_spec_test(MatchAgainst, MatchSpec, Type) -> TestResult
when
MatchAgainst :: [term()] | tuple(),
MatchSpec :: term(),
Type :: table | trace,
TestResult ::
{ok,
term(),
[return_trace],
[{error | warning, string()}]} |
{error, [{error | warning, string()}]}.
🫶 okay and this is where our chunk cuts off, bestie — the deets for this one keep going, so hold that thought…
match_spec_test — okay so this one is the ultimate match spec reality check 💅 it tests a match specification used in calls to ets:select/2 and trace:function/4.
and it does BOTH jobs for you, bestie: it tests a match specification for ✨"syntactic" correctness✨ and runs the match specification against the object. two birds, one iconic little function 🦋
if the match specification contains errors, the tuple {error, Errors} is returned, where Errors is a list of natural language descriptions of what was wrong with the match specification. natural language! it literally speaks to you. we love an honest queen 😭
if Type is table, the object to match against is to be a tuple. the function then returns {ok,Result,[],Warnings}, where Result is what would have been the result in a real ets:select/2 call, or false if the match specification does not match the object tuple.
if Type is trace, the object to match against is to be a list. the function returns {ok, Result, Flags, Warnings}, where Result is one of the following:
trueif a trace message is to be emittedfalseif a trace message is not to be emitted- The message term to be appended to the trace message
Flags is a list of trace flags to be enabled; currently, the only available flag is return_trace.
See also ets:test_ms/2.
Examples 🌸
1> Ms = [{{'$1','$2'}, [], [{{'$2','$1'}}]}].
2> erlang:match_spec_test({a,b}, Ms, table).
{ok,{b,a},[],[]}
3> erlang:match_spec_test({a,b,c}, Ms, table).
{ok,false,[],[]}
max(Term1, Term2) -> Maximum
when Term1 :: term(), Term2 :: term(), Maximum :: term().
Returns the largest of Term1 and Term2. biggest one wins, slay 👑
if the terms compare equal with the == operator, Term1 is returned. (so 1 beats 1.0 in the tie — noted, bestie 📝)
the Expressions section contains descriptions of the == operator and how terms are ordered.
CHANGE: Allowed in guards tests from Erlang/OTP 26.
Examples 💖
1> max(1, 2).
2
2> max(1.0, 1).
1.0
3> max(1, 1.0).
1
4> max("abc", "b").
"b"
md5(Data) -> Digest when Data :: iodata(), Digest :: binary().
Computes an MD5 message digest from Data, where the length of the digest is 128 bits (16 bytes). Data is a binary or a list of small integers and binaries.
for more information about MD5, see RFC 1321 - The MD5 Message-Digest Algorithm.
WARNING: The MD5 Message-Digest Algorithm is not considered safe for code-signing or software-integrity purposes. like, do NOT use this for your secrets, bestie, it's giving expired 🔥🚫
md5_final(Context) -> Digest
when Context :: binary(), Digest :: binary().
Finishes the update of an MD5 Context and returns the computed MD5 message digest. closing the tab on that MD5 session, periodt ✨
md5_init() -> Context when Context :: binary().
Creates an MD5 context, to be used in the following calls to md5_update/2. setting the stage, main character energy 🎀
md5_update(Context, Data) -> NewContext
when
Context :: binary(),
Data :: iodata(),
NewContext :: binary().
Update an MD5 Context with Data and returns a NewContext. keep feeding it, it keeps growing 💜
memory() -> [{Type, Size}]
when Type :: memory_type(), Size :: non_neg_integer().
Returns a list with information about memory dynamically allocated by the Erlang emulator. the emulator's lil memory receipts, we're obsessed 🧚
each list element is a tuple {Type, Size}. the first element Type is an atom describing memory type. the second element Size is the memory size in bytes.
Memory types:
total— the total amount of memory currently allocated. this is the same as the sum of the memory size forprocessesandsystem.processes— the total amount of memory currently allocated for the Erlang processes.processes_used— the total amount of memory currently used by the Erlang processes. this is part of the memory presented asprocessesmemory.system— the total amount of memory currently allocated for the emulator that is not directly related to any Erlang process. memory presented asprocessesis not included in this memory.instrumentcan be used to get a more detailed breakdown of what memory is part of this type.atom— the total amount of memory currently allocated for atoms. this memory is part of the memory presented assystemmemory.atom_used— the total amount of memory currently used for atoms. this memory is part of the memory presented asatommemory.binary— the total amount of memory currently allocated for binaries. this memory is part of the memory presented assystemmemory.code— the total amount of memory currently allocated for Erlang code. this memory is part of the memory presented assystemmemory.ets— the total amount of memory currently allocated for ETS tables. this memory is part of the memory presented assystemmemory.maximum— the maximum total amount of memory allocated since the emulator was started. this tuple is only present when the emulator is run with instrumentation.
for information on how to run the emulator with instrumentation, see instrument and/or erl(1).
NOTE: Thesystemvalue is not complete. some allocated memory that is to be part of this value is not. when the emulator is run with instrumentation, thesystemvalue is more accurate, but memory directly allocated formalloc(and friends) is still not part of thesystemvalue. direct calls tomallocare only done from OS-specific runtime libraries and perhaps from user-implemented Erlang drivers that do not use the memory allocation functions in the driver interface. as thetotalvalue is the sum ofprocessesandsystem, the error insystempropagates to thetotalvalue. the different amounts of memory that are summed are not gathered atomically, which introduces an error in the result. 😭 math said "close enough"
the different values have the following relation to each other. values beginning with an uppercase letter is not part of the result.
total = processes + system
processes = processes_used + ProcessesNotUsed
system = atom + binary + code + ets + OtherSystem
atom = atom_used + AtomNotUsed
RealTotal = processes + RealSystem
RealSystem = system + MissedSystem
more tuples in the returned list can be added in a future release. heads up, the list might grow later, bestie 🌈
NOTE: Thetotalvalue is supposed to be the total amount of memory dynamically allocated by the emulator. shared libraries, the code of the emulator itself, and the emulator stacks are not supposed to be included. that is, thetotalvalue is not supposed to be equal to the total size of all pages mapped to the emulator. also, because of fragmentation and prereservation of memory areas, the size of the memory segments containing the dynamically allocated memory blocks can be much larger than the total size of the dynamically allocated memory blocks.
CHANGE: As from ERTS 5.6.4,erlang:memory/0requires that allerts_alloc(3)allocators are enabled (default behavior).
Failure:notsupif anerts_alloc(3)allocator has been disabled.
memory(Type :: memory_type()) -> non_neg_integer();
(TypeList :: [memory_type()]) ->
[{memory_type(), non_neg_integer()}].
Returns the memory size in bytes allocated for memory of type Type. the argument can also be specified as a list of memory_type/0 atoms, in which case a corresponding list of {memory_type(), Size :: integer >= 0} tuples is returned. so you can ask for one type or ask for a whole lil list of them, we love options 💅
CHANGE: As from ERTS 5.6.4,erlang:memory/1requires that allerts_alloc(3)allocators are enabled (default behavior).
Failures:
badarg— ifTypeis not one of the memory types listed in the description oferlang:memory/0.badarg— ifmaximumis passed asTypeand the emulator is not run in instrumented mode.notsup— if anerts_alloc(3)allocator has been disabled.
See also erlang:memory/0.
min(Term1, Term2) -> Minimum
when Term1 :: term(), Term2 :: term(), Minimum :: term().
Returns the smallest of Term1 and Term2. tiniest one takes the crown 👑
if the terms compare equal with the == operator, Term1 is returned. (again, 1 wins over 1.0, same vibe as max, bestie 📝)
the Expressions section contains descriptions of the == operator and how terms are ordered.
CHANGE: Allowed in guards tests from Erlang/OTP 26.
Examples 🫶
1> min(1, 2).
1
2> min(1.0, 1).
1.0
3> min(1, 1.0).
1
4> min("abc", "b").
"abc"
module_loaded(Module) -> boolean() when Module :: module().
Returns true if the module Module is loaded as current code; otherwise, false. and NO, it does not attempt to load the module — it's just checking, not fixing. it does not chase after it, it simply observes 🦋
monitor(process, monitor_process_identifier()) -> MonitorRef
when MonitorRef :: reference();
(port, monitor_port_identifier()) -> MonitorRef
when MonitorRef :: reference();
(time_offset, clock_service) -> MonitorRef
when MonitorRef :: reference().
Sends a monitor request of type Type to the entity identified by Item. sending a lil "hey, i'm watching you" signal 👀
if the monitored entity does not exist or it changes monitored state, the caller of monitor/2 is notified by a message on the following format:
{Tag, MonitorRef, Type, Object, Info}
NOTE: The monitor request is an asynchronous signal. that is, it takes time before the signal reaches its destination. so don't expect instant feedback, bestie, it's in the mail 📬
Type can be one of the following atoms: process, port or time_offset.
a process or port monitor is triggered only once, after that it is removed from both monitoring process and the monitored entity. monitors are fired when the monitored process or port terminates, does not exist at the moment of creation, or if the connection to it is lost. if the connection to it is lost, we do not know if it still exists. the monitoring is also turned off when demonitor/1 is called. one and done, no lingering situationships 🙈
okay so real talk — a process or port monitor that you set up by name resolves that RegisteredName to a pid() or port() literally once, at the exact moment the monitor gets created. after that? if the name registration changes, your existing monitor does not care. it's locked in, bestie. 💅
When a process or port monitor fires, a 'DOWN' message gets sent with this pattern:
{'DOWN', MonitorRef, Type, Object, Info}
In that monitor message, MonitorRef and Type are the same as described earlier, and:
Object— the monitored entity that triggered the event. When you're monitoring a process or a local port,Objectequals thepid()orport()that was being monitored. When you monitor a process or port by name,Objectinstead has the format{RegisteredName, Node}, whereRegisteredNameis the name you handed to themonitor/2call andNodeis the local or remote node name. (For ports monitored by name,Nodeis always the local node name.)Info— either the exit reason of the process,noproc(meaning the process or port did not exist at the time the monitor was created), ornoconnection(meaning there's no connection to the node where the monitored process lives).
👀 Monitoring a process
Creates a monitor between the current process and another process identified by Item, which can be a pid() (local or remote), an atom RegisteredName, or a tuple {RegisteredName, Node} for a registered process located somewhere else.
🚨 CHANGE: Before ERTS 10.0 (OTP 21.0), monitoring a process could fail withbadargif the monitored process lived on a primitive node (likeerl_interfaceorjinterface), where remote process monitoring just isn't implemented. Now, that call to monitor instead succeeds and a monitor is created. But heads up — the monitor will only supervise the connection. That means a{'DOWN', _, process, _, noconnection}is the only message you might receive, since the primitive node has no way to report the status of the monitored process. 🫠
🔌 Monitoring a port
Creates a monitor between the current process and a port identified by Item, which can be a port() (only local), an atom RegisteredName, or a tuple {RegisteredName, Node} for a registered port located on this node. Note that trying to monitor a remote port will result in badarg. 😭
Available since OTP 19.0.
⏰ Monitoring a time_offset
Monitors changes in time_offset() between Erlang monotonic time and Erlang system time. There's exactly one valid Item that works with the time_offset Type, namely the atom clock_service. Fun fact: clock_service is not the registered name of a process. Here it serves as an identifier for the runtime system's internal clock service at the current runtime system instance. ✨
The monitor triggers when the time offset changes. This happens either when the time offset value changes, or when the offset goes from preliminary to final during finalization of the time offset when the single time warp mode is in use. When a change from preliminary to final time offset is made, the monitor triggers once regardless of whether the time offset value actually changed or not.
If the runtime system is in multi time warp mode, the time offset changes when the runtime system detects that the OS system time has changed. The runtime system does not, however, detect this immediately when it happens. A task checking the time offset is scheduled to run at least once a minute, so under normal operation this gets detected within a minute — but during heavy load it can take longer. 🐌
The monitor is not automatically removed after it's triggered. So repeated changes of the time offset trigger the monitor repeatedly. It just keeps going, like a group chat notification you can't mute. 💀
When the monitor triggers, a 'CHANGE' message is sent to the monitoring process. A 'CHANGE' message has this pattern:
{'CHANGE', MonitorRef, Type, Item, NewTimeOffset}
where MonitorRef, Type, and Item are the same as described above, and NewTimeOffset is the new time offset.
Once you've received the 'CHANGE' message, you're guaranteed not to retrieve the old time offset when calling erlang:time_offset/0. 👑 Notice though — you can observe the change of the time offset when calling erlang:time_offset/0 before you get the 'CHANGE' message.
Available since OTP 18.0.
Making several calls to monitor/2 for the same Item and/or Type is not an error — it just results in as many independent monitoring instances. stack 'em up, girl. 🌈
The monitor functionality is expected to be extended. That is, other Types and Items are expected to be supported in a future release.
📝 NOTE: If or whenmonitor/2is extended, other possible values forTag,Object, andInfoin the monitor message will be introduced.
📝 NOTE: For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.
🌸 the monitor/3 spec, look at her
monitor(process, monitor_process_identifier(), [monitor_option()]) ->
MonitorRef
when MonitorRef :: reference();
(port, monitor_port_identifier(), [monitor_option()]) ->
MonitorRef
when MonitorRef :: reference();
(time_offset, clock_service, [monitor_option()]) ->
MonitorRef
when MonitorRef :: reference().
Provides an option list for modifying the monitoring functionality that monitor/2 gives you. The Type and Item arguments mean the same thing as when you pass them to monitor/2.
Currently available options:
{alias, UnaliasOpt}— the returned monitor reference will also become an alias for the calling process. That is, the returned reference can be used for sending messages to the calling process. See alsoalias/0. TheUnaliasOptdetermines how the alias should be deactivated:explicit_unalias— only an explicit call tounalias/1will deactivate the alias.demonitor— the alias is automatically deactivated when the monitor is removed. That's either via an explicit call todemonitor/1or when it's automatically removed at the same time as a'DOWN'message is delivered because of the monitor. The alias can also still be deactivated via a call tounalias/1.reply_demonitor— the alias is automatically deactivated when the monitor is removed (see thedemonitoroption above) or when a reply message sent via the alias is received. When a reply message is received via the alias, the monitor is also automatically removed. This is useful in client/server scenarios when a client monitors the server and will get the reply via the alias. Once the response is received, both the alias and the monitor are automatically removed — regardless of whether the response is a reply or a'DOWN'message. The alias can also still be deactivated via a call tounalias/1. Note that if the alias is removed using theunalias/1BIF, the monitor will still be left active. 🙈
Example:
server() ->
receive
{request, AliasReqId, Request} ->
Result = perform_request(Request),
AliasReqId ! {reply, AliasReqId, Result}
end,
server().
client(ServerPid, Request) ->
AliasMonReqId = monitor(process, ServerPid, [{alias, reply_demonitor}]),
ServerPid ! {request, AliasMonReqId, Request},
%% Alias as well as monitor will be automatically deactivated if we
%% receive a reply or a 'DOWN' message since we used 'reply_demonitor'
%% as unalias option...
receive
{reply, AliasMonReqId, Result} ->
Result;
{'DOWN', AliasMonReqId, process, ServerPid, ExitReason} ->
error(ExitReason)
end.
Note that both the server and the client in this example must be executing on at least OTP 24 systems for this to work.
For more info on process aliases, see the Process Aliases section of the Erlang Reference Manual.
{tag, UserDefinedTag}— replace the defaultTagwithUserDefinedTagin the monitor message delivered when the monitor is triggered. For example, when monitoring a process, the'DOWN'tag in the down message gets replaced byUserDefinedTag. 💖
Here's an example of how the {tag, UserDefinedTag} option can be used to enable the new selective receive optimization introduced in OTP 24, when making multiple requests to different servers:
server() ->
receive
{request, From, ReqId, Request} ->
Result = perform_request(Request),
From ! {reply, self(), ReqId, Result}
end,
server().
client(ServerPids, Request) when is_list(ServerPids) ->
ReqId = make_ref(),
lists:foreach(fun (ServerPid) ->
_ = monitor(process, ServerPid,
[{tag, {'DOWN', ReqId}}]),
ServerPid ! {request, self(), ReqId, Request}
end,
ServerPids),
receive_replies(ReqId, length(ServerPids), []).
receive_replies(_ReqId, 0, Acc) ->
Acc;
receive_replies(ReqId, N, Acc) ->
%% The compiler will detect that we match on the 'ReqId'
%% reference in all clauses, and will enable the selective
%% receive optimization which makes the receive able to
%% skip past all messages present in the message queue at
%% the time when the 'ReqId' reference was created...
Res = receive
{reply, ServerPid, ReqId, Result} ->
%% Here we typically would have deactivated the
%% monitor by a call to demonitor(Mon, [flush]) but
%% we ignore this in this example for simplicity...
{ok, ServerPid, Result};
{{'DOWN', ReqId}, _Mon, process, ServerPid, ExitReason} ->
{error, ServerPid, ExitReason}
end,
receive_replies(ReqId, N-1, [Res | Acc]).
okay so for this lil example to actually do the thing it's supposed to do, the client has to be running on at least an OTP 24 system 🫶 — but the servers can be out here on older systems, no problem bestie.
priority 💅
Since OTP 28.0 ✨
This one turns on priority message reception for the monitor message(s) that get sent when this monitor gets triggered for the calling process.
WARNING: bestie. listen. you very seldom need to resort to using priority messages, and honestly you might cause issues instead of solving them if you don't use this with care. like, respectfully, be careful. 😭
For more info, go peep the Adding Messages to the Message Queue section of the Erlang Reference Manual. iykyk 📖
monitor_node(Node, Flag) -> true
monitor_node(Node, Flag) -> true
when Node :: node(), Flag :: boolean().
Monitors the status of the node Node. If Flag is true, monitoring is turned ON 💚. If Flag is false, monitoring is turned OFF.
Calling monitor_node(Node, true) several times for the same Node is not an error, bestie — it just gives you that many independent monitoring instances, one for each call. stacking them like scrunchies fr fr 🎀
If Node fails or straight up doesn't exist, the message {nodedown, Node} gets delivered to the process. So if a process has made two calls to monitor_node(Node, true) and then Node terminates, guess what — two nodedown messages get delivered to that process. two. 😭 If there's no connection to Node, an attempt gets made to create one. If that fails, a nodedown message is delivered.
The delivery of the nodedown signal is not ordered with respect to other link or monitor signals from the node that goes down. So if you need a guarantee that all signals from the remote node have been delivered before the nodedown signal is sent, you should be using net_kernel:monitor_nodes/1 instead. periodt 💅
Nodes connected through hidden connections can be monitored just like any other nodes 🌈
Failure: notalive if the local node is not alive. 💀
monitor_node(Node, Flag, Options) -> true
monitor_node(Node, Flag, Options) -> true
when
Node :: node(),
Flag :: boolean(),
Options :: [Option],
Option :: allow_passive_connect.
Behaves exactly like monitor_node/2, except it lets you pass an extra option, and that option is allow_passive_connect. 👑
This option lets the BIF wait out the normal network connection time-out for the monitored node to connect itself, even if it can't be actively connected from this node (aka, it's blocked 🚫). The state where this is actually useful can only be reached by using the Kernel option dist_auto_connect once. If that option isn't used, allow_passive_connect has no effect at all. like, zero. 🙈
NOTE: the option allow_passive_connect is used internally and is seldom needed in applications where the network topology and the Kernel options in effect are known in advance.
Failure: badarg if the local node is not alive or the option list is malformed. 💀
monotonic_time() -> integer()
monotonic_time() -> integer().
Returns the current Erlang monotonic time in native time unit. This is a monotonically increasing time since some unspecified point in time. it goes up and it never comes back down, slay 📈
NOTE: this is a monotonically increasing time, but not a strictly monotonically increasing time. That is, consecutive calls toerlang:monotonic_time/0can produce the same result. 😳 Different runtime system instances will use different unspecified points in time as the base for their Erlang monotonic clocks. So comparing monotonic times from different runtime system instances is... pointless bestie, don't do it. 🙈 Different runtime system instances can also place this unspecified point in time differently relative to runtime system start. It can be placed in the future (time at start is a negative value), the past (time at start is a positive value), or at the runtime system start (time at start is zero). The monotonic time at runtime system start can be retrieved by callingerlang:system_info(start_time). ✨
monotonic_time(Unit) -> integer()
monotonic_time(Unit) -> integer() when Unit :: time_unit().
Returns the current Erlang monotonic time converted into the Unit you passed as the argument. 🫶
Same as calling erlang:convert_time_unit(erlang:monotonic_time(), native, Unit), except it's optimized for commonly used Units. main character energy, but make it fast 💅
nif_error(Reason) -> no_return()
nif_error(Reason) -> no_return() when Reason :: term().
Works exactly like error/1, except Dialyzer thinks this BIF will return an arbitrary term. So when you use it in a stub function for a NIF to generate an exception when the NIF library isn't loaded, Dialyzer doesn't hit you with false warnings. no cap, it's giving thoughtful 🎀
nif_error(Reason, Args) -> no_return()
nif_error(Reason, Args) -> no_return()
when Reason :: term(), Args :: [term()].
Works exactly like error/2, except Dialyzer thinks this BIF will return an arbitrary term. When used in a stub function for a NIF to generate an exception when the NIF library isn't loaded, Dialyzer does not generate false warnings. same vibe, two args 🦋
node() -> Node
node() -> Node when Node :: node().
Returns the name of the local node. 🏠
If the node is not alive, nonode@nohost is returned.
Examples 🌸
> node().
nonode@nohost
node(Arg) -> Node
node(Arg) -> Node
when Arg :: pid() | port() | reference(), Node :: node().
Returns the node where Arg originates from. 🔍
If Arg originates from the local node and the local node is not alive, nonode@nohost is returned.
Examples 🌸
1> node(self()) =:= node().
true
nodes() -> Nodes
nodes() -> Nodes when Nodes :: [node()].
Returns a list of all nodes connected to this node through normal connections (so, hidden nodes are not listed, sorry hidden girlies 🫣). Same as nodes(visible). 🌈
nodes(Arg) -> Nodes
nodes(Arg) -> Nodes
when
Arg :: NodeType | [NodeType],
NodeType ::
visible | hidden | connected | this | known,
Nodes :: [node()].
Returns a list of nodes according to the argument you specified. When the argument is a list, the returned result is the list of nodes satisfying the disjunction(s) of the list elements. math girlie behavior, we love to see it 📐💖
NodeTypes:
visible— Nodes connected to this node through normal connections. 👀hidden— Nodes connected to this node through hidden connections. 🫥connected— All nodes connected to this node. 🔗this— This node. 👑known— Nodes that are known to this node. That is, connected nodes and nodes referred to by process identifiers, port identifiers, and references located on this node. The set of known nodes is garbage collected. Notice that this garbage collection can be delayed. For more information, seeerlang:system_info(delayed_node_table_gc). 🗑️
Some equalities, for the math besties: [node()] = nodes(this), nodes(connected) = nodes([visible, hidden]), and nodes() = nodes(visible). ✨
nodes(Arg, InfoOpts) -> [NodeInfo]
nodes(Arg, InfoOpts) -> [NodeInfo]
when
NodeType ::
visible | hidden | connected | this | known,
Arg :: NodeType | [NodeType],
InfoOpts ::
#{connection_id => boolean(),
node_type => boolean()},
NodeTypeInfo :: visible | hidden | this | known,
ConnectionId :: undefined | integer(),
Info ::
#{connection_id => ConnectionId,
node_type => NodeTypeInfo},
NodeInfo :: {node(), Info}.
Returns a list of NodeInfo tuples. 🎁
The first element is the node name. Which nodes get included in the list is determined by the first argument Arg in exactly the same way as for nodes(Arg). The second element of the NodeInfo tuples is a map containing further information about the node identified by the first element. What's actually in that map is determined by the InfoOpts map passed as the second argument. Currently the following associations are allowed in the InfoOpts map:
connection_id => boolean()— If the value of the association equalstrue, theInfomap in the returned result will contain the keyconnection_idassociated with the valueConnectionId. IfConnectionIdequalsundefined, the node is not connected to the node which the caller is executing on, or it is the node which the caller is executing on. IfConnectionIdis an integer, the node is currently connected to the node which the caller is executing on. 🔗
The integer connection identifier value together with a node name identifies a specific connection instance to the node with that node name. The connection identifier value is node local. That is, on the other node the connection identifier will not be the same value. 🙅 If a connection is taken down and then taken up again, the connection identifier value will change for the connection to that node. The amount of values for connection identifiers is limited, so it is possible to see the same value for different instances — but it's quite unlikely. It is undefined how the value changes between two consecutive connection instances. 😵💫
node_type => boolean() — set this to true and the Info map in what you get back will have a node_type key, holding NodeTypeInfo. Rn the node types that exist are:
visible— the node is connected to the calling process's node through your regular, ordinary visible connection. Basically: its name would show up in whatevernodes/0hands you. 💅hidden— the node is connected to the calling process's node through a hidden connection. So its name would not appear in the result ofnodes/0. sneaky bestie 🫣this— ok so this is literally the calling process's own node. it's giving main character ✨known— the node isn't connected at all, but it is known to the calling process's node. like a mutual you've never actually hung out with.
Example, live from the shell:
(a@localhost)1> nodes([this, connected], #{connection_id=>true, node_type=>true}).
[{c@localhost,#{connection_id => 13892108,node_type => hidden}},
{b@localhost,#{connection_id => 3067553,node_type => visible}},
{a@localhost,#{connection_id => undefined,node_type => this}}]
(a@localhost)2>
🕰️ now() -> Timestamp
now() -> Timestamp when Timestamp :: timestamp().
Deprecated: erlang:now/0 is deprecated; peep the "Time and Time Correction in Erlang" chapter of the ERTS User's Guide if you want the tea.
WARNING: this function is deprecated. Do not use it. fr fr. For more info, see the section Time and Time Correction in the User's Guide. Specifically, the section Dos and Dont's lays out what you should be using instead of erlang:now/0. 🚫
It returns the tuple {MegaSecs, Secs, MicroSecs}, which is the elapsed time since 00:00 GMT, January 1, 1970 (zero hour) — if the underlying OS provides that. If not, some other random point in time gets picked. 🙃
It's also guaranteed that back-to-back calls to this BIF return continuously increasing values. So yes, the return value from erlang:now/0 can be used to generate unique timestamps. ✨ But heads up: if you call it in a tight loop on a fast machine, the node's time can get skewed. 😭
You can only use it to check the local time of day if the underlying OS's time-zone info is configured properly. no cap.
🔌 open_port(PortName, PortSettings) -> port()
open_port(PortName, PortSettings) -> port()
when
PortName ::
{spawn, Command :: string() | binary()} |
{spawn_driver,
Command :: string() | binary()} |
{spawn_executable,
FileName :: file:name_all()} |
{fd,
In :: non_neg_integer(),
Out :: non_neg_integer()},
PortSettings :: [Opt],
Opt ::
{packet, N :: 1 | 2 | 4} |
stream |
{line, L :: non_neg_integer()} |
{cd, Dir :: string() | binary()} |
{env,
Env ::
[{Name :: os:env_var_name(),
Val :: os:env_var_value() | [] |
false}]} |
{args, [string() | binary()]} |
{arg0, string() | binary()} |
exit_status | use_stdio | nouse_stdio |
stderr_to_stdout | in | out | binary | eof |
{parallelism, Boolean :: boolean()} |
hide |
{busy_limits_port,
{non_neg_integer(), non_neg_integer()} |
disabled} |
{busy_limits_msgq,
{non_neg_integer(), non_neg_integer()} |
disabled}.
Returns a port identifier as the result of opening a brand new Erlang port. Think of a port as an external Erlang process, bestie. 🫶
The name of the executable, plus the arguments you spec in cd, env, args, and arg0, are all subject to Unicode filename translation if the system is running in Unicode filename mode. If you want to dodge translation, or force something like UTF-8, hand the executable and/or arguments over as a binary in the correct encoding. For the full details, see the module file, the function file:native_name_encoding/0 in Kernel, and the Using Unicode in Erlang User's Guide. 📖
NOTE: the characters in the name (if you specify it as a list) can only be > 255 if the Erlang VM was started in Unicode filename translation mode. Otherwise the executable's name is capped to the ISO Latin-1 character set. 💀
✨ PortNames ✨
{spawn, Command}— starts an external program.Commandis the name of the external program to run.Commandruns outside the Erlang work space, unless an Erlang driver namedCommandis found — in which case that driver gets started instead. A driver runs inside the Erlang work space, meaning it's linked with the Erlang runtime system. 🔗
For external programs, PATH gets searched (or whatever equivalent method your OS uses to find programs). This happens by invoking the shell on certain platforms. The first space-separated token of the command is treated as the name of the executable (or driver). This — among other things — makes this option unsuitable for running programs whose filenames or directory names contain spaces. If you do want spaces in executable filenames, use {spawn_executable, Command} instead.
WARNING: on Unix systems, arguments get passed to a new OS process as an array of strings — but on Windows it's up to the child process to parse them, and some Windows programs apply their own rules, which are inconsistent with the standard C runtimeargvparsing. This gets particularly gnarly when you invoke.bat,.cmd, or.comfiles, since those run implicitly throughcmd.exe, whose argument parsing is vulnerable to malicious input and can be used to run arbitrary shell commands. So: if you're on Windows and you're executing batch files or.comapplications, you must not pass untrusted input as arguments to the program. This affects bothspawnandspawn_executable. 🚨
{spawn_executable, FileName}— works like{spawn, FileName}, but only runs external executables.FileNamein its entirety is used as the name of the executable, including any spaces. If you need to pass arguments, thePortSettingsargsandarg0are there for you. 👑
The shell is usually not invoked to start the program — it's executed directly. PATH (or equivalent) is not searched. If you want to find a program in PATH to execute, use os:find_executable/1.
Only if a shell script or .bat file is executed does the appropriate command interpreter get invoked implicitly — but even then there's still no command-argument expansion and no implicit PATH search.
If FileName can't be run, an error exception gets raised, with the POSIX error code as the reason. The error reason can differ between OSs. Typically enoent is raised when you attempt to run a program that isn't found, and eacces is raised when the specified file isn't executable. 😤
{spawn_driver, Command}— works like{spawn, Command}, but demands that the first (space-separated) token of the command be the name of a loaded driver. If no driver with that name is loaded, abadargerror is raised. 💀{fd, In, Out}— lets an Erlang process access any currently opened file descriptors used by Erlang. File descriptorIncan be used for standard input, and file descriptorOutfor standard output. It's only used for various servers in the Erlang OS (shell and user). Hence, its use is limited. 🙈
🌸 PortSettings 🌸
PortSettings is a list of settings for the port. The valid settings are as follows:
{packet, N}— messages are preceded by their length, sent inNbytes, with the most significant byte first. Valid values forNare1,2, and4. 🔢stream— output messages are sent without packet lengths. A user-defined protocol must be used between the Erlang process and the external object. ✨{line, L}— messages are delivered on a per-line basis. Each line (delimited by the OS-dependent newline sequence) is delivered in a single message. The message data format is{Flag, Line}, whereFlagiseolornoeol, andLineis the data delivered (minus the newline sequence).
L specifies the maximum line length in bytes. Lines longer than that get delivered across more than one message, with Flag set to noeol for all but the last message. If end of file is encountered anywhere other than immediately following a newline sequence, the last line is also delivered with Flag set to noeol. Otherwise lines are delivered with Flag set to eol.
The {packet, N} and {line, L} settings are mutually exclusive. pick one bestie, you can't have both 🙅♀️
{cd, Dir}— only valid for{spawn, Command}and{spawn_executable, FileName}. The external program starts usingDiras its working directory.Dirmust be a string.{env, Env}— only valid for{spawn, Command}, and{spawn_executable, FileName}. The environment of the started process gets extended using the environment specifications inEnv.
Env is to be a list of tuples {Name, Val}, where Name is an os:env_var_name/0 representing the name of an environment variable, and Val is a os:env_var_name/0 representing the value it is to have in the spawned port process. Both Name and Val must be strings.
If Val is set to the atom false or the empty string (that is, "" or []), open_port will consider those variables unset — just as if os:unsetenv/1 had been called. 🫥
{args, [string() | binary()]}— only a thing for{spawn_executable, FileName}, and it's how you hand over the args to the executable. Each argument goes in as its own separate string, and on Unix each one literally ends up as one element in the argument vector. Other platforms just kinda mimic that behavior.
Heads up bestie: the args are not expanded by the shell before they hit the executable. Big deal: that means file wildcard expansion does not happen. Want wildcards expanded? Use filelib:wildcard/1 yourself. And even if the program is a Unix shell script (so like, the shell does eventually get invoked), wildcard expansion still doesn't happen and the script receives the untouched args. On Windows, wildcard expansion is always the program's own business, so it's a non-issue there.
Also: do not put the executable name (a.k.a. argv[0]) in this list. The proper executable name gets used as argv[0] automatically, where applicable. If you really wanna set the program name in the argument vector yourself, use the arg0 option. 💅
{arg0, string() | binary()}— only for{spawn_executable, FileName}, and it explicitly sets the program name argument when running an executable. In some circumstances, on some OSs, this is desirable. How the program responds to it is super system-dependent and no specific effect is guaranteed.exit_status— only valid for{spawn, Command}(whereCommandrefers to an external program) and for{spawn_executable, FileName}.
When the external process connected to the port exits, a message of the form {Port,{exit_status,Status}} gets sent to the connected process, where Status is the exit status of the external process. If the program aborts on Unix, same convention as the shells use (that is, 128+signal).
If you also specified option eof, the messages eof and exit_status appear in an unspecified order. So like, don't count on one coming first. 🙈
use_stdio— only for{spawn, Command}and{spawn_executable, FileName}. Lets the standard input and output (file descriptors0and1) of the spawned (Unix) process do the communicating with Erlang.nouse_stdio— the opposite ofuse_stdio. It uses file descriptors3and4to talk to Erlang instead.stderr_to_stdout— affects ports to external programs. The executed program gets its standard error file redirected into its standard output file. And jsyk,stderr_to_stdoutandnouse_stdioare mutually exclusive — pick one, bestie. ✨overlapped_io— affects ports to external programs on Windows only. The standard input and standard output handles of the port program are, if you supply this option, opened with flagFILE_FLAG_OVERLAPPED, so the port program can (and must) do overlapped I/O on its standard handles. Not normally the case for simple port programs, but an option of value for the experienced Windows programmer. On all other platforms this option is silently discarded. 🫠in— the port can only be used for input.out— the port can only be used for output.binary— all I/O from the port is binary data objects instead of lists of bytes.eof— the port is not closed at the end of the file and doesn't produce an exit signal. Instead it stays open and a{Port, eof}message is sent to the process holding the port.hide— when running on Windows, suppresses creation of a new console window when spawning the port program. (This option has no effect on other platforms.){parallelism, Boolean}— sets a scheduler hint for port parallelism. Set it totrueand the virtual machine schedules port tasks, which improves parallelism in the system. Set it tofalseand the VM tries to do port tasks immediately, which improves latency at the expense of parallelism. The default can be set at system startup by passing command-line argument+spptoerl.{busy_limits_port, {Low, High} | disabled}— sets the limits used for controlling the busy state of the port.
When the port's internal output queue size becomes larger than or equal to High bytes, it enters the busy state. When it becomes less than Low bytes, it leaves the busy state. While the port is in the busy state, processes sending commands to it get suspended until the port leaves the busy state. In this context, "commands" means either Port ! {Owner, {command, Data}} or port_command/[2,3].
The Low limit is automatically adjusted to the same as High if it's set larger than High. Valid range of values for Low and High is [1, (1 bsl (8*erlang:system_info(wordsize)))-2]. If the atom disabled is passed, the port will never enter the busy state.
The defaults are Low = 4096 and High = 8192.
Note: this option is only valid when spawning an executable (port program) by opening the spawn driver and when opening the fd driver. Using it when opening other drivers causes a failure with a badarg exception.
{busy_limits_msgq, {Low, High} | disabled}— sets the limits used for controlling the busy state of the port message queue.
When the port's message queue size becomes larger than or equal to High bytes, it enters the busy state. When it becomes less than Low bytes, it leaves the busy state. While the port message queue is in the busy state, processes sending commands to it get suspended until the port message queue leaves the busy state. Again, "commands" here means either Port ! {Owner, {command, Data}} or port_command/[2,3].
The Low limit is automatically adjusted to the same as High if it's set larger than High. Valid range of values for Low and High is [1, (1 bsl (8*erlang:system_info(wordsize)))-2]. If the atom disabled is passed, the port message queue will never enter the busy state.
Note: if the driver statically has disabled the use of this feature, a failure with a badarg exception is raised unless this option also is set to disable or not passed at all.
The defaults are Low = 4096 and High = 8192 unless the driver itself does modifications of these values.
Note: the driver might fail if it also adjusts these limits by itself and you have disabled this feature.
The spawn driver (used when spawning an executable) and the fd driver do not disable this feature and do not adjust these limits by themselves.
For more info, see the documentation for erl_drv_busy_msgq_limits().
Default is stream for all port types and use_stdio for spawned ports.
💀 The Failure Zone 💀
If the port cannot be opened, the exit reason is badarg, system_limit, or the POSIX error code that most closely describes the error, or einval if no POSIX code is appropriate:
badarg— bad input arguments toopen_port.system_limit— all available ports in the Erlang emulator are in use.enomem— not enough memory to create the port.eagain— no more available OS processes.enametoolong— too long external command.emfile— no more available file descriptors (for the OS process that the Erlang emulator runs in).enfile— full file table (for the entire OS).eacces— command specified in{spawn_executable, Command}does not point out an executable file.enoent—FileNamespecified in{spawn_executable, FileName}does not point out an existing file.
During use of a port opened using {spawn, Name}, {spawn_driver, Name}, or {spawn_executable, Name}, errors arising when sending messages to it are reported to the owning process using signals of the form {'EXIT', Port, PosixCode}. For the possible values of PosixCode, see file.
The maximum number of ports that can be open at the same time can be configured by passing command-line flag +Q to erl.
phash(Term, Range) -> Hash
phash(Term, Range) -> Hash
when
Term :: term(),
Range :: pos_integer(),
Hash :: pos_integer().
Deprecated:erlang:phash/2is deprecated; useerlang:phash2/2instead
WARNING: This function is deprecated aserlang:phash2/2should be used for new code. Note thaterlang:phash(X,N)is not necessarily equal toerlang:phash2(X,N).
Portable hash function that gives the same hash for the same Erlang term regardless of machine architecture and ERTS version (the BIF was introduced in ERTS 4.9.1.1). The function returns a hash value for Term within the range 1..Range. The maximum value for Range is 2^32.
phash2(Term, Range) -> Hash
phash2(Term, Range) -> Hash
when
Term :: term(),
Range :: pos_integer(),
Hash :: non_neg_integer().
Returns a hash value for Term. ✨
The hash value for the same Erlang term is guaranteed to be the same regardless of machine architecture and ERTS version. No cap.
The function returns a hash value for Term within the range 0..Range-1. The maximum value for Range is 2^32. When called without argument Range, a value in the range 0..2^27-1 is returned.
This BIF is always the one to use for hashing terms, bestie. It distributes small integers better than phash/2, and it's faster for large integers and binaries.
Notice that the range0..Range-1is different from the range ofphash/2, which is1..Range. Don't get them mixed up. 😭
Examples 🍓
1> erlang:phash2({a,b,c}, 1_000).
870
2> erlang:phash2(41, 1_000).
297
3> erlang:phash2(42, 1_000).
368
4> erlang:phash2(43, 1_000).
725
✨ pid_to_list/1 ✨
pid_to_list(Pid) -> string() when Pid :: pid().
Gives you back a string that is the text representation of Pid. that's it, that's the function 💅
NOTE: the creation for the node is NOT included in the list representation of Pid. bestie this is important 😭 it means processes in different incarnations of a node with a specific name can end up with the same list representation. same string, different vibe, no cap.
Examples 🌸
1> erlang:pid_to_list(<0.1.0>).
"<0.1.0>"
🦋 port_call/3 🦋
port_call(Port, Operation, Data) -> term()
when
Port :: port() | atom(),
Operation :: integer(),
Data :: term().
okay so this one does a synchronous call to a port. the meaning of Operation and Data? fully depends on the port, like, on the port driver. and ngl not all port drivers even support this feature 🙈
- Port is a port identifier, referring to a driver.
- Operation is an integer, which is passed on to the driver.
- Data is any Erlang term. this data is converted to binary term format and sent to the port.
Returns a term from the driver. the meaning of the returned data also depends on the port driver, so like, read the room (the driver docs) 💖
Failures:
badarg— if Port is not an identifier of an open port, or the registered name of an open port. and if the calling process was previously linked to the closed port, identified by Port, the exit signal from the port is guaranteed to be delivered before thisbadargexception occurs.badarg— if Operation does not fit in a 32-bit integer.badarg— if the port driver does not support synchronous control operations.badarg— if the port driver so decides for any reason (probably something wrong with Operation or Data). we don't ask questions 🫶
WARNING: do not callport_callwith an unknown Port identifier and expect abadargexception. literally any undefined behavior is possible (including node crash 💀) depending on how the port driver interprets the supplied arguments. do not play with this fr fr.
🎀 port_close/1 🎀
port_close(Port) -> true when Port :: port() | atom().
Closes an open port. roughly the same as Port ! {self(), close} except for the error behavior (see below), being synchronous, and that the port does not reply with {Port, closed}. subtle ✨
Any process can close a port with port_close/1, not only the port owner (the connected process). we love equal access 💅 if the calling process is linked to the port identified by Port, the exit signal from the port is guaranteed to be delivered before port_close/1 returns.
For comparison, since bestie needs the tea ☕: Port ! {self(), close} only fails with badarg if Port does not refer to a port or a process. if Port is a closed port, nothing happens. if Port is an open port and the calling process is the port owner, the port replies with {Port, closed} when all buffers have been flushed and the port really closes. if the calling process is not the port owner, the port owner fails with badsig.
Notice that any process can close a port using Port ! {PortOwner, close} as if it itself was the port owner, but the reply always goes to the port owner.
As from Erlang/OTP R16, Port ! {PortOwner, close} is truly asynchronous. notice that this operation has always been documented as an asynchronous operation, while the underlying implementation has been synchronous. port_close/1 is however still fully synchronous because of its error behavior. the mask stays on 😷
Failure: badarg if Port is not an identifier of an open port, or the registered name of an open port. if the calling process was previously linked to the closed port, identified by Port, the exit signal from the port is guaranteed to be delivered before this badarg exception occurs.
🌈 port_command/2 🌈
port_command(Port, Data) -> true
when Port :: port() | atom(), Data :: iodata().
Sends data to a port. same as Port ! {PortOwner, {command, Data}} except for the error behavior and being synchronous (see below). okurr 👑
Any process can send data to a port with port_command/2, not only the port owner (the connected process).
For comparison: Port ! {PortOwner, {command, Data}} only fails with badarg if Port does not refer to a port or a process. if Port is a closed port, the data message disappears without a sound 😶 if Port is open and the calling process is not the port owner, the port owner fails with badsig. the port owner fails with badsig also if Data is an invalid I/O list.
Notice that any process can send to a port using Port ! {PortOwner, {command, Data}} as if it itself was the port owner.
If the port is busy, the calling process is suspended until the port is not busy any more. nap time bestie 😴
As from Erlang/OTP R16, Port ! {PortOwner, {command, Data}} is truly asynchronous. notice that this operation has always been documented as an asynchronous operation, while the underlying implementation has been synchronous. port_command/2 is however still fully synchronous because of its error behavior.
Failures:
badarg— if Port is not an identifier of an open port, or the registered name of an open port. if the calling process was previously linked to the closed port, identified by Port, the exit signal from the port is guaranteed to be delivered before thisbadargexception occurs.badarg— if Data is an invalid I/O list.
WARNING: do not send data to an unknown port. any undefined behavior is possible (including node crash 💀) depending on how the port driver interprets the data. seriously.
💜 port_command/3 💜
port_command(Port, Data, OptionList) -> boolean()
when
Port :: port() | atom(),
Data :: iodata(),
Option :: force | nosuspend,
OptionList :: [Option].
Sends data to a port. port_command(Port, Data, []) equals port_command(Port, Data). slay, an overload 💖
If the port command is aborted, false is returned, otherwise true.
If the port is busy, the calling process is suspended until the port is not busy anymore.
Options:
force— the calling process is not suspended if the port is busy, instead the port command is forced through. the call fails with anotsupexception if the driver of the port does not support this. for more information, see driver flagERL_DRV_FLAG_SOFT_BUSY. 💪nosuspend— the calling process is not suspended if the port is busy, instead the port command is aborted andfalseis returned.
CHANGE: more options can be added in a future release. stay tuned besties 📢
Failures:
badarg— if Port is not an identifier of an open port, or the registered name of an open port. if the calling process was previously linked to the closed port, identified by Port, the exit signal from the port is guaranteed to be delivered before thisbadargexception occurs.badarg— if Data is an invalid I/O list.badarg— if OptionList is an invalid option list.notsup— if optionforcehas been passed, but the driver of the port does not allow forcing through a busy port. sorry bestie, not supported 🚫
WARNING: do not send data to an unknown port. any undefined behavior is possible (including node crash 💀) depending on how the port driver interprets the data.
🧚 port_connect/2 🧚
port_connect(Port, Pid) -> true
when Port :: port() | atom(), Pid :: pid().
Sets the port owner (the connected port) to Pid. roughly the same as Port ! {Owner, {connect, Pid}} except for the following tea 👇
- The error behavior differs, see below.
- The port does not reply with
{Port, connected}. port_connect/1is synchronous, see below.- The new port owner gets linked to the port.
The old port owner stays linked to the port and must call unlink(Port) if this is not desired. yes, it lingers, like an ex in the group chat 😭 any process can set the port owner to be any process with port_connect/2.
For comparison: Port ! {self(), {connect, Pid}} only fails with badarg if Port does not refer to a port or a process. if Port is a closed port, nothing happens. if Port is an open port and the calling process is the port owner, the port replies with {Port, connected} to the old port owner. notice that the old port owner is still linked to the port, while the new is not. if Port is an open port and the calling process is not the port owner, the port owner fails with badsig. the port owner fails with badsig also if Pid is not an existing local process identifier.
Notice that any process can set the port owner using Port ! {PortOwner, {connect, Pid}} as if it itself was the port owner, but the reply always goes to the port owner.
As from Erlang/OTP R16, Port ! {PortOwner, {connect, Pid}} is truly asynchronous. notice that this operation has always been documented as an asynchronous operation, while the underlying implementation has been synchronous. port_connect/2 is however still fully synchronous because of its error behavior.
Failures:
badarg— if Port is not an identifier of an open port, or the registered name of an open port. if the calling process was previously linked to the closed port, identified by Port, the exit signal from the port is guaranteed to be delivered before thisbadargexception occurs.badarg— if the process identified by Pid is not an existing local process.
⭐ port_control/3 ⭐
port_control(Port, Operation, Data) -> iodata() | binary()
when
Port :: port() | atom(),
Operation :: integer(),
Data :: iodata().
Performs a synchronous control operation on a port. the meaning of Operation and Data depends on the port, that is, on the port driver. not all port drivers support this control feature 🙈 so like, check first bestie.
Returns a list of integers in the range 0..255, or a binary, depending on the port driver. Lowkey the port driver decides everything here — and what the returned data even means? Also up to the port driver. Yeah, the vibes are entirely the driver's.
Failures (aka the ways this can go 💀):
badarg— ifPortis not an open port, or the registered name of an open port.badarg— ifOperationcannot fit in a 32-bit integer.badarg— if the port driver does not support synchronous control operations.badarg— if the port driver so decides, for any reason whatsoever (probably something's wrong withOperationorData).
WARNING: Do not callport_control/3with an unknownPortidentifier and expect abadargexception. Any undefined behavior is possible (including node crash) depending on how the port driver interprets the supplied arguments. Bestie, this is not a vibe check you want to fail. 🙈
🦋 port_info/1 🦋
port_info(Port) -> Result
when
Port :: port() | atom(),
ResultItem ::
{registered_name, RegisteredName :: atom()} |
{id, Index :: non_neg_integer()} |
{connected, Pid :: pid()} |
{links, Pids :: [pid()]} |
{name, String :: string()} |
{input, Bytes :: non_neg_integer()} |
{output, Bytes :: non_neg_integer()} |
{os_pid,
OsPid :: non_neg_integer() | undefined},
Result :: [ResultItem] | undefined.
Returns a list of tuples stuffed with info about Port — or undefined if the port is not open. 🫶
The order of those tuples is undefined, and ngl, none of the tuples are mandatory either. And if the port is closed and the calling process was previously linked to it? The exit signal from the port is guaranteed to be delivered before port_info/1 returns undefined. No racing, slay. ✨
The result contains info about these Items:
registered_name(only if the port has a registered name)idconnectedlinksnameinputoutput
Want the tea on what each of those Items actually means? See port_info/2. 👑
Failure: badarg if Port is not a local port identifier, or an atom.
💅 port_info/2 💅
port_info(Port, Item :: connected) -> {connected, Pid} | undefined
when Port :: port() | atom(), Pid :: pid();
(Port, Item :: id) -> {id, Index} | undefined
when
Port :: port() | atom(),
Index :: non_neg_integer();
(Port, Item :: input) -> {input, Bytes} | undefined
when
Port :: port() | atom(),
Bytes :: non_neg_integer();
(Port, Item :: links) -> {links, Pids} | undefined
when Port :: port() | atom(), Pids :: [pid()];
(Port, Item :: locking) -> {locking, Locking} | undefined
when
Port :: port() | atom(),
Locking :: false | port_level | driver_level;
(Port, Item :: memory) -> {memory, Bytes} | undefined
when
Port :: port() | atom(),
Bytes :: non_neg_integer();
(Port, Item :: monitors) ->
{monitors, Monitors} | undefined
when
Port :: port() | atom(),
Monitors :: [{process, pid()}];
(Port, Item :: monitored_by) ->
{monitored_by, MonitoredBy} | undefined
when
Port :: port() | atom(), MonitoredBy :: [pid()];
(Port, Item :: name) -> {name, Name} | undefined
when Port :: port() | atom(), Name :: string();
(Port, Item :: os_pid) -> {os_pid, OsPid} | undefined
when
Port :: port() | atom(),
OsPid :: non_neg_integer() | undefined;
(Port, Item :: output) -> {output, Bytes} | undefined
when
Port :: port() | atom(),
Bytes :: non_neg_integer();
(Port, Item :: parallelism) ->
{parallelism, Boolean} | undefined
when Port :: port() | atom(), Boolean :: boolean();
(Port, Item :: queue_size) ->
{queue_size, Bytes} | undefined
when
Port :: port() | atom(),
Bytes :: non_neg_integer();
(Port, Item :: registered_name) ->
{registered_name, RegisteredName} | [] | undefined
when
Port :: port() | atom(), RegisteredName :: atom().
Returns info about Port. 🎀
If the port identified by Port is not open, undefined is returned. And if the port is closed while the calling process was previously linked to it, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined. Iconic, no cap.
Item is one of the following, and you use it to pull whatever particular info you're nosy about:
connected— returns{connected, Pid}, wherePidis the process identifier of the process connected to the port.id— returns{id, Index}, whereIndexis the internal index of the port. This index can be used to separate ports. (Yes, it's giving ✨unique identifier✨.)input— returns{input, Bytes}, whereBytesis the total number of bytes read from the port.links— returns{links, Pids}, wherePidsis a list of the process identifiers of the processes that the port is linked to.locking— returns{locking, Locking}, whereLockingis one of the following:port_level(port-specific locking)driver_level(driver-specific locking)
Heads up though: these results are highly implementation-specific and can change in a future release. So like, don't get too attached. 😭
Since: OTP R16B
memory— returns{memory, Bytes}, whereBytesis the total number of bytes allocated for this port by the runtime system. The port itself can have allocated memory that is not included inBytes. Sneaky little extra memory, not our problem. 💀
Since: OTP R16B
monitors— returns{monitors, Monitors}, whereMonitorsrepresent processes monitored by this port.
Since: OTP R16B
monitored_by— returns{monitored_by, MonitoredBy}, whereMonitoredByis a list of pids that are monitoring the given port at the moment.
Since: OTP 19.0
name— returns{name, Name}, whereNameis the command name set byopen_port/2.os_pid— returns{os_pid, OsPid}, whereOsPidis the process identifier (or equivalent) of an OS process created withopen_port({spawn | spawn_executable, Command}, Options). If the port is not the result of spawning an OS process, the value isundefined.
Since: OTP R16B
output— returns{output, Bytes}, whereBytesis the total number of bytes written to the port from Erlang processes usingport_command/2,port_command/3, orPort ! {Owner, {command, Data}}.parallelism— returns{parallelism, Boolean}, whereBooleancorresponds to the port parallelism hint used by this port. For more info, see optionparallelismofopen_port/2.
Since: OTP R16B
queue_size— returns{queue_size, Bytes}, whereBytesis the total number of bytes queued by the port using the ERTS driver queue implementation.
Since: OTP R16B
registered_name— returns{registered_name, RegisteredName}, whereRegisteredNameis the registered name of the port. If the port has no registered name,[]is returned. Yeah, an empty list. That's just how it is, bestie. 💜
Failure: badarg if Port is not a local port identifier, or an atom.
🌈 port_to_list/1 🌈
port_to_list(Port) -> string() when Port :: port().
Returns a string corresponding to the text representation of the port identifier Port. She's textual, she's iconic. 👑
✨ Examples ✨
1> erlang:port_to_list(#Port<0.0>).
"#Port<0.0>"
Look at her go. 🎀
🦋 ports/0 🦋
ports() -> [port()].
Returns a list of port identifiers corresponding to all the ports existing on the local node. The whole roster, fr fr. 🌸
Heads up though: notice that an exiting port exists, but is not open. She's leaving but she's still in the building. 💅
⭐ pre_loaded/0 ⭐
pre_loaded() -> [module()].
Returns a list of Erlang modules that are preloaded in the runtime system. 🫶
Pre-loaded modules are Erlang modules that are needed to bootstrap the system to load the first Erlang modules from either disk, or by using erl_boot_server. The OGs that get the party started. 👑
💀 process_display/2 💀
process_display(Pid, Type) -> true
when Pid :: pid(), Type :: backtrace.
Writes information about the local process Pid on standard error. 📢
The only allowed value for the atom Type is backtrace, which shows the contents of the call stack, including information about the call chain, with the current function printed first. The format of the output is not further defined. Not further defined, bestie — take what you get and enjoy the vibes. 🙈
okay bestie, buckle up, because process_flag/2 is a whole ✨*menu*✨ and the spec alone is giving "I contain multitudes":
process_flag(async_dist, Boolean) -> OldBoolean
when Boolean :: boolean(), OldBoolean :: boolean();
(trap_exit, Boolean) -> OldBoolean
when Boolean :: boolean(), OldBoolean :: boolean();
(error_handler, Module) -> OldModule
when Module :: atom(), OldModule :: atom();
(fullsweep_after, FullsweepAfter) -> OldFullsweepAfter
when FullsweepAfter :: non_neg_integer(),
OldFullsweepAfter :: non_neg_integer();
(min_heap_size, MinHeapSize) -> OldMinHeapSize
when MinHeapSize :: non_neg_integer(),
OldMinHeapSize :: non_neg_integer();
(min_bin_vheap_size, MinBinVHeapSize) -> OldMinBinVHeapSize
when MinBinVHeapSize :: non_neg_integer(),
OldMinBinVHeapSize :: non_neg_integer();
(max_heap_size, MaxHeapSize) -> OldMaxHeapSize
when MaxHeapSize :: max_heap_size(),
OldMaxHeapSize :: max_heap_size();
(message_queue_data, MQD) -> OldMQD
when MQD :: message_queue_data(),
OldMQD :: message_queue_data();
(priority, Level) -> OldLevel
when Level :: priority_level(),
OldLevel :: priority_level();
(save_calls, N) -> OldN
when N :: 0..10000, OldN :: 0..10000;
(sensitive, Boolean) -> OldBoolean
when Boolean :: boolean(), OldBoolean :: boolean();
({monitor_nodes, term()}, term()) -> term();
(monitor_nodes, term()) -> term().
So basically you tell it which flag you want and what value it should be, and it sets that flag on the calling process, then hands you back the previous value of that flag. Like a lil "here's what it was before, you're welcome." 💅
Flag is one of these, and yes, we're going through all of them:
process_flag(async_dist, boolean())— turns fully asynchronous distributed signaling on or off for the calling process.
When it's disabled (which is the default, btw), a process that sends a distributed signal will block in the send operation if the buffer for the distribution channel hits the distribution buffer busy limit. It just sits there, blocked, until the buffer shrinks back down enough. And lowkey? That can take a substantial amount of time in some cases. 😭
When async_dist is enabled, send operations of distributed signals will always buffer the signal on the outgoing distribution channel and then immediately return. So those sends will never block the sending process. slay ✨
NOTE: because no flow control is enforced by the runtime system when theasync_distprocess flag is enabled, YOU need to make sure that flow control for that data is actually implemented — or that the amount of such data is known to always be limited. Unlimited signaling withasync_distenabled, in the absence of flow control, will typically cause the sending runtime system to crash on an out of memory condition. 💀 fr fr.
Blocking due to disabled async_dist can be monitored by trace:system() using the busy_dist_port option. Only data buffered by processes which (at the time of sending a signal) have disabled async_dist will be counted when determining whether or not an operation should block the caller. noted. 📝
The async_dist flag can also be set on a new process when spawning it using the spawn_opt() BIF with the option {async_dist, Enable}. And the default async_dist flag to use on newly spawned processes can be set by passing the command line argument +pad <boolean> when starting the runtime system. If the +pad <boolean> command line argument is not passed, the default value of the async_dist flag will be false.
You can inspect the state of the async_dist process flag of a process by calling process_info(Pid, async_dist). peek 👀
process_flag(trap_exit, boolean())— whentrap_exitistrue, exit signals arriving to a process get converted into{'EXIT', From, Reason}messages, which you can then receive as ordinary messages like nothing happened. 🎀 Iftrap_exitisfalse, the process exits if it receives an exit signal other thannormal, and that exit signal is propagated to its linked processes. Application processes are normally not supposed to trap exits, just so you know.
See also exit_signal/2.
process_flag(error_handler, module())— lets a process redefine theerror_handlerfor undefined function calls and undefined registered processes. Use this flag with substantial caution, because code auto-loading depends on the correct operation of the error handling module. like, don't be reckless with this one bestie 🫶process_flag(fullsweep_after, non_neg_integer())— changes the maximum number of generational collections before forcing a fullsweep for the calling process.process_flag(min_heap_size, non_neg_integer())— changes the minimum heap size for the calling process.process_flag(min_bin_vheap_size, non_neg_integer())— changes the minimum binary virtual heap size for the calling process.process_flag(max_heap_size, max_heap_size())— sets the maximum heap size for the calling process. IfMaxHeapSizeis an integer, the system default values forkillanderror_loggerare used.
For details on how the heap grows, see Sizing the heap in the ERTS internal documentation.
size— the maximum size in words of the process. If set to zero, the heap size limit is disabled.badargis be thrown if the value is smaller thanmin_heap_size. Heads up: the size check is only done when a garbage collection is triggered.
size is the entire heap of the process when garbage collection is triggered. That includes all generational heaps, the process stack, any messages that are considered to be part of the heap, and any extra memory that the garbage collector needs during collection.
size is the same as can be retrieved using erlang:process_info(Pid, total_heap_size), or by adding heap_block_size, old_heap_block_size and mbuf_size from erlang:process_info(Pid, garbage_collection_info). math checks out 📐
kill— when set totrue, the runtime system sends an untrappable exit signal with reasonkillto the process if the maximum heap size is reached. The garbage collection that triggered the kill is not completed; instead the process exits as soon as possible. When set tofalse, no exit signal is sent to the process, and instead it continues executing.
If kill is not defined in the map, the system default will be used. The default system default is true. It can be changed by either option +hmaxk in erl, or erlang:system_flag(max_heap_size, MaxHeapSize).
error_logger— when set totrue, the runtime system logs an error event vialogger, containing details about the process when the maximum heap size is reached. One log event is sent each time the limit is reached.
If error_logger is not defined in the map, the system default is used. The default system default is true. It can be changed by either the option +hmaxel int erl, or erlang:system_flag(max_heap_size, MaxHeapSize).
include_shared_binaries— when set totrue, off-heap binaries are included in the total sum compared against the size limit. Off-heap binaries are typically larger binaries that may be shared between processes. The size of a shared binary is included by all processes that are referring it. Also, the entire size of a large binary may be included even if only a smaller part of it is referred by the process. yeah. that's the tea ☕
If include_shared_binaries is not defined in the map, the system default is used. The default system default is false. It can be changed by either the option +hmaxib in erl, or erlang:system_flag(max_heap_size, MaxHeapSize).
The heap size of a process is quite hard to predict, especially the amount of memory that is used during the garbage collection. When contemplating using this option, it is recommended to first run it in production with kill set to false and inspect the log events to see what the normal peak sizes of the processes in the system is, and then tune the value accordingly. vibes first, numbers second 📊
process_flag(message_queue_data, message_queue_data())— determines how messages in the message queue are stored, as follows:off_heap— all messages in the message queue will be stored outside the process heap. This implies that no messages in the message queue will be part of a garbage collection of the process. squeaky clean 🧼on_heap— all messages in the message queue will eventually be placed on the process heap. They can, however, be temporarily stored off the heap. This is how messages have always been stored up until ERTS 8.0. the classic way 🎀
The default value of the message_queue_data process flag is determined by the command-line argument +hmqd in erl.
Okay so the rest of that message_queue_data tea: if a process might pile up a huge number of messages in its queue, bestie, set the flag value to off_heap. Why? Because garbage collection of a process sitting on a big old heap full of messages can get extremely expensive and that process can eat up large amounts of memory. That said, the actual message passing performance is generally better when the flag value is on_heap. Trade-offs, we love them 💅
Changing the flag value causes any existing messages to be moved. The move operation is initiated, but not necessarily completed, by the time the function returns. So like, don't assume it's done-done, okay?
process_flag(priority, priority_level())— sets the process priority 🎀 Level is an atom. Four priority levels exist:low,normal,high, andmax. Default isnormal.
NOTE: priority level max is reserved for internal use in the Erlang runtime system, and is not to be used by others. Hands off, that's not yours 🙈
Internally in each priority level, processes are scheduled in a round robin fashion.
Execution of processes on priority normal and low are interleaved. Processes on priority low are selected for execution less frequently than processes on priority normal.
When runnable processes on priority high exist, no processes on priority low or normal are selected for execution. Notice however that this does not mean that no processes on priority low or normal can run when processes are running on priority high. When using multiple schedulers, more processes can be running in parallel than processes on priority high. That is, a low and a high priority process can execute at the same time 👀
When runnable processes on priority max exist, no processes on priority low, normal, or high are selected for execution. As with priority high, processes on lower priorities can execute in parallel with processes on priority max.
Scheduling is pre-emptive. Regardless of priority, a process is pre-empted when it has consumed more than a certain number of reductions since the last time it was selected for execution.
NOTE: do not depend on the scheduling to remain exactly as it is today. Scheduling is likely to be changed in a future release to use available processor cores better. It's giving moving target, fr fr.
There is no automatic mechanism for avoiding priority inversion, such as priority inheritance or priority ceilings. When using priorities, take this into account and handle such scenarios by yourself. You're the main character here, you handle it 💪
Making calls from a high priority process into code that you have no control over can cause the high priority process to wait for a process with lower priority. That is, effectively decreasing the priority of the high priority process during the call. Even if this is not the case with one version of the code that you have no control over, it can be the case in a future version of it 😭 This can, for example, occur if a high priority process triggers code loading, as the code server runs on priority normal.
Other priorities than normal are normally not needed. When other priorities are used, use them with care, especially priority high. A process on priority high is only to perform work for short periods. Busy looping for long periods in a high priority process causes most likely problems, as important OTP servers run on priority normal. So like, don't make the important servers sad 🌸
process_flag(save_calls, 0..10000)—Nmust be an integer in the interval0..10000. IfN > 0, call saving is made active for the process. This means that information about theNmost recent global function calls, BIF calls, sends, and receives made by the process are saved in a list, which can be retrieved withprocess_info(Pid, last_calls). A global function call is one in which the module of the function is explicitly mentioned. Only a fixed amount of information is saved, as follows:- tuple
{Module, Function, Arity}for function calls - The atoms
send,'receive', andtimeoutfor sends and receives ('receive'when a message is received andtimeoutwhen a receive times out)
- tuple
If N = 0, call saving is disabled for the process, which is the default. Whenever the size of the call saving list is set, its contents are reset.
process_flag(sensitive, boolean())— sets or clears flagsensitivefor the current process. When a process has been marked as sensitive by callingprocess_flag(sensitive, true), features in the runtime system that can be used for examining the data or inner working of the process are silently disabled. Spooky but make it private ✨
Features that are disabled include (but are not limited to) the following:
- Tracing. Trace flags can still be set for the process, but no trace messages of any kind are generated. (If flag
sensitiveis turned off, trace messages are again generated if any trace flags are set.) - Sequential tracing. The sequential trace token is propagated as usual, but no sequential trace messages are generated.
process_info/1,2 cannot be used to read out the message queue or the process dictionary (both are returned as empty lists).
Stack back-traces cannot be displayed for the process.
In crash dumps, the stack, messages, and the process dictionary are omitted.
If {save_calls,N} has been set for the process, no function calls are saved to the call saving list. (The call saving list is not cleared. Also, send, receive, and time-out events are still added to the list.) Not me pointing out that those events are still slipping through 🙈
process_flag(Pid, Flag, Value) -> OldValue
when
Pid :: pid(),
Flag :: save_calls,
Value :: non_neg_integer(),
OldValue :: non_neg_integer().
Sets certain flags for the process Pid, in the same manner as process_flag/2. Returns the old value of the flag. The valid values for Flag are only a subset of those allowed in process_flag/2, namely save_calls. Yeah, only that one. Sorry bestie 🫶
Failure: badarg if Pid is not a local process.
process_info(Pid) -> Info
when
Pid :: pid(),
Info :: [InfoTuple] | undefined,
InfoTuple :: process_info_result_item().
Returns a list containing InfoTuples with miscellaneous information about the process identified by Pid, or undefined if the process is not alive.
The order of the InfoTuples is undefined and all InfoTuples are not mandatory. The InfoTuples part of the result can be changed without prior notice. So like, don't get attached to the order, okay? 💀
The InfoTuples with the following items are part of the result:
current_functioninitial_callstatusmessage_queue_lenlinksdictionarytrap_exiterror_handlerprioritygroup_leadertotal_heap_sizeheap_sizestack_sizereductionsgarbage_collection
If the process identified by Pid has a registered name, also an InfoTuple with item registered_name is included.
For information about specific InfoTuples, see process_info/2.
WARNING: this BIF is intended for debugging only. For all other purposes, use process_info/2. Like, for real, use the other one 🔥
Failure: badarg if Pid is not a local process.
process_info(Pid, Item) -> InfoTuple | [] | undefined
when
Pid :: pid(),
Item :: process_info_item(),
InfoTuple :: process_info_result_item();
(Pid, ItemList) -> InfoTupleList | [] | undefined
when
Pid :: pid(),
ItemList :: [Item],
Item :: process_info_item(),
InfoTupleList :: [InfoTuple],
InfoTuple :: process_info_result_item().
Returns information about the process identified by Pid, as specified by Item or ItemList. Returns undefined if the process is not alive.
If the process is alive and a single Item is specified, the returned value is the corresponding InfoTuple, unless Item =:= registered_name and the process has no registered name. In this case, [] is returned. This strange behavior is because of historical reasons, and is kept for backward compatibility. OK so it's weird but it's our weird, we're keeping it 💅
If ItemList is specified, the result is InfoTupleList. The InfoTuples in InfoTupleList are included with the corresponding Items in the same order as the Items were included in ItemList. Valid Items can be included multiple times in ItemList. Duplicates? Sure, why not 🎀
Getting process information follows the signal ordering guarantees described in the Processes Chapter in the Erlang Reference Manual.
NOTE: ifregistered_nameis part ofItemListand the process has no name registered, a{registered_name, []}InfoTuplewill be included in the resultingInfoTupleList. This behavior is different when a singleItem =:= registered_nameis specified, and whenprocess_info/1is used. Yes bestie, three different behaviors. Chemistry 🧪
Valid InfoTuples with corresponding Items:
{async_dist, Enabled}
Current value of the async_dist process flag.
Since: OTP 25.3
{backtrace, Bin}
Binary Bin contains the same information as the output from erlang:process_display(Pid, backtrace). Use binary_to_list/1 to obtain the string of characters from the binary.
{binary, BinInfo}
So basically, BinInfo is a lil list stuffed with miscellaneous deets about the binaries chillin' on this process's heap. Heads up tho: this InfoTuple can get changed or straight-up deleted with zero prior notice, so don't get attached 🥲. In the current implementation, BinInfo is a list of tuples, and those tuples contain; BinaryId, BinarySize, BinaryRefcCount.
Depending on what the message_queue_data process flag is set to, the message queue may be stored on the heap. slay.
{catchlevel, CatchLevel}—CatchLevelis how many catches are currently active in this process. Fair warning bestie: thisInfoTuplecan be changed or removed without prior notice.{current_function, {Module, Function, Arity} | undefined}—Module,Function,Arityis the current function call of this process. The valueundefinedcan be returned if the process is currently executing native compiled code.{current_location, {Module, Function, Arity, Location}}—Module,Function,Arityis the current function call of the process.Locationis a list of two-tuples describing the location in the source code.{current_stacktrace, Stack}— Returns the current call stack back-trace (stacktrace) of the process. The stack has the same format as in the catch part of atry. See The call-stack back trace (stacktrace). The depth of the stacktrace is truncated according to thebacktrace_depthsystem flag setting.{dictionary, Dictionary}—Dictionaryis the process dictionary.{{dictionary, Key}, Value}—Valueassociated withKeyin the process dictionary.{error_handler, Module}—Moduleis theerror_handlermodule used by the process (for undefined function calls, for example).{garbage_collection, GCInfo}—GCInfois a list holding miscellaneous info about garbage collection for this process. The content ofGCInfocan be changed without prior notice.{garbage_collection_info, GCInfo}—GCInfois a list holding miscellaneous detailed info about garbage collection for this process. The content ofGCInfocan be changed without prior notice. For details about the meaning of each item, seegc_minor_startintrace:process/4.{group_leader, GroupLeader}—GroupLeaderis the group leader for the I/O of the process.{heap_size, Size}—Sizeis the size in words of the youngest heap generation of the process. This generation includes the process stack. This information is highly implementation-dependent, and can change if the implementation changes.{initial_call, {Module, Function, Arity}}—Module,Function,Arityis the initial function call with which the process was spawned.{links, PidsAndPorts}—PidsAndPortsis a list of process identifiers and port identifiers, with processes or ports to which the process has a link.{label, Label}—Labelis the label for the process. Seeproc_lib:get_label/1.
Since: OTP 27.2
{last_calls, false|Calls}— The value isfalseif call saving is not active for the process (seeprocess_flag/3). If call saving is active, a list is returned, in which the last element is the most recent called. 👑{memory, Size}—Sizeis the size in bytes of the process. This includes call stack, heap, and internal structures.{message_queue_len, MessageQueueLen}—MessageQueueLenis the number of messages currently sitting in the message queue of the process. This is the length of the listMessageQueuereturned as the information itemmessages(see below).{messages, MessageQueue}—MessageQueueis a list of the messages to the process, which have not yet been processed.{min_heap_size, MinHeapSize}—MinHeapSizeis the minimum heap size for the process.{min_bin_vheap_size, MinBinVHeapSize}—MinBinVHeapSizeis the minimum binary virtual heap size for the process.{monitored_by, MonitoredBy}— A list of identifiers for all the processes, ports and NIF resources, that are monitoring the process.{monitors, Monitors}— A list of monitors (started bymonitor/2) that are active for the process. For a local process monitor or a remote process monitor by a process identifier, the list consists of:{process, Pid}— Process is monitored by pid.{process, {RegName, Node}}— Local or remote process is monitored by name.{port, PortId}— Local port is monitored by port id.{port, {RegName, Node}}— Local port is monitored by name. Please note, that remote port monitors are not supported, soNodewill always be the local node name.
{message_queue_data, MQD}—MQDis the current value of themessage_queue_dataprocess flag, which can be eitheroff_heaporon_heap. For more information, see the documentation ofprocess_flag(message_queue_data, MQD).{parent, Pid}—Pidis the identifier of the parent process, the one that spawned current process. When the process does not have a parentundefinedis returned. Only the initial process (init) on a node lacks a parent, though.
Since: OTP 25.0
{priority, Level}—Levelis the current priority level for the process. For more information on priorities, seeprocess_flag(priority, Level).{priority_messages, Enabled}— Since OTP 28.0
If Enabled equals true, the process has enabled priority message reception for at least one type of messages.
For more information see the Adding Messages to the Message Queue section of the Erlang Reference Manual.
{reductions, Number}—Numberis the number of reductions executed by the process.{registered_name, Atom}—Atomis the registered process name. If the process has no registered name, this tuple is not present in the list. sneaky.{sequential_trace_token, [] | SequentialTraceToken}—SequentialTraceTokenis the sequential trace token for the process. ThisInfoTuplecan be changed or removed without prior notice.{stack_size, Size}—Sizeis the stack size, in words, of the process.{status, Status}—Statusis the status of the process and is one of the following:exitinggarbage_collectingwaiting(for a message)runningrunnable(ready to run, but another process is running)suspended(suspended on a "busy" port or by the BIFerlang:suspend_process/1,2)
{suspending, SuspendeeList}—SuspendeeListis a list of{Suspendee, ActiveSuspendCount, OutstandingSuspendCount}tuples.Suspendeeis the process identifier of a process that has been, or is to be, suspended by the process identified byPidthrough the BIFerlang:suspend_process/2orerlang:suspend_process/1.
ActiveSuspendCount is the number of times Suspendee has been suspended by Pid. OutstandingSuspendCount is the number of not yet completed suspend requests sent by Pid, that is:
- If
ActiveSuspendCount =/= 0,Suspendeeis currently in the suspended state. - If
OutstandingSuspendCount =/= 0, optionasynchronousoferlang:suspend_process/2has been used and the suspendee has not yet been suspended byPid.
Notice that ActiveSuspendCount and OutstandingSuspendCount are not the total suspend count on Suspendee, only the parts contributed by Pid.
{total_heap_size, Size}—Sizeis the total size, in words, of all heap fragments of the process. This includes the process stack and any unreceived messages that are considered to be part of the heap.{trace, InternalTraceFlags}—InternalTraceFlagsis an integer representing the internal trace flag for this process. ThisInfoTuplecan be changed or removed without prior notice.{trap_exit, Boolean}—Booleanistrueif the process is trapping exits, otherwisefalse.
Notice that not all implementations support all these Items. so if one's missing, it's not you, it's the implementation 🫶
Failures:
badarg— IfPidis not a local process.badarg— IfItemis an invalid item.
💖 processes() -> [pid()].
Returns a list of process identifiers corresponding to all the processes currently existing on the local node. the whole roster bestie.
Notice that an exiting process exists, but is not alive. That is, is_process_alive/1 returns false for an exiting process, but its process identifier is part of the result returned from processes/0.
Example:
> processes().
[<0.0.0>,<0.2.0>,<0.4.0>,<0.5.0>,<0.7.0>,<0.8.0>]
🦋 processes_iterator() -> processes_iter_ref().
Returns a processes iterator that can be used in processes_next/1.
✨ processes_next(Iter)
processes_next(Iter) -> {Pid, NewIter} | none
when
Iter :: processes_iter_ref(),
NewIter :: processes_iter_ref(),
Pid :: pid().
Returns a 2-tuple, consisting of one process identifier and a new processes iterator. If the process iterator has run out of processes in the process table, none will be returned.
The two major benefits of using the processes_iterator/0/processes_next/1 BIFs instead of using the processes/0 BIF are that they scale better since no locking is needed, and you do not risk getting a huge list allocated on the heap if there are a huge amount of processes alive in the system. no cap, it's giving efficiency 🌈
Example:
> I0 = erlang:processes_iterator(), ok.
ok
> {Pid1, I1} = erlang:processes_next(I0), Pid1.
<0.0.0>,
> {Pid2, I2} = erlang:processes_next(I1), Pid2.
<0.1.0>
NOTE: this BIF has less consistency guarantee thanprocesses/0. Bestie, let that sink in. The process identifiers you get back from consecutive calls of this BIF may not be a consistent snapshot of all elements existing in the table during any of those calls. But — and this is the important bit — if a process is alive beforeprocesses_iterator/0is called, and keeps being alive untilprocesses_next/1returnsnone, then its process identifier is guaranteed to be part of the result returned from one of the calls toprocesses_next/1. That's the contract, and it's the only one you get. 💅
purge_module(Module) -> true when Module :: atom().
Removes old code for Module. Okay so before you even think about using this BIF, you're supposed to call check_process_code/2 first, to confirm that no processes are executing old code in the module. That's the etiquette, okay?? 😤
WARNING: this BIF is intended for the code server (see code) and is not to be used elsewhere. It's giving "staff only" energy fr fr. 🙈
CHANGE: as from ERTS 8.0 (Erlang/OTP 19), any lingering processes that still execute the old code are killed by this function. In earlier versions, such incorrect use could cause much more fatal failures, like emulator crash. So like… no cap, it used to be way worse. 💀
Failure: badarg if there is no old code for Module.
put(Key, Val) -> term() when Key :: term(), Val :: term().
Adds a new Key to the process dictionary, associated with the value Val, and returns undefined. If Key exists, the old value gets deleted and replaced by Val, and the function returns the old value. Iconic trade-in behaviour tbh. ✨
The average time complexity for the current implementation of this function is O(1) and the worst case time complexity is O(N), where N is the number of items in the process dictionary.
For example:
1> X = put(name, walrus).
undefined
2> Y = put(name, carpenter).
walrus
3> Z = get(name).
carpenter
4> erase(name).
5> get(name).
undefined
NOTE: the values stored whenputis evaluated within the scope of acatchare not retracted if athrowis evaluated, or if an error occurs. So don't be out here thinking your state is spotless after a dramatic exit, bestie. 😭
raise(Class, Reason, Stacktrace) -> badarg
when
Class :: error | exit | throw,
Reason :: term(),
Stacktrace :: raise_stacktrace().
Raises an exception of the specified class, reason, and call stack backtrace (stacktrace). We're stirring the pot manually today. 🍓
Class is error, exit, or throw. So, if it were not for the stacktrace, erlang:raise(Class, Reason, Stacktrace) is equivalent to erlang:Class(Reason) (given that Class is a valid class).
Reason can be any term.
Stacktrace is a list as provided in a try-catch clause.
try
...
catch Class:Reason:Stacktrace ->
...
end
That is, a list of four-tuples {Module, Function, Arity | Args, ExtraInfo}, where Module and Function are atoms, and the third element is an integer arity or an argument list. The stacktrace can also contain {Fun, Args, ExtraInfo} tuples, where Fun is a local fun and Args is an argument list.
Element ExtraInfo at the end is optional. Omitting it is equivalent to specifying an empty list. Very chill of it. 🦋
The stacktrace is used as the exception stacktrace for the calling process; it is truncated to the current maximum stacktrace depth.
As evaluating this function causes the process to terminate, it has no return value unless the arguments are invalid, in which case the function returns the error reason badarg. If you want to be sure not to return, you can call:
error(erlang:raise(Class, Reason, Stacktrace))
and hope to distinguish exceptions later. "and hope" — the manpage said it, not me. 🫶
See the reference manual about errors and error handling for more information about exception classes and how to catch exceptions.
read_timer(TimerRef, Options) -> Result | ok
when
TimerRef :: reference(),
Async :: boolean(),
Option :: {async, Async},
Options :: [Option],
Time :: non_neg_integer(),
Result :: Time | false.
Reads the state of a timer that has been created by either erlang:start_timer or erlang:send_after. TimerRef identifies the timer, and was returned by the BIF that created the timer. Vibe check on your timer, let's go. ⏰
Options:
{async, Async}— Asynchronous request for state information.Asyncdefaults tofalse, which causes the operation to be performed synchronously. In this case, theResultis returned byerlang:read_timer. WhenAsyncistrue,erlang:read_timersends an asynchronous request for the state information to the timer service that manages the timer, and then returnsok. A message on the format{read_timer, TimerRef, Result}is sent to the caller oferlang:read_timerwhen the operation has been processed.
More options can be added in the future. Foreshadowing?? 👀
If Result is an integer, it represents the time in milliseconds left until the timer expires.
If Result is false, a timer corresponding to TimerRef could not be found. This because the timer had expired, or been canceled, or because TimerRef never has corresponded to a timer. Even if the timer has expired, it does not tell you whether or not the time-out message has arrived at its destination yet. So don't @ me if the message is still in transit, okay?? 💀
NOTE: the timer service that manages the timer can be co-located with another scheduler than the scheduler that the calling process is executing on. If so, communication with the timer service takes much longer time than if it is located locally. If the calling process is in a critical path, and can do other things while waiting for the result of this operation, you want to use option{async, true}. If using option{async, false}, the calling process is blocked until the operation has been performed. 😴
See also erlang:send_after/4, erlang:start_timer/4, and erlang:cancel_timer/2.
ref_to_list(Ref) -> string() when Ref :: reference().
Returns a string corresponding to the text representation of Ref. Glow-up for your reference, basically. ✨
WARNING: this BIF is intended for debugging and is not to be used in application programs. It's giving "temporary print statement that you forgot to delete" energy. 🙈
Examples
1> ref_to_list(#Ref<0.0.0.0>).
"#Ref<0.0.0.0>"
register(RegName, PidOrPort) -> true
when RegName :: atom(), PidOrPort :: port() | pid().
Registers the name RegName with a process identifier (pid) or a port identifier in the name registry. RegName, which must be an atom, can be used instead of the pid or port identifier in send operator (RegName ! Message) and most other BIFs that take a pid or port identifier as an argument. It's giving nickname energy — now everybody knows them by name. 👑
For example:
1> Pid = spawn(fun() -> receive after infinity -> ok end end).
2> register(db, Pid).
true
The registered name is considered a Directly Visible Erlang Resource and is automatically unregistered when the process terminates. Cleanup queen. 🧹💖
Failures:
badarg— IfPidOrPortis not an existing local process or port.badarg— IfRegNameis already in use.badarg— If the process or port is already registered (already has a name).badarg— IfRegNameis the atomundefined.
registered() -> [RegName] when RegName :: atom().
Returns a list of names that have been registered using register/2. The whole group chat roster, basically. 📋
For example:
> registered().
[code_server, file_server, init, user, my_db]
resume_process(Suspendee) -> true when Suspendee :: pid().
Decreases the suspend count on the process identified by Suspendee. Un-pausing, bestie. ⏯️
Suspendee is previously to have been suspended through erlang:suspend_process/2 or erlang:suspend_process/1 by the process calling erlang:resume_process(Suspendee). When the suspend count on Suspendee reaches zero, Suspendee is resumed, that is, its state is changed from suspended into the state it had before it was suspended.
WARNING: this BIF is intended for debugging only. Leave it be in prod, I'm literally begging. 😭
Failures:
badarg— IfSuspendeeis not a process identifier.badarg— If the process callingerlang:resume_process/1had not previously increased the suspend count on the process identified bySuspendee.badarg— If the process identified bySuspendeeis not alive.
round(Number) -> integer() when Number :: number().
Returns an integer by rounding Number to the nearest integer. Math but make it cute. 🔢
Example:
1> round(42.1).
42
2> round(5.5).
6
3> round(-5.5).
-6
4> round(36028797018963969.0).
36028797018963968
In the last example, round(36028797018963969.0) evaluates to 36028797018963968. The reason for this is that the number 36028797018963969.0 cannot be represented exactly as a float value. Instead, the float literal is represented as 36028797018963968.0, which is the closest number that can be represented exactly as a float value. See Representation of Floating Point Numbers for additional information. Floats out here lying to you, smh. 💀
self() -> pid().
Returns the process identifier of the calling process. Main character moment — it's you. 💅
For example:
> self().
<0.26.0>
send(Dest, Msg) -> Msg
when Dest :: send_destination(), Msg :: term().
Sends a message and returns Msg. This is the same as using the send operator: Dest ! Msg. 📨
Dest can be a remote or local process identifier, an alias, a (local) port, a locally registered name, or a tuple {RegName, Node} for a registered name at another node. So basically, if it has an address, you can send to it. Slay. ✨
So basically: this function throws a badarg run-time error when Dest is an atom name and that name is not registered. And that's it — that's literally the only case where send fails for an unreachable Dest (of correct type, bestie, correct type 💅).
NOTE: for some important tea about distributed signals, go read the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.
✨ send/3 ✨
send(Dest, Msg, Options) -> Res
when
Dest :: send_destination(),
Msg :: term(),
Options :: [nosuspend | noconnect | priority],
Res :: ok | nosuspend | noconnect.
Either it sends the message and returns ok, or it does not send the message and returns something else (see below, bestie 👇). Other than that, it's the exact same energy as erlang:send/2.
For the full detailed explanation and the warnings, go check erlang:send_nosuspend/2,3. 🫶
Options:
nosuspend— if the sender would have to be suspended to do the send, thennosuspendgets returned instead. No suspension, no problem 😌noconnect— if the destination node would have to be auto-connected to do the send,noconnectgets returned instead. Not me auto-connecting, I would literally never 🙈priority— Since OTP 28.0 ✨
Send this message as a priority message. For the receiver to actually handle it as a priority message, this option must be passed and Dest must be an active priority alias. Both things, bestie, it's giving "and" not "or".
If Dest is an active priority alias but this option is not passed, the message gets handled as an ordinary message. Same deal the other way around: if this option is passed but Dest is not an active priority alias → ordinary message. Sorry babe 🎀
WARNING: You very seldom need to resort to using priority messages and you may cause issues instead of solving issues if not used with care. Like, very seldom. Extreme care, fr fr 😭
For more info, see the Adding Messages to the Message Queue and the Enabling Priority Message Reception sections of the Erlang Reference Manual.
NOTE: for some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.
WARNING: As with erlang:send_nosuspend/2,3: use with extreme care. 👑
🦋 send_after/4 🦋
send_after(Time, Dest, Msg, Options) -> TimerRef
when
Time :: integer(),
Dest :: pid() | atom(),
Msg :: term(),
Options :: [Option],
Abs :: boolean(),
Option :: {abs, Abs},
TimerRef :: reference().
Starts a timer ⏰. When the timer expires, the message Msg is sent to the process identified by Dest. Apart from the format of the time-out message, this function works exactly like erlang:start_timer/4. Periodt.
🌈 send_nosuspend/2 🌈
send_nosuspend(Dest, Msg) -> boolean()
when Dest :: send_destination(), Msg :: term().
Send a message without suspending the caller. Iconic behaviour honestly.
Equivalent to erlang:send(Dest, Msg, [nosuspend]), except it returns true if the message was sent and false if the message was not sent because the sender would have had to be suspended. 💀
This function is intended for send operations to an unreliable remote node without ever blocking the sending (Erlang) process. If the connection to the remote node (usually not a real Erlang node, but a node written in C or Java) is overloaded, this function does not send the message and returns false. No cap.
The same thing happens if Dest refers to a local port that is busy. For all other destinations (the ones allowed for the ordinary send operator '!'), this function sends the message and returns true. Slay.
This function is only to be used in rare circumstances where a process communicates with Erlang nodes that can disappear without any trace, causing the TCP buffers and the drivers queue to be over-full before the node is shut down (because of tick time-outs) by net_kernel. The normal reaction to take when this occurs is some kind of premature shutdown of the other node. 😭
Notice that ignoring the return value from this function would result in an unreliable message passing, which is contradictory to the Erlang programming model. The message is not sent if this function returns false. Read the return value, bestie, please. 🙏
In many systems, transient states of overloaded queues are normal. Although this function returns false does not mean that the other node is guaranteed to be non-responsive — it could be a temporary overload. Also, a return value of true does only mean that the message can be sent on the (TCP) channel without blocking; the message is not guaranteed to arrive at the remote node. For a disconnected non-responsive node, the return value is true (mimics the behavior of operator !). The expected behavior and the actions to take when the function returns false are application- and hardware-specific. iykyk 🎀
WARNING: Use with extreme care.
⭐ send_nosuspend/3 ⭐
send_nosuspend(Dest, Msg, Options) -> boolean()
when
Dest :: send_destination(),
Msg :: term(),
Options :: [noconnect].
Equivalent to erlang:send(Dest, Msg, [nosuspend | Options]), but with a Boolean return value. Same drama, different return type 💅
This function behaves like erlang:send_nosuspend/2, but takes a third parameter, a list of options. The only option is noconnect, which makes the function return false if the remote node is not currently reachable by the local node. The normal behavior is to try to connect to the node, which can stall the process during a short period. The use of option noconnect makes it possible to be sure not to get the slightest delay when sending to a remote process. This is especially useful when communicating with nodes that expect to always be the connecting part (that is, nodes written in C or Java). 👑
Whenever the function returns false (either when a suspend would occur or when noconnect was specified and the node was not already connected), the message is guaranteed not to have been sent. Guaranteed. Periodt.
WARNING: Use with extreme care.
🎀 set_cookie/1 🎀
set_cookie(Cookie) -> true when Cookie :: atom().
Sets the magic cookie of the local node to the atom Cookie, which is also the cookie for all nodes that have no explicit cookie set with set_cookie/2 Cookie. Magic cookie bestie, that's the vibe ✨
See section Distributed Erlang in the Erlang Reference Manual in System Documentation for more information.
You can get this value using get_cookie/0.
Failure: function_clause if the local node is not alive. Like, if it's not alive, it's not giving cookie 😭
💜 set_cookie/2 💜
set_cookie(Node, Cookie) -> true
when Node :: node(), Cookie :: atom().
Sets the magic cookie for Node to the atom Cookie. If Node is the local node, the function sets the cookie of all other nodes (that have no explicit cookie set with this function) to Cookie. She's setting cookies for the whole friend group 🍪
See section Distributed Erlang in the Erlang Reference Manual in System Documentation for more information.
You can get this value using get_cookie/1.
Failure: function_clause if the local node is not alive.
🌸 setelement/3 🌸
setelement(Index, Tuple1, Value) -> Tuple2
when
Index :: pos_integer(),
Tuple1 :: tuple(),
Tuple2 :: tuple(),
Value :: term().
Returns a tuple that's a copy of argument Tuple1, with the element specified by integer argument Index (the first element is the element with index 1, bestie — one-indexed, not zero-indexed, don't come at me) replaced by argument Value. Swap-in, no muss no fuss 💅
🌟 Examples 🌟
1> setelement(2, {10, green, bottles}, red).
{10,red,bottles}
🧚 size/1 🧚
size(Item) -> non_neg_integer() when Item :: tuple() | binary().
Returns the number of elements in a tuple or the number of bytes in a binary or bitstring. Two-for-one, we love a versatile icon 🌈
For bitstrings, the number of whole bytes is returned. That is, if the number of bits in the bitstring is not divisible by 8, the resulting number of bytes is rounded down. Rounding down, not up, don't get got by that 😭
See also tuple_size/1, byte_size/1, and bit_size/1.
NOTE: It is recommended to avoid size/1 in new code. She's dated, bestie, we're using the others now 💅
🌸 Examples 🌸
1> size({a, b, c}).
3
2> tuple_size({a, b, c}).
3
3> size(<<11, 22, 33>>).
3
4> byte_size(<<11, 22, 33>>).
3
5> size(<<11, 7:4>>).
1
6> byte_size(<<11, 7:4>>).
2
7> bit_size(<<11, 7:4>>).
12
(Look at that rounding-down in action, cases 5 and 6 are literally giving the whole lesson 🍓)
🫶 spawn/1 🫶
spawn(Fun) -> pid() when Fun :: function().
Returns the process identifier of a new process started by the application of Fun to the empty list []. Otherwise it works like spawn/3. New process, who dis 💫
🦋 spawn/2 🦋
spawn(Node, Fun) -> pid() when Node :: node(), Fun :: function().
Returns the process identifier of a new process started by the application of Fun to the empty list [] on Node. If Node does not exist, a useless pid is returned (rip, useless pid, she did nothing wrong 😭). Otherwise it works like spawn/3.
💖 spawn/3 💖
spawn(Module, Function, Args) -> pid()
when
Module :: module(),
Function :: atom(),
Args :: [term()].
Returns the process identifier of a new process started by the application of Module:Function to Args. The classic. The main character energy ✨
error_handler:undefined_function(Module, Function, Args) is evaluated by the new process if Module:Function/Arity does not exist (where Arity is the length of Args). The error handler can be redefined (see process_flag/2). If error_handler is undefined, or the user has redefined the default error_handler and its replacement is undefined, a failure with reason undef occurs. 💀
Example:
> spawn(speed, regulator, [high_speed, thin_cut]).
<0.13.1>
👑 spawn/4 👑
spawn(Node, Module, Function, Args) -> pid()
when
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: [term()].
okay so the spawn/4 saga continues — this one hands you the process identifier (pid) of a brand new process that gets started by applying Module:Function to Args on Node. If Node doesn't exist? You get back a useless pid 💀 (not the vibe, but it is what it is). Otherwise it works exactly like spawn/3.
spawn_link(Fun) -> pid() when Fun :: fun(() -> term())
Returns the pid of a fresh process, started by applying Fun to the empty list []. A link gets created between the calling process and the new one — atomically, bestie, the link happens in the same breath. Otherwise it works like spawn/3.
spawn_link(Node, Fun) -> pid() when Node :: node(), Fun :: fun(() -> term())
Returns the pid of a new process started by applying Fun to the empty list [] on Node. A link is created between the calling process and the new process, atomically. ✨
If Node doesn't exist, you get a useless pid back and an exit signal with reason noconnection gets sent to the calling process. Otherwise works like spawn/3.
spawn_link(Module, Function, Args) -> pid() when Module :: module(), Function :: atom(), Args :: [term()]
Returns the pid of a new process started by applying Module:Function to Args. A link is created between the calling process and the new process, atomically. Otherwise works like spawn/3.
spawn_link(Node, Module, Function, Args) -> pid() when Node :: node(), Module :: module(), Function :: atom(), Args :: [term()]
Returns the pid of a new process started by applying Module:Function to Args on Node. A link is created between the calling process and the new process, atomically.
Same deal as before if Node doesn't exist — useless pid comes back, and an exit signal with reason noconnection hits the calling process. Otherwise works like spawn/3.
spawn_monitor(Fun) -> {pid(), reference()} when Fun :: function()
Returns the pid of a new process, started by applying Fun to the empty list [], plus a reference for a monitor created on the new process. 🫶 Two-for-one. Otherwise works like spawn/3.
spawn_monitor(Node, Fun) -> {pid(), reference()} when Node :: node(), Fun :: function()
Returns the pid of a new process, started by applying Fun to the empty list [] on the node Node, and a reference for a monitor created to the new process. Otherwise works like spawn/3.
If the node identified byNodedoes not support distributedspawn_monitor(), the call will fail with anotsupexception. 😭 (yeah, rip)
spawn_monitor(Module, Function, Args) -> {pid(), reference()} when Module :: module(), Function :: atom(), Args :: [term()]
A new process is started by the application of Module:Function to Args. The process is monitored at the same time. Returns the process identifier and a reference for the monitor. Otherwise works like spawn/3.
spawn_monitor(Node, Module, Function, Args) -> {pid(), reference()} when Node :: node(), Module :: module(), Function :: atom(), Args :: [term()]
A new process is started by the application of Module:Function to Args on the node Node. The process is monitored at the same time. Returns the pid and a reference for the monitor. Otherwise works like spawn/3.
If the node identified byNodedoes not support distributedspawn_monitor(), the call will fail with anotsupexception. again. 🙈
spawn_opt(Fun, Options) -> pid() | {pid(), reference()} when Fun :: function(), Options :: [spawn_opt_option()]
Returns the pid of a new process started by applying Fun to the empty list []. Otherwise works like spawn_opt/4.
If the option monitor is specified, the newly created process is monitored — and you get back both the pid and the reference for the monitor. 👑
spawn_opt(Node, Fun, Options) -> pid() | {pid(), reference()} when Node :: node(), Fun :: function(), Options :: [monitor | {monitor, [monitor_option()]} | link | OtherOption], OtherOption :: term()
Returns the pid of a new process started by applying Fun to the empty list [] on Node. If Node doesn't exist, a useless pid is returned (classic). Otherwise works like spawn_opt/4.
Valid options depend on what options the node identified by Node supports. A description of valid Options for the local node of the current OTP version can be found in the docs for spawn_opt/4.
spawn_opt(Module, Function, Args, Options) -> Pid | {Pid, MonitorRef} when Module :: module(), Function :: atom(), Args :: [term()], Options :: [spawn_opt_option()], Pid :: pid(), MonitorRef :: reference()
Works like spawn/3, except that an extra option list is specified when the process is being created. 💅
If the option monitor is specified, the newly created process is monitored — and both the pid and reference for the monitor get returned.
Options:
link— sets a link to the parent process (like whatspawn_link/3does).monitor— monitors the new process (likemonitor(process, Pid)does). A{Pid, MonitorRef}tuple gets returned instead of just aPid.{monitor, MonitorOpts}— monitors the new process with options (likemonitor(process, Pid, MonitorOpts)does). A{Pid, MonitorRef}tuple gets returned instead of just aPid.{priority, Level}— sets the priority of the new process. Equivalent to executingprocess_flag(priority, Level)in the start function of the new process, except the priority is set before the process is selected for execution for the first time. For more deets on priorities, seeprocess_flag(priority, Level).{fullsweep_after, Number}— useful only for performance tuning. Do not use this option unless you know there's a problem with execution times or memory consumption, and make sure the option actually improves things.
The Erlang runtime system uses a generational garbage collection scheme, spending an "old heap" for data that has survived at least one garbage collection. When there's no more room on the old heap, a fullsweep garbage collection is done.
Option fullsweep_after makes it possible to specify the maximum number of generational collections before forcing a fullsweep, even if there's room on the old heap. Setting the number to zero disables the generational collection algorithm — meaning all live data gets copied at every garbage collection.
A few cases where it can be useful to change fullsweep_after:
- If binaries that are no longer used should be thrown away as soon as possible. (Set
Numberto zero.) - Processes that mostly have short-lived data get fullsweeped seldom or never — meaning the old heap contains mostly garbage. To ensure a fullsweep occasionally, set
Numberto a suitable value like10or20. - In embedded systems with a limited amount of RAM and no virtual memory, you might want to preserve memory by setting
Numberto zero. (The value can be set globally, seeerlang:system_flag/2.)
{min_heap_size, Size}— useful only for performance tuning. Do not use this option unless you know there's a problem with execution times or memory consumption, and make sure the option actually improves things.
Gives a minimum heap size, in words. Setting this value higher than the system default can speed up some processes because less garbage collection is done. However, setting too high a value can waste memory and slow down the system because of worse data locality. So only use this option for fine-tuning an application and to measure execution time with various Size values.
{min_bin_vheap_size, VSize}— useful only for performance tuning. Do not use this option unless you know there's a problem with execution times or memory consumption, and make sure the option actually improves things.
Gives a minimum binary virtual heap size, in words. Setting this value higher than the system default can speed up some processes because less garbage collection is done. However, setting too high a value can waste memory. So only use this option for fine-tuning an application and to measure execution time with various VSize values.
{max_heap_size, Size}— sets themax_heap_sizeprocess flag. The defaultmax_heap_sizeis determined by command-line argument+hmaxinerl. For more info, see the documentation ofprocess_flag(max_heap_size, Size).{message_queue_data, MQD}— sets the value of themessage_queue_dataprocess flag.MQDcan be eitheroff_heaporon_heap. The default value of themessage_queue_dataprocess flag is determined by the command-line argument+hmqdinerl. For more info, see the documentation ofprocess_flag(message_queue_data, MQD).{async_dist, Enabled}— sets theasync_distprocess flag on the process you're spawning. This one overrides whatever default the command line argument+pad <boolean>set. So like, if the command line said one thing, this option says "no bestie, we're doing it this way" 💅
Since: OTP 25.3 ✨
spawn_opt(Node, Module, Function, Args, Options) ->
pid() | {pid(), reference()}
when
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: [term()],
Options ::
[monitor |
{monitor, [monitor_option()]} |
link | OtherOption],
OtherOption :: term().
Returns the process identifier (pid) of a new process started by the application of Module:Function to Args on Node. On Node, okay? Not here, not there — there 🦋
And if Node doesn't exist? You get back a useless pid. Like a fake number, a vibe with no substance, absolutely nothing behind it 💀 Otherwise it works just like spawn_opt/4.
The valid options depend on what the node over there actually supports, so no promises bestie. If you want the rundown of valid Options for the local node on the current OTP version, go read the docs for spawn_opt/4. iykyk 🎀
spawn_request(Fun) -> ReqId
when Fun :: function(), ReqId :: reference().
Equivalent to the call spawn_request(node(),Fun,[]). That is: a spawn request on the local node, no options, nothing extra. Just vibes 🫶
spawn_request(Fun, Options) -> ReqId
when
Fun :: function(),
Option ::
{reply_tag, ReplyTag} |
{reply, Reply} |
spawn_opt_option(),
ReplyTag :: term(),
Reply :: yes | no | error_only | success_only,
Options :: [Option],
ReqId :: reference();
(Node, Fun) -> ReqId
when
Node :: node(),
Fun :: function(),
ReqId :: reference().
Equivalent to spawn_request(node(),Fun,Options) or spawn_request(Node,Fun,[]) — depends on which arguments you fed it, obviously 💅
So it's either:
- a spawn request on the local node 🏠
- a spawn request with no options. periodt.
spawn_request(Node, Fun, Options) -> ReqId
when
Node :: node(),
Fun :: function(),
Options :: [Option],
Option ::
monitor |
{monitor, [monitor_option()]} |
link |
{reply_tag, ReplyTag} |
{reply, Reply} |
OtherOption,
ReplyTag :: term(),
Reply :: yes | no | error_only | success_only,
OtherOption :: term(),
ReqId :: reference();
(Module, Function, Args) -> ReqId
when
Module :: module(),
Function :: atom(),
Args :: [term()],
ReqId :: reference().
Equivalent to spawn_request(Node,erlang,apply,[Fun,[]],Options)](spawn_request/5) or [spawn_request(node(),Module,Function,Args,[]) — depends on the arguments, babes 🌸
So it's either:
- a spawn request using the fun
Funof arity zero as the entry point 🎯 - a spawn request on the local node with no options.
And heads up — this function will fail with a badarg exception if any of these are true, no cap:
Nodeis not an atom.Funis not a fun of arity zero.Optionsis not a proper list of terms.
spawn_request(Node, Module, Function, Args) -> ReqId
when
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: [term()],
ReqId :: reference();
(Module, Function, Args, Options) -> ReqId
when
Module :: module(),
Function :: atom(),
Args :: [term()],
Option ::
{reply_tag, ReplyTag} |
{reply, Reply} |
spawn_opt_option(),
ReplyTag :: term(),
Reply :: yes | no | error_only | success_only,
Options :: [Option],
ReqId :: reference().
Equivalent to spawn_request(Node,Module,Function,Args,[]) or spawn_request(node(),Module,Function,Args,Options) — guess what, it depends on the arguments 😭
So it's either:
- a spawn request with no options.
- a spawn request on the local node.
spawn_request(Node, Module, Function, Args, Options) -> ReqId
when
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: [term()],
Options :: [Option],
Option ::
monitor |
{monitor, [monitor_option()]} |
link |
{reply_tag, ReplyTag} |
{reply, Reply} |
OtherOption,
ReplyTag :: term(),
Reply :: yes | no | error_only | success_only,
OtherOption :: term(),
ReqId :: reference().
Asynchronously send a spawn request. Returns a request identifier, ReqId. asynchronously — the whole point, she doesn't wait around 💅
If the spawn operation succeeds, a new process is created on the node identified by Node. And when a spawn operation succeeds, the caller will by default be sent a message of the form {ReplyTag, ReqId, ok, Pid} where Pid is the process identifier of the freshly created process. We call this a success message from here on out. ReplyTag is, by default, the atom spawn_reply — unless you changed it with the {reply_tag, ReplyTag} option. The new process gets started by the application of Module:Function to Args. 🦋
The spawn operation can fail either because creation of a new process failed, or because the spawn operation got interrupted by a connection failure. When a spawn operation fails, the caller will by default be sent a message on the form {ReplyTag, ReqId, error, Reason} where Reason is the error reason. We call this an error message from here on out. Right now these spawn error Reasons are defined, but other reasons can appear at any time without prior notice, so don't get comfy 😭
badopt— an invalidOptionwas passed as an argument. And note: different runtime systems may support different options, so what works for your bestie might not work for you 🫠notsup— the node identified byNodedoes not support spawn operations issued byspawn_request(). Rude of it, honestly.noconnection— failure to set up a connection to the node identified byNode, or the connection to that node was lost during the spawn operation. And in the case the connection was lost, a process may or may not have been created. Like, we genuinely do not know. 💀system_limit— could not create a new process due to some system limit being reached. Typically the process table was full. She's full bestie, there's no room 🍓
✨ Valid Options ✨
monitor— in the absence of spawn operation failures, atomically sets up a monitor to the newly created process. That is, exactly as if the calling process had calledmonitor(process, Pid)wherePidis the process identifier of the newly created process. And theReqIdreturned byspawn_request()is also used as the monitor reference, just as if it had been returned frommonitor(process, Pid). 🎀
Note that the monitor will not be activated for the calling process until the spawn operation has succeeded. You also can't demonitor it before the operation has succeeded. A 'DOWN' message for the corresponding monitor is guaranteed not to be delivered before a success message that corresponds to the spawn operation. And if the spawn operation fails, no 'DOWN' message will be delivered. 🫶
If the connection between the nodes involved in the spawn operation is lost during the spawn operation, the spawn operation will fail with an error reason of noconnection. A new process may or may not have been created. 🙈
{monitor, MonitorOpts}— in the absence of spawn operation failures, atomically sets up a monitor to the newly created process. That is, exactly as if the calling process had calledmonitor(process, Pid, MonitorOpts)wherePidis the process identifier of the newly created process. See themonitoroption above for more info, bestie. 💜
Note that the monitor will not be activated for the calling process until the spawn operation has succeeded. For example, if an alias is created using the monitor option, the alias won't be active until the monitor is activated. So like, chill, it's coming ✨
link— in absence of spawn operation failures, atomically sets up a link between the calling process and the newly created process. That is, exactly as if the calling process had calledlink(Pid)wherePidis the process identifier of the newly created process. 🔗
The link will not be activated for the calling process until the spawn operation has succeeded. And the link can not be removed before the operation has succeeded. An exit signal due to the link is guaranteed not to be delivered before a success message that corresponds to the spawn operation. And if the spawn operation fails, no exit signal due to the link will be delivered to the caller of spawn_request(). periodt.
If the connection between the nodes involved in the spawn operation is lost during the spawn operation, the spawn operation will fail with an error reason of noconnection. A new process may or may not have been created. If it has been created, it will be delivered an exit signal with an exit reason of noconnection. 💀
{reply, Reply}— ValidReplyvalues:yes— A spawn reply message will be sent to the caller regardless of whether the operation succeeds or not. If the call tospawn_request()returns without raising an exception and the reply option is set toyes, the caller is guaranteed to be delivered either a success message or an error message. The reply option is by default set toyes. 💖no— No spawn reply message will be sent to the caller when the spawn operation completes. This regardless of whether the operation succeeds or not. 🤐error_only— No spawn reply message will be sent to the caller if the spawn operation succeeds, but an error message will be sent to the caller if the operation fails. 😭success_only— No spawn reply message will be sent to the caller if the spawn operation fails, but a success message will be sent to the caller if the operation succeeds. ✨
{reply_tag, ReplyTag}— Sets the reply tag toReplyTagin the reply message. That is, in the success or error message that is sent to the caller due to the spawn operation. The default reply tag is the atomspawn_reply. 🏷️OtherOption— Other valid options depends on what options are supported by the node identified byNode. A description of other validOptionsfor the local node of current OTP version can be found in the documentation ofspawn_opt/4. 👀
If a spawn reply message is delivered, it is guaranteed to be delivered before any other signals from the newly spawned process are delivered to the process issuing the spawn request. 🧾
This function will fail with a badarg exception if:
Nodeis not an atom.Moduleis not an atom.Functionis not an atom.Argsis not a proper list of terms.Optionsis not a proper list of terms.
Note that not all individual Options are checked when the spawn request is sent. Some Options can only be checked on reception of the request. Therefore an invalid option does not cause a badarg exception, but will cause the spawn operation to fail with an error reason of badopt. 🚩
A spawn request can be abandoned by calling spawn_request_abandon/1. 🏃♀️
NOTE: For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual. 📚
💅 spawn_request_abandon(ReqId :: reference()) -> boolean() 💅
Abandon a previously issued spawn request. ReqId corresponds to a request identifier previously returned by spawn_request() in a call from current process. That is, only the process that has made the request can abandon the request. 🙅♀️
A spawn request can only be successfully abandoned until the spawn request has completed. When a spawn request has been successfully abandoned, the caller will not be effected by future direct effects of the spawn request itself. For example, it will not receive a spawn reply message. The request is however not withdrawn, so a new process may or may not be created due to the request. If a new process is created after the spawn request was abandoned, no monitors nor links will be set up to the caller of spawn_request_abandon/1 due to the spawn request. If the spawn request included the link option, the process created due to this request will be sent an exit signal from its parent with the exit reason abandoned when it is detected that the spawn operation has succeeded. 😵
NOTE: A process created due to a spawn request that has been abandoned may communicate with its parent as any other process. It is only the direct effects on the parent of the actual spawn request, that will be canceled by abandoning a spawn request. 👻
Return values:
true— The spawn request was successfully abandoned. ✅false— No spawn request was abandoned. TheReqIdrequest identifier did not correspond to an outstanding spawn request issued by the calling process. The reason for this is either:ReqIdcorresponds to a spawn request previoulsy made by the calling process. The spawn operation has completed and a spawn reply has already been delivered to the calling process unless the spawn reply was disabled in the request.ReqIddoes not correspond to a spawn request that has been made by the calling process.
This function fail with a badarg exception if ReqId is not a reference. 💥
🎀 split_binary/2 🎀
split_binary(Bin, Pos) -> {binary(), binary()}
when Bin :: binary(), Pos :: non_neg_integer().
Returns a tuple containing the binaries that are the result of splitting Bin into two parts at position Pos. ✂️
This operation is non-destructive. After the operation, there are three binaries altogether. 🧬
🌸 Examples 🌸
1> B = list_to_binary("0123456789").
<<"0123456789">>
2> byte_size(B).
10
3> {B1, B2} = split_binary(B, 3).
{<<"012">>,<<"3456789">>}
4> byte_size(B1).
3
5> byte_size(B2).
7
⏰ start_timer/4 ⏰
start_timer(Time, Dest, Msg, Options) -> TimerRef
when
Time :: integer(),
Dest :: pid() | atom(),
Msg :: term(),
Options :: [Option],
Abs :: boolean(),
Option :: {abs, Abs},
TimerRef :: reference().
Starts a timer. When the timer expires, the message {timeout, TimerRef, Msg} is sent to the process identified by Dest. ⏳
Options:
{abs, false}— This is the default. It means theTimevalue is interpreted as a time in milliseconds relative current Erlang monotonic time. 🕰️{abs, true}— AbsoluteTimevalue. TheTimevalue is interpreted as an absolute Erlang monotonic time in milliseconds. 📅
More Options can be added in the future. 🔮
The absolute point in time, the timer is set to expire on, must be in the interval [erlang:convert_time_unit(erlang:system_info(start_time), native, millisecond), erlang:convert_time_unit(erlang:system_info(end_time), native, millisecond) ]. If a relative time is specified, the Time value is not allowed to be negative. ⚠️
If Dest is a pid/0, it must be a pid/0 of a process created on the current runtime system instance. This process has either terminated or not. If Dest is an atom/0, it is interpreted as the name of a locally registered process. The process referred to by the name is looked up at the time of timer expiration. No error is returned if the name does not refer to a process. 🔍
If Dest is a pid/0, the timer is automatically canceled if the process referred to by the pid/0 is not alive, or if the process exits. This feature was introduced in ERTS 5.4.11. Notice that timers are not automatically canceled when Dest is an atom/0. 🚫
See also erlang:send_after/4, erlang:cancel_timer/2, and erlang:read_timer/2. 👯♀️
For more information on timers in Erlang in general, see the Timers section of the Time and Time Correction in Erlang ERTS User's guide. 📖
Failure: badarg if the arguments do not satisfy the requirements specified here. 💀
statistics(active_tasks) -> [ActiveTasks]
when ActiveTasks :: non_neg_integer();
(active_tasks_all) -> [ActiveTasks]
when ActiveTasks :: non_neg_integer();
(context_switches) -> {ContextSwitches, 0}
when ContextSwitches :: non_neg_integer();
(exact_reductions) ->
{Total_Exact_Reductions,
Exact_Reductions_Since_Last_Call}
when
Total_Exact_Reductions :: non_neg_integer(),
Exact_Reductions_Since_Last_Call ::
non_neg_integer();
(garbage_collection) ->
{Number_of_GCs, Words_Reclaimed, 0}
when
Number_of_GCs :: non_neg_integer(),
Words_Reclaimed :: non_neg_integer();
(io) -> {{input, Input}, {output, Output}}
when
Input :: non_neg_integer(),
Output :: non_neg_integer();
(microstate_accounting) -> [MSAcc_Thread] | undefined
when
MSAcc_Thread ::
#{type := MSAcc_Thread_Type,
id := MSAcc_Thread_Id,
counters := MSAcc_Counters},
MSAcc_Thread_Type ::
async | aux | dirty_io_scheduler |
dirty_cpu_scheduler | poll | scheduler,
MSAcc_Thread_Id :: non_neg_integer(),
MSAcc_Counters ::
#{MSAcc_Thread_State => non_neg_integer()},
MSAcc_Thread_State ::
alloc | aux | bif | busy_wait | check_io |
emulator | ets | gc | gc_fullsweep | nif |
other | port | send | sleep | timers;
(reductions) ->
{Total_Reductions, Reductions_Since_Last_Call}
when
Total_Reductions :: non_neg_integer(),
Reductions_Since_Last_Call :: non_neg_integer();
(run_queue) -> non_neg_integer();
(run_queue_lengths) -> [RunQueueLength]
when RunQueueLength :: non_neg_integer();
(run_queue_lengths_all) -> [RunQueueLength]
when RunQueueLength :: non_neg_integer();
(runtime) -> {Total_Run_Time, Time_Since_Last_Call}
when
Total_Run_Time :: non_neg_integer(),
Time_Since_Last_Call :: non_neg_integer();
(scheduler_wall_time) ->
[{SchedulerId, ActiveTime, TotalTime}] | undefined
when
SchedulerId :: pos_integer(),
ActiveTime :: non_neg_integer(),
TotalTime :: non_neg_integer();
(scheduler_wall_time_all) ->
[{SchedulerId, ActiveTime, TotalTime}] | undefined
when
SchedulerId :: pos_integer(),
ActiveTime :: non_neg_integer(),
TotalTime :: non_neg_integer();
(total_active_tasks) -> ActiveTasks
when ActiveTasks :: non_neg_integer();
(total_active_tasks_all) -> ActiveTasks
when ActiveTasks :: non_neg_integer();
(total_run_queue_lengths) -> TotalRunQueueLengths
when TotalRunQueueLengths :: non_neg_integer();
(total_run_queue_lengths_all) -> TotalRunQueueLengths
when TotalRunQueueLengths :: non_neg_integer();
(wall_clock) ->
{Total_Wallclock_Time,
Wallclock_Time_Since_Last_Call}
when
Total_Wallclock_Time :: non_neg_integer(),
Wallclock_Time_Since_Last_Call ::
non_neg_integer().
okay bestie — this bad boy hands you statistics about the current system. ✨ That's literally the whole vibe.
The flags you can pass are these ones, and no, you can't skip any of them, I'm listing all of them:
statistics(active_tasks) -> [non_neg_integer()]
Same tea as statistics(active_tasks_all), except you don't get any of the info about the dirty IO run queue and its scheduler besties. So like… only the tasks that are expected to be CPU bound show up. 🧚
Available since OTP 18.3
statistics(active_tasks_all) -> [non_neg_integer()]
Gives you a list where each element = the amount of active processes and ports chillin' on each run queue and its associated schedulers. Translation: the number of processes and ports that are ready to run, or that are currently running. 🏃♀️💨
The values for normal run queues and their associated schedulers come first in the list. Element one = scheduler number 1, element two = scheduler 2, and so on, periodt. If dirty scheduler support exists, then an element with the value for the dirty CPU run queue and its associated dirty CPU schedulers comes next, and then as the last element you get the value for the dirty IO run queue and its associated dirty IO schedulers. 🎀
Heads up though: this info is not gathered atomically. So the result isn't guaranteed to be a consistent snapshot of the state — it's just gathered quite efficiently. ngl that's the tradeoff. 🙈
NOTE: Each normal scheduler has one run queue that it manages. If dirty schedulers are supported, all dirty CPU schedulers share one run queue, and all dirty IO schedulers share one run queue. So like… multiple normal run queues, one dirty CPU run queue, one dirty IO run queue. Work cannot migrate between the different types of run queues. Only work in normal run queues can migrate to other normal run queues. You have to take this into account when you're evaluating the result, bestie, otherwise you're gonna read the numbers wrong. 💀
See also statistics(total_active_tasks), statistics(run_queue_lengths), statistics(run_queue_lengths_all), statistics(total_run_queue_lengths), and statistics(total_run_queue_lengths_all).
Available since OTP 20.0
statistics(context_switches) -> {non_neg_integer(), 0}
Returns the total number of context switches since the system started. That's it, that's the whole function. 🦋
statistics(exact_reductions) -> {Total :: non_neg_integer(), SinceLastCall :: non_neg_integer()}
Returns the number of exact reductions.
NOTE:statistics(exact_reductions)is a more expensive operation thanstatistics(reductions). So like… know what you're asking for, queen. 👑
statistics(garbage_collection) -> { NumerOfGCs :: non_neg_integer(), WordsReclaimed :: non_neg_integer(), 0}
Gives you info about garbage collection, like this for example:
> statistics(garbage_collection).
{85,23961,0}
Caveat: this information can be invalid for some implementations. 🫠
statistics(io) -> {{input, non_neg_integer()}, {output, non_neg_integer()}}
Returns Input, which is the total number of bytes received through ports, and Output, which is the total number of bytes output to ports. 🌊
statistics(microstate_accounting) -> [MSAcc_Thread]
Microstate accounting is THE tool for measuring how much time the Erlang runtime system spends doing various tasks. It's designed to be as lightweight as possible, but yeah, some overhead exists when you enable it. It's meant as a profiling tool to help you hunt down performance bottlenecks. To start / stop / reset microstate accounting, use the system flag microstate_accounting. ✨
statistics(microstate_accounting) returns a list of maps representing some of the OS threads inside ERTS. Each map has type and id fields you can use to figure out which thread it is, plus a counters field holding data about how much time has been spent in the various states. 🔍
Example, because obviously:
> erlang:statistics(microstate_accounting).
[#{counters => #{aux => 1899182914,
check_io => 2605863602,
emulator => 45731880463,
gc => 1512206910,
other => 5421338456,
port => 221631,
sleep => 5150294100},
id => 1,
type => scheduler}, ...]
The time unit is the same one os:perf_counter/0 returns. So to convert it to milliseconds, you can do something like this:
lists:map(
fun(#{ counters := Cnt } = M) ->
MsCnt = maps:map(fun(_K, PerfCount) ->
erlang:convert_time_unit(PerfCount, perf_counter, 1000)
end, Cnt),
M#{ counters := MsCnt }
end, erlang:statistics(microstate_accounting)).
Notice that these values are not guaranteed to be the exact time spent in each state. That's because of all the various optimisations done to keep the overhead as small as possible. It's giving "best effort", not "certified truth". 😭
🧚 MSAcc_Thread_Types 🧚
scheduler— The main execution threads that do most of the work. Seeerl +Sfor more details. 👑dirty_cpu_scheduler— The threads for long running cpu intensive work. Seeerl +SDcpufor more details. 🔥dirty_io_scheduler— The threads for long running I/O work. Seeerl +SDiofor more details. 🌸async— Async threads are used by various linked-in drivers (mainly the file drivers) to offload non-CPU intensive work. Seeerl +Afor more details. 🦋
aux— handles all the lil jobs that aren't specifically assigned to a scheduler. someone has to do the odd jobs bestie 💅poll— does the IO polling for the emulator. seeerl +IOtfor the deets.
The following MSAcc_Thread_States are available. all these states are exclusive, meaning a thread literally cannot be in two states at once. so if you add up the numbers of all counters in one thread, you get the total runtime for that thread. math is mathing ✨
aux— time spent handling auxiliary jobs.check_io— time spent checking for new I/O events.emulator— time spent executing Erlang processes.gc— time spent doing garbage collection. when extra states are enabled, this is the time spent doing non-fullsweep garbage collections.other— time spent doing unaccounted things. (mysterious 💀)port— time spent executing ports.sleep— time spent sleeping. me too honestly 😭
More fine-grained MSAcc_Thread_States can be added through configure (such as ./configure --with-microstate-accounting=extra). Enabling these states causes performance degradation when microstate accounting is turned off, and increases the overhead when it is turned on. so like, pick your struggle 🙈
alloc— time spent managing memory. without extra states, this time is spread out over all other states.bif— time spent in BIFs. without extra states, this time is part of theemulatorstate.busy_wait— time spent busy waiting. this is also the state where a scheduler no longer reports that it is active when usingstatistics(scheduler_wall_time). so if you add all other states but this one andsleep, and then divide that by all time in the thread, you should get something very similar to thescheduler_wall_timefraction. without extra states, this time is part of theotherstate.ets— time spent executing ETS BIFs. without extra states, this time is part of theemulatorstate.gc_full— time spent doing fullsweep garbage collection. without extra states, this time is part of thegcstate.nif— time spent in NIFs. without extra states, this time is part of theemulatorstate.send— time spent sending messages (processes only). without extra states, this time is part of theemulatorstate.timers— time spent managing timers. without extra states, this time is part of theotherstate.
The utility module msacc can be used to more easily analyse these statistics. it's giving helpful 🫶
Returns undefined if system flag microstate_accounting is turned off.
The list of thread information is unsorted and can appear in different order between calls. don't come for it, it's just like that.
NOTE: The threads and states are subject to change without any prior notice. no cap, they can switch up on you 💀
Available since OTP 19.0
statistics(reductions) -> {Reductions :: non_neg_integer(), SinceLastCall :: non_neg_integer()}
Returns information about reductions, for example:
> statistics(reductions).
{2046,11}
CHANGE: As from ERTS 5.5 (Erlang/OTP R11B), this value does not include reductions performed in current time slices of currently scheduled processes. if an exact value is wanted, use statistics(exact_reductions). read the fine print bestie 📜
statistics(run_queue) -> non_neg_integer()
Returns the total length of all normal and dirty CPU run queues. that is, queued work that is expected to be CPU bound. the information is gathered atomically. that is, the result is a consistent snapshot of the state, but this operation is much more expensive compared to statistics(total_run_queue_lengths), especially when a large amount of schedulers is used. so like, it's accurate but it costs you 💸
statistics(run_queue_lengths) -> [non_neg_integer()]
Returns the same as statistics(run_queue_lengths_all) with the exception that no information about the dirty IO run queue is part of the result. that is, only run queues with work that is expected to be CPU bound is part of the result.
Available since OTP 18.3
statistics(run_queue_lengths_all) -> [non_neg_integer()]
Returns a list where each element represents the amount of processes and ports ready to run for each run queue. values for normal run queues are located first in the resulting list. the first element corresponds to the normal run queue of scheduler number 1 and so on. if support for dirty schedulers exist, values for the dirty CPU run queue and the dirty IO run queue follow (in that order) at the end. the information is not gathered atomically. that is, the result is not necessarily a consistent snapshot of the state, but instead quite efficiently gathered. fast > perfect, we love to see it 🏃♀️
NOTE: Each normal scheduler has one run queue that it manages. If dirty schedulers are supported, all dirty CPU schedulers share one run queue, and all dirty IO schedulers share one run queue. That is, we have multiple normal run queues, one dirty CPU run queue and one dirty IO run queue. Work can not migrate between the different types of run queues. Only work in normal run queues can migrate to other normal run queues. This has to be taken into account when evaluating the result.
See also statistics(run_queue_lengths), statistics(total_run_queue_lengths_all), statistics(total_run_queue_lengths), statistics(active_tasks), statistics(active_tasks_all), and statistics(total_active_tasks), statistics(total_active_tasks_all).
Available since OTP 20.0
statistics(runtime) -> {Total :: non_neg_integer(), SinceLastCall :: non_neg_integer()}
Returns information about runtime, in milliseconds.
This is the sum of the runtime for all threads in the Erlang runtime system and can therefore be greater than the wall clock time. the math is wild but it's true 🕰️
WARNING: This value might wrap due to limitations in the underlying functionality provided by the operating system that is used. so like, don't trust it past a certain point 💀
Example:
> statistics(runtime).
{1690,1620}
statistics(scheduler_wall_time) -> [{Id :: pos_integer, ActiveTime :: non_neg_integer(), TotalTime :: non_neg_integer()}] | undefined
Returns information describing how much time normal and dirty CPU schedulers in the system have been busy. this value is normally a better indicator of how much load an Erlang node is under instead of looking at the CPU utilization provided by tools such as top or sysstat. this is because scheduler_wall_time also includes time where the scheduler is waiting for some other resource (such as an internal mutex) to be available but does not use the CPU. in order to better understand what a scheduler is busy doing, you can use microstate accounting. it's giving receipts 🧾✨
The definition of a busy scheduler is when it is not idle and not busy waiting for new work, that is:
- Executing process code
- Executing linked-in driver or NIF code
- Executing BIFs, or any other runtime handling
- Garbage collecting
- Handling any other memory management
Notice that a scheduler can also be busy even if the OS has scheduled out the scheduler thread. sneaky but true 👑
NOTE: It is recommended to use the module scheduler instead of this function directly, as it provides an easier way to get the information that you usually want.
If enabled, this function returns a list of tuples with {SchedulerId, ActiveTime, TotalTime}, where SchedulerId is an integer ID of the scheduler, ActiveTime is the duration the scheduler has been busy, and TotalTime is the total time duration since scheduler_wall_time activation for the specific scheduler. the time unit returned is undefined and can be subject to change between releases, OSs, and system restarts. scheduler_wall_time is only to be used to calculate relative values for scheduler utilization. the ActiveTime can never exceed TotalTime. the list of scheduler information is unsorted and can appear in different order between calls.
The disabled this function returns undefined.
The activation time can differ significantly between schedulers. currently dirty schedulers are activated at system start while normal schedulers are activated some time after the scheduler_wall_time functionality is enabled. they're just built different 😭
Only information about schedulers that are expected to handle CPU bound work is included in the return values from this function. if you also want information about dirty I/O schedulers, use statistics(scheduler_wall_time_all) instead.
Normal schedulers will have scheduler identifiers in the range 1 =< SchedulerId =< erlang:system_info(schedulers). Dirty CPU schedulers will have scheduler identifiers in the range erlang:system_info(schedulers) < SchedulerId =< erlang:system_info(schedulers) + erlang:system_info(dirty_cpu_schedulers).
Heads up bestie: the different types of schedulers handle specific types of jobs. Every single job gets assigned to a specific scheduler type. Jobs can migrate between different schedulers of the same type — but ✨never✨ between schedulers of different types. So when you're evaluating the results you get back, keep that little fact in your back pocket, okay? 💅
You can use scheduler_wall_time to calculate scheduler utilization. First you grab a sample of the values returned by erlang:statistics(scheduler_wall_time):
> erlang:system_flag(scheduler_wall_time, true).
false
> Ts0 = lists:sort(erlang:statistics(scheduler_wall_time)), ok.
ok
Some time later the user takes another snapshot and calculates scheduler utilization per scheduler, for example:
> Ts1 = lists:sort(erlang:statistics(scheduler_wall_time)), ok.
ok
> lists:map(fun({{I, A0, T0}, {I, A1, T1}}) ->
{I, (A1 - A0)/(T1 - T0)} end, lists:zip(Ts0,Ts1)).
[{1,0.9743474730177548},
{2,0.9744843782751444},
{3,0.9995902361669045},
{4,0.9738012596572161},
{5,0.9717956667018103},
{6,0.9739235846420741},
{7,0.973237033077876},
{8,0.9741297293248656}]
Using the same snapshots to calculate a total scheduler utilization:
> {A, T} = lists:foldl(fun({{_, A0, T0}, {_, A1, T1}}, {Ai,Ti}) ->
{Ai + (A1 - A0), Ti + (T1 - T0)} end, {0, 0}, lists:zip(Ts0,Ts1)),
TotalSchedulerUtilization = A/T.
0.9769136803764825
Total scheduler utilization will equal 1.0 when all schedulers have been active all the time between the two measurements. Iconic behaviour tbh. 👑
Another (probably more) useful value is to calculate total scheduler utilization weighted against maximum amount of available CPU time:
> WeightedSchedulerUtilization = (TotalSchedulerUtilization
* (erlang:system_info(schedulers)
+ erlang:system_info(dirty_cpu_schedulers)))
/ erlang:system_info(logical_processors_available).
0.9769136803764825
This weighted scheduler utilization will reach 1.0 when schedulers are active the same amount of time as maximum available CPU time. And if more schedulers exist than available logical processors, this value may be greater than 1.0. Not a bug babe, that's just math. 😌
As of ERTS version 9.0, the Erlang runtime system will as default have more schedulers than logical processors. This due to the dirty schedulers.
NOTE:scheduler_wall_timeis by default disabled. To enable it, useerlang:system_flag(scheduler_wall_time, true).
Available since OTP R15B01
statistics(scheduler_wall_time_all) ->
[{Id :: pos_integer,
ActiveTime :: non_neg_integer(),
TotalTime :: non_neg_integer()}] |
undefined
Equivalent to statistics(scheduler_wall_time), except that it also include information about all dirty I/O schedulers. 🧹✨
Dirty IO schedulers will have scheduler identifiers in the range erlang:system_info(schedulers)+erlang:system_info(dirty_cpu_schedulers) < SchedulerId =< erlang:system_info(schedulers) + erlang:system_info(dirty_cpu_schedulers) +erlang:system_info(dirty_io_schedulers).
NOTE: note that work executing on dirty I/O schedulers are expected to mainly wait for I/O. That is, when you get high scheduler utilization on dirty I/O schedulers, CPU utilization is not expected to be high due to this work. So don't panic when you see those numbers, bestie. 🫶
Available since OTP 20.0
statistics(total_active_tasks) -> non_neg_integer()
Equivalent to calling lists:sum(statistics(active_tasks)), but more efficient. Lazy math but make it fast. 💅
Available since OTP 18.3
statistics(total_active_tasks_all) -> non_neg_integer()
Equivalent to calling lists:sum(statistics(active_tasks_all)), but more efficient.
Available since OTP 20.0
statistics(total_run_queue_lengths) -> non_neg_integer()
Equivalent to calling lists:sum(statistics(run_queue_lengths)), but more efficient.
Available since OTP 18.3
statistics(total_run_queue_lengths_all) -> non_neg_integer()
Equivalent to calling lists:sum(statistics(run_queue_lengths_all)), but more efficient.
Available since OTP 20.0
statistics(wall_clock) -> {Total :: non_neg_integer(), SinceLastCall :: non_neg_integer()}
Returns information about wall clock. wall_clock can be used in the same manner as runtime, except that real time is measured as opposed to runtime or CPU time. Clocks are clocking, as they should. ⏰
suspend_process(Suspendee) -> true when Suspendee :: pid().
Suspends the process identified by Suspendee. Equivalent to calling erlang:suspend_process(Suspendee, []).
WARNING: this BIF is intended for debugging only. 🚨
suspend_process(Suspendee, OptList) -> boolean()
when
Suspendee :: pid(),
OptList :: [Opt],
Opt ::
unless_suspending | asynchronous |
{asynchronous, term()}.
Increases the suspend count on the process identified by Suspendee and puts it in the suspended state if it is not already in that state. A suspended process is not scheduled for execution until the process has been resumed. 😴
If the suspended process currently is waiting in a receive ... after expression, the timer for the timeout will, as of OTP 28.0, also be suspended until the process is resumed. BIF timers (see erlang:send_after/3 and erlang:start_timer/3) created using the PID of Suspendee will, as of OTP 29.0, also be suspended until the process is resumed. BIF timers created using a registered name are not affected. iykyk 💅
A process can be suspended by multiple processes and can be suspended multiple times by a single process. A suspended process does not leave the suspended state until its suspend count reaches zero. The suspend count of Suspendee is decreased when erlang:resume_process(Suspendee) is called by the same process that called erlang:suspend_process(Suspendee). All increased suspend counts on other processes acquired by a process are automatically decreased when the process terminates. Very tidy. ✨
Options (Opts):
asynchronous— A suspend request is sent to the process identified bySuspendee.Suspendeeeventually suspends unless it is resumed before it could suspend. The caller oferlang:suspend_process/2returns immediately, regardless of whetherSuspendeehas suspended yet or not. The point in time whenSuspendeesuspends cannot be deduced from other events in the system. It is only guaranteed thatSuspendeeeventually suspends (unless it is resumed). If no asynchronous options has been passed, the caller oferlang:suspend_process/2is blocked untilSuspendeehas suspended. fr fr, patience is a virtue.{asynchronous, ReplyTag}— A suspend request is sent to the process identified bySuspendee. When the suspend request has been processed, a reply message is sent to the caller of this function. The reply is on the form{ReplyTag, State}whereStateis either:exited—Suspendeehas exited. 😭suspended—Suspendeeis now suspended. 🎉not_suspended—Suspendeeis not suspended. This can only happen when the process that issued this request, have calledresume_process(Suspendee)before getting the reply.
Apart from the reply message, the {asynchronous, ReplyTag} option behaves exactly the same as the asynchronous option without reply tag.
unless_suspending— The process identified bySuspendeeis suspended unless the calling process already is suspendingSuspendee. Ifunless_suspendingis combined with optionasynchronous, a suspend request is sent unless the calling process already is suspendingSuspendeeor if a suspend request already has been sent and is in transit. If the calling process already is suspendingSuspendee, or if combined with optionasynchronousand a send request already is in transit,falseis returned and the suspend count onSuspendeeremains unchanged.
If the suspend count on the process identified by Suspendee is increased, true is returned, otherwise false.
WARNING: this BIF is intended for debugging only. 🚨
WARNING: you can easily create deadlocks if processes suspends each other (directly or in circles). In ERTS versions prior to ERTS version 10.0, the runtime system prevented such deadlocks, but this prevention has now been removed due to performance reasons. So like… be careful, bestie. 💀
Failures:
badarg— IfSuspendeeis not a process identifier.badarg— If the process identified bySuspendeeis the same process as the process callingerlang:suspend_process/2.badarg— If the process identified bySuspendeeis not alive.badarg— If the process identified bySuspendeeresides on another node.badarg— IfOptListis not a proper list of validOpts.system_limit— If the process identified bySuspendeehas been suspended more times by the calling process than can be represented by the currently used internal data structures. The system limit is greater than2,000,000,000suspends and will never be lower. That's a lot of suspends, no cap. 🫠
system_flag(backtrace_depth, Depth) -> OldDepth
when
Depth :: non_neg_integer(),
OldDepth :: non_neg_integer();
(cpu_topology, CpuTopology) -> OldCpuTopology
when
CpuTopology :: cpu_topology(),
OldCpuTopology :: cpu_topology();
(dirty_cpu_schedulers_online, DirtyCPUSchedulersOnline)
->
OldDirtyCPUSchedulersOnline
when
DirtyCPUSchedulersOnline :: pos_integer(),
OldDirtyCPUSchedulersOnline :: pos_integer();
(erts_alloc, {Alloc, F, V}) -> ok | notsup
when Alloc :: atom(), F :: atom(), V :: integer();
(fullsweep_after, Number) -> OldNumber
when
Number :: non_neg_integer(),
OldNumber :: non_neg_integer();
(microstate_accounting, Action) -> OldState
when
Action :: true | false | reset,
OldState :: true | false;
(min_heap_size, MinHeapSize) -> OldMinHeapSize
when
MinHeapSize :: non_neg_integer(),
OldMinHeapSize :: non_neg_integer();
(min_bin_vheap_size, MinBinVHeapSize) ->
OldMinBinVHeapSize
when
MinBinVHeapSize :: non_neg_integer(),
OldMinBinVHeapSize :: non_neg_integer();
(max_heap_size, MaxHeapSize) -> OldMaxHeapSize
when
MaxHeapSize :: max_heap_size(),
OldMaxHeapSize :: max_heap_size();
(multi_scheduling, BlockState) -> OldBlockState
when
BlockState ::
block | unblock | block_normal |
unblock_normal,
OldBlockState :: blocked | disabled | enabled;
(outstanding_system_requests_limit, NewLimit) ->
OldLimit
when
NewLimit :: 1..134217727,
OldLimit :: 1..134217727;
(scheduler_bind_type, How) -> OldBindType
when
How :: scheduler_bind_type() | default_bind,
OldBindType :: scheduler_bind_type();
(scheduler_wall_time, Boolean) -> OldBoolean
when Boolean :: boolean(), OldBoolean :: boolean();
(schedulers_online, SchedulersOnline) ->
OldSchedulersOnline
when
SchedulersOnline :: pos_integer(),
OldSchedulersOnline :: pos_integer();
(system_logger, Logger) -> PrevLogger
when
Logger :: logger | undefined | pid(),
PrevLogger :: logger | undefined | pid();
(trace_control_word, TCW) -> OldTCW
when
TCW :: non_neg_integer(),
OldTCW :: non_neg_integer();
(time_offset, finalize) -> OldState
when OldState :: preliminary | final | volatile;
(internal_cpu_topology, term()) -> term();
(sequential_tracer, Tracer) -> PrevTracer | false
when
Tracer ::
pid() | port() | {module(), term()} |
false,
PrevTracer ::
pid() | port() | {module(), term()} |
false;
(reset_seq_trace, true) -> true.
okay so this one sets a system flag to the value you hand it. 💅 That's the whole vibe. But WHICH flags though?? Bestie there are like a million, so let's go one by one. Buckle up. 🎀
Here's the menu of flags you can set:
system_flag(backtrace_depth, non_neg_integer()) -> non_neg_integer()
Sets the max depth of call stack back-traces that show up in the exit reason element of 'EXIT' tuples. This flag also caps the stacktrace depth that process_info/2 hands back for the current_stacktrace item. ✨
Returns the old value of the flag. 🫶
system_flag(cpu_topology, cpu_topology()) -> cpu_topology()
WARNING: this argument is deprecated!! 😭 Instead of using it, use the command-line argument+sctinerl. And when this argument eventually gets removed, a final CPU topology to use is determined at emulator boot time. So like... plan accordingly, bestie.
Sets the user-defined CpuTopology. The user-defined CPU topology overrides any automatically detected CPU topology — main character energy, fr. If you pass undefined as CpuTopology, the system reverts back to the CPU topology it automatically detected. The value it returns is equal to whatever erlang:system_info(cpu_topology) said before the change was made. 🌸
Returns the old value of the flag.
The CPU topology is what gets used when binding schedulers to logical processors. And if schedulers are already bound when you change the CPU topology? The schedulers get sent a request to rebind according to the new CPU topology. Slay, adaptive. 💖
You can also set the user-defined CPU topology by passing the command-line argument +sct to erl.
For info on the type CpuTopology and more, go look at erlang:system_info(cpu_topology) plus the command-line flags +sct and +sbt in erl. iykyk 🦋
system_flag(dirty_cpu_schedulers_online, pos_integer()) -> pos_integer()
Sets how many dirty CPU schedulers are online. Range is 1 <= DirtyCPUSchedulersOnline <= N, where N is the smallest of the return values of erlang:system_info(dirty_cpu_schedulers) and erlang:system_info(schedulers_online).
Returns the old value of the flag.
Plot twist: the number of dirty CPU schedulers online can change if the number of schedulers online changes. Example time — if 12 schedulers and 6 dirty CPU schedulers are online, and you use system_flag/2 to set the number of schedulers online down to 6, then the number of dirty CPU schedulers online automatically gets cut in half too, down to 3. And yeah, it scales the other way as well: the dirty CPU schedulers online increase proportionally to increases in schedulers online. ✨
For more information, see erlang:system_info(dirty_cpu_schedulers) and erlang:system_info(dirty_cpu_schedulers_online).
Available since OTP 17.0 👑
system_flag(erts_alloc, {Alloc :: atom(), F :: atom(), V :: integer()}) -> ok | notsup
Sets system flags for erts_alloc(3). Alloc is the allocator to affect, for example binary_alloc. F is the flag to change, and V is the new value. 🧚
Heads up: only a subset of all erts_alloc flags can be changed at run time. That subset is currently only the flag sbct. periodt.
Returns ok if the flag was set, or notsup if it's not supported by erts_alloc.
Available since OTP 20.2.3 💜
system_flag(fullsweep_after, non_neg_integer()) -> non_neg_integer()
Sets the system flag fullsweep_after. Number is a non-negative integer telling you how many times generational garbage collections can happen without forcing a fullsweep collection. The value applies to new processes — processes already running are not affected, sorry babes. 🙈
Returns the old value of the flag.
On low-memory systems (especially ones without virtual memory), setting the value to 0 can help conserve memory. 🌱
This value can also be set through the (OS) environment variable ERL_FULLSWEEP_AFTER.
system_flag(microstate_accounting, true | false | reset) -> boolean()
Turns microstate accounting measurements on or off. And when you pass reset, all counters get reset to 0. ✨
For more info see statistics(microstate_accounting).
Available since OTP 19.0 🌈
system_flag(min_heap_size, non_neg_integer()) -> non_neg_integer()
Sets the default minimum heap size for processes. The size is specified in words. The new min_heap_size only effects processes spawned after the min_heap_size change has been made — it's not retroactive, bestie. But you can set min_heap_size for individual processes by using spawn_opt/4 or process_flag/2. 🎀
Returns the old value of the flag.
system_flag(min_bin_vheap_size, non_neg_integer()) -> non_neg_integer()
Sets the default minimum binary virtual heap size for processes. Size is, again, specified in words. The new min_bin_vhheap_size only effects processes spawned after the change of min_bin_vheap_size has been made. And min_bin_vheap_size can be set for individual processes by using spawn_opt/2,3,4 or process_flag/2. 💖
Returns the old value of the flag.
Available since OTP R13B04 ⭐
system_flag(max_heap_size, max_heap_size()) -> max_heap_size()
Sets the default maximum heap size settings for processes. The size is specified in words. The new max_heap_size only effects processes spawned after the change has been made. And max_heap_size can be set for individual processes using spawn_opt/2,3,4 or process_flag/2. 😌
Returns the old value of the flag.
For details on how the heap grows, see Sizing the heap in the ERTS internal documentation. 📚
Available since OTP 19.0 🔥
system_flag(multi_scheduling, BlockState) -> OldBlockStatewhenBlockState :: block | unblock | block_normal | unblock_normal,OldBlockState :: blocked | disabled | enabled
If multi-scheduling is on, more than one scheduler thread is being used by the emulator, bestie. Multi-scheduling can be blocked in two totally different ways. Either all schedulers but one get blocked, or all normal schedulers but one get blocked. And when only normal schedulers are blocked? The dirty schedulers are still free to keep scheduling processes, they're out there doing their own thing 💅
If BlockState =:= block, multi-scheduling is blocked. Like, one and only one scheduler thread will execute. Periodt. If BlockState =:= unblock and nobody else is blocking multi-scheduling, and this process has blocked only once, then multi-scheduling is unblocked. Slay.
If BlockState =:= block_normal, normal multi-scheduling is blocked. That is, only one normal scheduler thread will execute, but multiple dirty schedulers can execute. If BlockState =:= unblock_normal and no one else blocks normal multi-scheduling, and this process has blocked only once, normal multi-scheduling is unblocked.
One process can block multi-scheduling and normal multi-scheduling multiple times, no cap. If a process has blocked multiple times, it must unblock exactly as many times as it has blocked before it has released its multi-scheduling block. It's giving "you break it, you buy it" energy 😭 And if a process that has blocked multi-scheduling or normal multi-scheduling exits, it automatically releases its blocking of multi-scheduling and normal multi-scheduling. Iconic cleanup behaviour, honestly.
The return values are disabled, blocked, blocked_normal, or enabled. The returned value describes the state just after the call to erlang:system_flag(multi_scheduling, BlockState) has been made. For info about the return values, see erlang:system_info(multi_scheduling).
NOTE: Blocking of multi-scheduling and normal multi-scheduling is normally not needed. If you feel that you need to use these features, consider it a few more times again. Blocking multi-scheduling is only to be used as a last resort, as it is most likely a very inefficient way to solve the problem. Bestie. Ngl. Don't.
See also erlang:system_info(multi_scheduling), erlang:system_info(normal_multi_scheduling_blockers), erlang:system_info(multi_scheduling_blockers), and erlang:system_info(schedulers).
system_flag(outstanding_system_requests_limit, 1..134217727) -> 1..134217727— sets a limit on the amount of outstanding requests made by a system process orchestrating system wide changes 🎀
Currently there are two such processes:
- The Code Purger — the code purger orchestrates checking of references to old code before old code is removed from the system.
- The Literal Area Collector — the literal area collector orchestrates copying of references from old literal areas before removal of such areas from the system.
Each of these processes are allowed to have as many outstanding requests as this limit is set to. By default this limit is set to twice the amount of schedulers on the system. This will ensure that schedulers will have enough work scheduled to perform these operations as quickly as possible at the same time as other work will be interleaved with this work. The currently used limit can be checked by calling erlang:system_info(outstanding_system_requests_limit).
This limit can also be set by passing the command line argument +zosrl <Limit> to erl.
Available since OTP 24.2 ✨
system_flag(scheduler_bind_type, scheduler_bind_type() | default_bind) -> scheduler_bind_type()— controls if and how schedulers are bound to logical processors 🧚
WARNING: This argument is deprecated. Instead of using this argument, use command-line argument+sbtinerl. When this argument is removed, a final scheduler bind type to use is determined at emulator boot time.
When erlang:system_flag(scheduler_bind_type, How) is called, an asynchronous signal is sent to all schedulers online, causing them to try to bind or unbind as requested.
NOTE: If a scheduler fails to bind, this is often silently ignored, as it is not always possible to verify valid logical processor identifiers. If an error is reported, an error event is logged. To verify that the schedulers have bound as requested, call erlang:system_info(scheduler_bindings).
Schedulers can be bound on newer Linux, Solaris, FreeBSD, and Windows systems, but more systems will be supported in future releases 🦋
In order for the runtime system to be able to bind schedulers, the CPU topology must be known. If the runtime system fails to detect the CPU topology automatically, it can be defined. For more information on how to define the CPU topology, see command-line flag +sct in erl.
The runtime system does by default not bind schedulers to logical processors.
NOTE: If the Erlang runtime system is the only OS process binding threads to logical processors, this improves the performance of the runtime system. However, if other OS processes (for example, another Erlang runtime system) also bind threads to logical processors, there can be a performance penalty instead. Sometimes this performance penalty can be severe. If so, it is recommended to not bind the schedulers. Vibe check your machine first, fr fr.
Schedulers can be bound in different ways. Argument How determines how schedulers are bound and can be any of the following:
unbound— same as command-line argument+sbt uinerl.no_spread— same as command-line argument+sbt nsinerl.thread_spread— same as command-line argument+sbt tsinerl.processor_spread— same as command-line argument+sbt psinerl.spread— same as command-line argument+sbt sinerl.no_node_thread_spread— same as command-line argument+sbt nntsinerl.no_node_processor_spread— same as command-line argument+sbt nnpsinerl.thread_no_node_processor_spread— same as command-line argument+sbt tnnpsinerl.default_bind— same as command-line argument+sbt dbinerl.
The returned value equals How before flag scheduler_bind_type was changed.
Failures 💀:
notsup— if binding of schedulers is not supported.badarg— if How is not one of the documented alternatives.badarg— if CPU topology information is unavailable.
The scheduler bind type can also be set by passing the command-line argument +sbt to erl.
For more information, see erlang:system_info(scheduler_bind_type), erlang:system_info(scheduler_bindings), as well as command-line flags +sbt and +sct in erl.
system_flag(scheduler_wall_time, boolean()) -> boolean()— try to enable or disable scheduler wall time measurements by passing Boolean as eithertrueorfalse🌸
For more information about how to use scheduler wall time measurements, see statistics(scheduler_wall_time).
Scheduler wall time measurements has a node global state. It is either enabled for all processes on the node or disabled for all processes. Each process has a logical counter initialized as zero. A call with Boolean as true will increase that counter one step for the calling process. A call with false will decrease it one step unless it already is zero. The node global state for scheduler_wall_time will be enabled as long as there is at least one process alive with a counter value larger than zero. When a process terminates, its counter will also disappear 😭 To ensure scheduler_wall_time is kept enabled, the process that enabled it must therefore be kept alive. Like, keep your enabling process hydrated and breathing, bestie.
Returns the old value of the node global state, true if scheduler wall time measurements were enabled, false if it were disabled.
Scheduler wall time measurements do consume some cpu overhead and should not be left turned on unless used. Turn it off, it's not a personality trait 🫶
Available since OTP R15B01
system_flag(schedulers_online, pos_integer()) -> pos_integer()— sets the number of schedulers online. The range is1 <= SchedulersOnline <= erlang:system_info(schedulers)👑
Returns the old value of the flag.
If the emulator was built with support for dirty schedulers, changing the number of schedulers online can also change the number of dirty CPU schedulers online. For example, if 12 schedulers and 6 dirty CPU schedulers are online, and system_flag/2 is used to set the number of schedulers online to 6, then the number of dirty CPU schedulers online is automatically decreased by half as well, down to 3. Similarly, the number of dirty CPU schedulers online increases proportionally to increases in the number of schedulers online. They're matching, it's giving coordinated fits 💅
For more information, see erlang:system_info(schedulers) and erlang:system_info(schedulers_online).
system_flag(system_logger, logger | undefined | pid()) -> logger | undefined | pid()— sets the process that will receive the logging messages generated by ERTS. If set toundefined, all logging messages generated by ERTS will be dropped. The messages will be in the format:
{log,Level,Format,ArgList,Metadata} where
Level = atom(),
Format = string(),
ArgList = list(term()),
Metadata = #{ pid => pid(),
group_leader => pid(),
time := logger:timestamp(),
error_logger := #{ emulator := true, tag := atom() }
okay so if the system_logger process dies, this flag gets reset back to logger. 💀
The default is the process named logger.
Returns the old value of the flag.
NOTE: This function is designed to be used by the KERNEL logger. Be careful if you change it to something else as log messages may be lost. If you want to intercept emulator log messages, do it by adding a specialized handler to the KERNEL logger.
Available since OTP 21.2
system_flag(trace_control_word, non_neg_integer()) -> non_neg_integer()— Sets the value of the node trace control word toTCW, which is to be an unsigned integer. For more information, see functionset_tcwin section "Match Specifications in Erlang" in the User's Guide.
Returns the old value of the flag.
system_flag(time_offset, finalize) -> preliminary | final | volatile— Finalizes the time offset when single time warp mode is used. If another time warp mode is used, the time offset state is left unchanged.
Returns the old state identifier, that is:
- If
preliminaryis returned, finalization was performed and the time offset is now final. - If
finalis returned, the time offset was already in the final state. This either because anothererlang:system_flag(time_offset, finalize)call or because no time warp mode is used. - If
volatileis returned, the time offset cannot be finalized because multi-time warp mode is used.
Available since OTP 18.0
system_info(allocated_areas) -> [tuple()];
(allocator) -> {Allocator, Version, Features, Settings}
when
Allocator :: undefined | glibc,
Version :: [non_neg_integer()],
Features :: [atom()],
Settings ::
[{Subsystem :: atom(),
[{Parameter :: atom(), Value ::
term()}]}];
({allocator, Alloc}) -> [_] when Alloc :: atom();
(alloc_util_allocators) -> [Alloc] when Alloc ::
atom();
({allocator_sizes, Alloc}) -> [_] when Alloc :: atom();
(atom_count) -> pos_integer();
(atom_limit) -> pos_integer();
(build_type) ->
opt | debug | gcov | valgrind | gprof | lcnt |
frmptr;
(c_compiler_used) -> {atom(), term()};
(check_io) -> [_];
(cpu_topology) -> CpuTopology
when CpuTopology :: cpu_topology();
({cpu_topology, defined | detected | used}) ->
CpuTopology
when CpuTopology :: cpu_topology();
(cpu_quota) -> pos_integer() | unknown;
(creation) -> integer();
(debug_compiled) -> boolean();
(delayed_node_table_gc) -> infinity |
non_neg_integer();
(dirty_cpu_schedulers) -> non_neg_integer();
(dirty_cpu_schedulers_online) -> non_neg_integer();
(dirty_io_schedulers) -> non_neg_integer();
(dist) -> binary();
(dist_buf_busy_limit) -> non_neg_integer();
(dist_ctrl) ->
[{Node :: node(),
ControllingEntity :: port() | pid()}];
(driver_version) -> string();
(dynamic_trace) -> none | dtrace | systemtap;
(dynamic_trace_probes) -> boolean();
(eager_check_io) -> boolean();
(embedded_3pps) ->
#{included := [atom()], excluded := [atom()]};
(emu_flavor) -> emu | jit;
(emu_type) ->
opt | debug | gcov | valgrind | gprof | lcnt |
frmptr;
(end_time) -> non_neg_integer();
(ets_count) -> pos_integer();
(ets_limit) -> pos_integer();
(fullsweep_after) ->
{fullsweep_after, non_neg_integer()};
(garbage_collection) -> garbage_collection_defaults();
(heap_sizes) -> [non_neg_integer()];
(heap_type) -> private;
(info) -> binary();
(kernel_poll) -> boolean();
(loaded) -> binary();
(logical_processors | logical_processors_available |
logical_processors_online) ->
unknown | pos_integer();
(machine) -> string();
(max_heap_size) ->
{max_heap_size, MaxHeapSize :: max_heap_size()};
(message_queue_data) -> message_queue_data();
(min_heap_size) ->
{min_heap_size, MinHeapSize :: pos_integer()};
(min_bin_vheap_size) ->
{min_bin_vheap_size,
MinBinVHeapSize :: pos_integer()};
(modified_timing_level) -> integer() | undefined;
(multi_scheduling) ->
disabled | blocked | blocked_normal | enabled;
(multi_scheduling_blockers) -> [Pid :: pid()];
(nif_version) -> string();
(normal_multi_scheduling_blockers) -> [Pid :: pid()];
(otp_release) -> string();
(os_monotonic_time_source) -> [{atom(), term()}];
(os_system_time_source) -> [{atom(), term()}];
(outstanding_system_requests_limit) -> 1..134217727;
(port_parallelism) -> boolean();
(port_count) -> non_neg_integer();
(port_limit) -> pos_integer();
(process_count) -> pos_integer();
(process_limit) -> pos_integer();
(procs) -> binary();
(scheduler_bind_type) -> scheduler_bind_type();
(scheduler_bindings) -> tuple();
(scheduler_id) -> SchedulerId :: pos_integer();
(schedulers | schedulers_online) -> pos_integer();
(smp_support) -> boolean();
(start_time) -> integer();
(system_architecture) -> string();
(system_logger) -> logger | undefined | pid();
(system_version) -> string();
(threads) -> boolean();
(thread_pool_size) -> non_neg_integer();
(time_correction) -> true | false;
(time_offset) -> preliminary | final | volatile;
(time_warp_mode) ->
no_time_warp | single_time_warp | multi_time_warp;
(tolerant_timeofday) -> enabled | disabled;
(trace_control_word) -> non_neg_integer();
(update_cpu_info) -> changed | unchanged;
(version) -> string();
(wordsize | {wordsize, internal} | {wordsize,
external}) ->
4 | 8;
(async_dist) -> boolean();
(halt_flush_timeout) -> non_neg_integer() | infinity.
Returns information about the current system. 👑
The documentation of this function is broken into the following sections in order to make it easier to navigate.
- Memory Allocation —
allocated_areas,allocator,alloc_util_allocators,allocator_sizes - CPU Topology —
cpu_topology,logical_processors,update_cpu_info - Process Information —
fullsweep_after,garbage_collection,heap_sizes,heap_type,max_heap_size,message_queue_data,min_heap_size,min_bin_vheap_size,procs - System Limits —
atom_count,atom_limit,ets_count,ets_limit,port_count,port_limit,process_count,process_limit - System Time —
end_time,os_monotonic_time_source,os_system_time_source,start_time,time_correction,time_offset,time_warp_mode,tolerant_timeofday - Scheduler Information —
dirty_cpu_schedulers,dirty_cpu_schedulers_online,dirty_io_schedulers,multi_scheduling,multi_scheduling_blockers,normal_multi_scheduling_blockers,scheduler_bind_type,scheduler_bindings,scheduler_id,schedulers,smp_support,threads,thread_pool_size - Distribution Information —
creation,delayed_node_table_gc,dist,dist_buf_busy_limit,dist_ctrl - System Information —
c_compiler_used,check_io,debug_compiled,driver_version,dynamic_trace,dynamic_trace_probes,embedded_3pps,emu_flavor,emu_type,info,kernel_poll,loaded,machine,modified_timing_level,nif_version,otp_release,outstanding_system_requests_limit,port_parallelism,system_architecture,system_logger,system_version,trace_control_word,version,wordsize
🌸 Memory Allocation 🌸
Returns various information about the memory allocators of the current system (emulator) as specified by Item:
allocated_areas— Returns[tuple()]with information about miscellaneous allocated memory areas.
Each tuple contains an atom describing the type of memory as first element and the amount of allocated memory in bytes as second element. When information about allocated and used memory is present, also a third element is present, containing the amount of used memory in bytes.
erlang:system_info(allocated_areas) is intended for debugging, and the content is highly implementation-dependent. The content of the results therefore changes when needed without prior notice.
bestie, quick heads-up before we go any further: the sum of these values is not the total amount of memory the emulator allocated, okay? Some of these values are literally part of other values, and some memory areas just… aren't in the result at all. If you want the actual total amount of memory the emulator allocated, go look at erlang:memory/0,1. slay 💅
allocator</p>
Returns this whole situation:
{Allocator :: undefined | glibc,
Version :: [non_neg_integer()],
Features :: [atom()],
Settings :: [{Subsystem :: atom(),
[{Parameter :: atom(),
Value :: term()}]
}]
}
where, and let's break it down because there's a lot going on here:
Allocator— this is whichevermalloc()implementation is being used. IfAllocatorisundefined, then bestie, we simply cannot identify whichmalloc()implementation is in play.glibcis one that can be identified. 🔍Version— a list of integers (and not a string, don't come for me) representing the version of themalloc()implementation being used.Features— a list of atoms representing the allocation features used.Settings— a list of subsystems, their configurable parameters, and the values used. Real talk,Settingscan differ between different combos of platforms, allocators, and allocation features. Memory sizes are given in bytes.
Also see "System Flags Effecting erts_alloc" in erts_alloc(3). ✨
{allocator, Alloc}
Returns info about the allocator you specified. As from ERTS 5.6.1, the return value is a list of {instance, InstanceNo, InstanceInfo} tuples, where InstanceInfo contains info about one specific instance of the allocator. If Alloc isn't a recognized allocator, you get undefined back. If Alloc is disabled, you get false. 💀
Notice that the info returned here is highly implementation-dependent and can absolutely be changed or removed at any time, with no prior notice. It was originally meant as a tool for developing new allocators, but since other people found it interesting it got briefly documented. So like, use it, but don't build your whole personality on it.
The recognized allocators are listed in erts_alloc(3). Info about super carriers can be obtained from ERTS 8.0 with {allocator, erts_mmap} or from ERTS 5.10.4; and the list you get back when calling with {allocator, mseg_alloc} also includes an {erts_mmap, _} tuple as one element in the list.
Once you've read the erts_alloc(3) docs, what you get back more or less speaks for itself, but a few things are worth explaining. Call counts come as two values: the first one is giga calls, the second one is calls. mbcs and sbcs mean multi-block carriers and single-block carriers, respectively. Sizes are in bytes. When a size isn't presented, it's the amount of something. And sizes and amounts are often presented as three values:
- The first is the current value.
- The second is the maximum value since the last call to
erlang:system_info({allocator, Alloc}). - The third is the maximum value since the emulator was started.
If only one value is present, it's just the current value. fix_alloc memory block types are presented as two values: the first is the memory pool size, the second is the used memory size. 🫶
alloc_util_allocators
Returns a list of the names of all allocators using the ERTS internal alloc_util framework, as atoms. For more info, see the section The alloc_util framework in erts_alloc(3). 🌈
{allocator_sizes, Alloc}
Returns various size information for the allocator you specified. The info you get back is a subset of what erlang:system_info({allocator, Alloc}) gives you. iykyk ✨
🌸 CPU Topology 🌸
Returns various info about the CPU topology of the current system (emulator), as specified by Item:
cpu_topology
Returns the cpu_topology() currently used by the emulator. The CPU topology is used when binding schedulers to logical processors. The topology actually used is the user-defined CPU topology, if one exists; otherwise the automatically detected CPU topology, if one exists. And if no CPU topology exists at all? undefined comes back. no cap.
{cpu_topology, defined}
Returns the user-defined cpu_topology(). For more info, see command-line flag +sct in erl(1) and the argument cpu_topology.
{cpu_topology, detected}
Returns the automatically detected cpu_topology(). The emulator detects the CPU topology on some newer Linux, Solaris, FreeBSD, and Windows systems. On a Windows system with more than 32 logical processors, the CPU topology is not detected. 😭
For more info, see the argument cpu_topology.
{cpu_topology, used}
Returns CpuTopology used by the emulator. For more info, see the argument cpu_topology.
logical_processors
Returns the detected number of logical processors configured in the system. The return value is either an integer, or the atom unknown if the emulator can't detect the configured logical processors.
logical_processors_available
Returns the detected number of logical processors available to the Erlang runtime system. The return value is either an integer, or the atom unknown if the emulator can't detect the available logical processors. The number of available logical processors is less than or equal to the number of logical processors online. math is mathing 📐
logical_processors_online
Returns the detected number of logical processors online on the system. The return value is either an integer, or the atom unknown if the emulator can't detect logical processors online. The number of logical processors online is less than or equal to the number of logical processors configured.
cpu_quota
Returns the detected CPU quota the emulator is limited by. The return value is an integer saying how many processors' worth of runtime we get (somewhere between 1 and the number of logical processors), or the atom unknown if the emulator can't detect a quota.
update_cpu_info
The runtime system rereads the CPU info that's available and updates its internally stored info about the detected CPU topology and the number of logical processors configured, online, available, and the cpu quota. 👑
If the CPU info has changed since the last time it was read, the atom changed is returned; otherwise you get unchanged. And if the CPU info has changed, you probably wanna adjust the number of schedulers online. Typically you want as many schedulers online as there are logical processors available. bestie behavior tbh
Since: OTP R14B
🧚 Process Information 🧚
Returns info about the default process heap settings:
fullsweep_after
Returns {fullsweep_after, integer() >= 0}, which is the fullsweep_after garbage collection setting used by default. For more info, see garbage_collection described below.
garbage_collection
Returns garbage_collection_defaults/0 describing the default garbage collection settings. A process spawned on the local node by a spawn or spawn_link uses these garbage collection settings. The default settings can be changed using erlang:system_flag/2. And spawn_opt/2,3,4 can spawn a process that doesn't use the default settings. it's giving options 💅
heap_sizes
Returns a list of integers representing valid heap sizes in words. All Erlang heaps are sized from sizes in this list.
heap_type
Returns the heap type used by the current emulator. One heap type exists, and it is:
private— each process has a heap reserved for its use, and no references between heaps of different processes are allowed. Messages passed between processes are copied between heaps. 🫶
max_heap_size
Returns {max_heap_size, MaxHeapSize}, where MaxHeapSize is the current system-wide maximum heap size settings for spawned processes. This setting can be set using the command-line flags +hmax, +hmaxk, +hmaxel and +hmaxibl in erl(1). It can also be changed at runtime using erlang:system_flag(max_heap_size, MaxHeapSize). For way more details about the max_heap_size process flag, see process_flag(max_heap_size, MaxHeapSize).
Since: OTP 19.0
message_queue_data
Returns the default value of the message_queue_data process flag, which can be either off_heap or on_heap. The default value is set by the command-line argument +hmqd in erl(1). For more info, see the docs for process_flag(message_queue_data, MQD).
Since: OTP 19.0
min_heap_size
Returns {min_heap_size, MinHeapSize}, where MinHeapSize is the current system-wide minimum heap size for spawned processes.
Since: OTP R13B04
min_bin_vheap_size
Returns {min_bin_vheap_size, MinBinVHeapSize}, where MinBinVHeapSize is the current system-wide minimum binary virtual heap size for spawned processes.
Since: OTP R13B04
procs
Returns a binary containing a string of process and port information, formatted like it is in Erlang crash dumps. For more info, see the section How to interpret the Erlang crash dumps in the User's Guide. 💀📄
👑 System Limits 👑
Returns info about the current system (emulator) limits, as specified by Item:
atom_count
Returns the number of atoms currently existing at the local node. The value is given as an integer.
Since: OTP 20.0
atom_limit
Returns the maximum number of atoms allowed. This limit can be increased at startup by passing the command-line flag +t to erl(1).
Since: OTP 20.0
ets_count
Returns the number of ETS tables currently existing at the local node.
Since: OTP 21.1
ets_limit
Returns the limit for the number of ETS tables. Lowkey this limit is partially obsolete, and the number of tables is only limited by available memory.
Since: OTP R16B03
port_count
Returns the number of ports currently existing at the local node. The value is given as an integer. This is the same value as length(erlang:ports()) returns, but more efficient. slay 🏃♀️💨
Since: OTP R16B
port_limit
Returns the maximum number of simultaneously existing ports at the local node as an integer. This limit can be configured at startup by using the command-line flag +Q in erl(1).
Since OTP R16B
process_count
Returns the number of processes currently existing at the local node. The value is given as an integer. This is the same value as length(processes()) returns, but more efficient.
process_limit
Returns the maximum number of simultaneously existing processes at the local node. The value is given as an integer. This limit can be configured at startup by using the command-line flag +P in erl(1).
🌈 System Time 🌈
Returns information about the current system (emulator) time as specified by Item:
end_time— the very last Erlang monotonic time, in native time unit, that can even be represented internally in this current Erlang runtime system instance 🕰️. And bestie, the span between the start time and the end time is at least a quarter of a millennium. yes literally centuries. iconic longevity behavior fr.
Since: OTP 18.0
os_monotonic_time_source— hands you back a list with all the tea about the source of OS monotonic time that the runtime system is using ☕.
If it returns [], that means no OS monotonic time is available, periodt. Otherwise the list is full of two-tuples: Keys first, Values second. The order of those tuples? undefined, we do not know, it's a mystery 💅. These tuples can be in the list, but more tuples might get introduced in the future, so don't get too comfy:
{function, Function}Functionis the name of the function being used. This tuple always exists if OS monotonic time is available to the runtime system.
{clock_id, ClockId}- This tuple only exists if
Functioncan be used with different clocks.ClockIdcorresponds to the clock identifier used when callingFunction.
- This tuple only exists if
{resolution, OsMonotonicTimeResolution}- The highest possible resolution of the current OS monotonic time source, as parts per second. If no resolution info can be retrieved from the OS,
OsMonotonicTimeResolutiongets set to the resolution of the time unit of theFunctions return value. So the actual resolution can be lower thanOsMonotonicTimeResolution. Also notice: resolution says nothing about accuracy, and nothing about whether the precision aligns with the resolution. What you do know is that the precision is not better thanOsMonotonicTimeResolution. no cap.
- The highest possible resolution of the current OS monotonic time source, as parts per second. If no resolution info can be retrieved from the OS,
{used_resolution, UsedOsMonotonicTimeResolution}- The OS monotonic time resolution actually used by the runtime system. Very often this is the same as
OsMonotonicTimeResolution, but on some systems the resolution has to be reduced so monotonic timestamps can be reliably produced. Example: whenQueryPerformanceCounter()is used as the OS monotonic time source on Windows. If such a reduction happened,UsedOsMonotonicTimeResolutionwill be smaller thanOsMonotonicTimeResolution.
- The OS monotonic time resolution actually used by the runtime system. Very often this is the same as
{extended, Extended}Extendedequalsyesif the range of time values has been extended; otherwiseExtendedequalsno. The range must be extended ifFunctionreturns values that wrap fast — typically the case when the return value is a 32-bit value 👀.
{parallel, Parallel}ParallelequalsyesifFunctionis called in parallel from multiple threads. If it's not called in parallel because calls must be serialized,Parallelequalsno.
{time, OsMonotonicTime}OsMonotonicTimeequals the current OS monotonic time in native time unit.
Since: OTP 18.0
os_system_time_source— same vibe, but for the source of OS system time used by the runtime system ✨.
The list contains two-tuples with Keys as first element and Values as second. The order of these tuples is undefined. The following tuples can be part of the list, but more tuples can be introduced in the future:
{function, Function}Functionis the name of the function used.
{clock_id, ClockId}- Exists only if
Functioncan be used with different clocks.ClockIdcorresponds to the clock identifier used when callingFunction.
- Exists only if
{resolution, OsSystemTimeResolution}- Highest possible resolution of the current OS system time source, as parts per second. If no resolution information can be retrieved from the OS,
OsSystemTimeResolutionis set to the resolution of the time unit of theFunctions return value. That is, the actual resolution can be lower thanOsSystemTimeResolution. Notice that the resolution does not say anything about accuracy or whether the precision do align with the resolution. You do, however, know that the precision is not better thanOsSystemTimeResolution.
- Highest possible resolution of the current OS system time source, as parts per second. If no resolution information can be retrieved from the OS,
{parallel, Parallel}ParallelequalsyesifFunctionis called in parallel from multiple threads. If it's not called in parallel, because calls needs to be serialized,Parallelequalsno.
{time, OsSystemTime}OsSystemTimeequals the current OS system time in native time unit.
Since: OTP 18.0
start_time— the Erlang monotonic time, in native time unit, at the moment when the current Erlang runtime system instance started 🐣.
See also erlang:system_info(end_time).
Since: OTP 18.0
time_correction— returns aboolean()value telling you whether time correction is enabled or not ✅.
Since: OTP 18.0
time_offset— returns the state of the time offset, and the options are:preliminary— the time offset is preliminary and will be changed and finalized later. The preliminary time offset is used during the preliminary phase of the single time warp mode.final— the time offset is final. This is either because no time warp mode is used, or because the time offset have been finalized when single time warp mode is used.volatile— the time offset is volatile. That is, it can change at any time. This is because multi-time warp mode is used. chaotic queen behavior, honestly 😭.
Since: OTP 18.0
time_warp_mode— returns a value identifying which time warp mode is in use:no_time_warp— the no time warp mode is used.single_time_warp— the single time warp mode is used.multi_time_warp— the multi-time warp mode is used.
Since: OTP 18.0
tolerant_timeofday— tells you whether a pre ERTS 7.0 backwards compatible compensation for sudden changes of system time is enabled or disabled. Such compensation is enabled when the time offset isfinal, and time correction is enabled 🫶.
Since: OTP 17.1
🧵 Scheduler Information
Returns information about schedulers, scheduling and threads in the current system, as specified by Item:
dirty_cpu_schedulers— returns the number of dirty CPU scheduler threads used by the emulator. Dirty CPU schedulers execute CPU-bound native functions, like NIFs, linked-in driver code, and BIFs that cannot be managed cleanly by the normal emulator schedulers 🔥.
The number of dirty CPU scheduler threads is determined at emulator boot time and cannot be changed after that. However — and this is the fun part — the number of dirty CPU scheduler threads online can be changed at any time. The number of dirty CPU schedulers can be set at startup by passing command-line flag +SDcpu or +SDPcpu in erl(1).
See also erlang:system_flag(dirty_cpu_schedulers_online, DirtyCPUSchedulersOnline), erlang:system_info(dirty_cpu_schedulers_online), erlang:system_info(dirty_io_schedulers), erlang:system_info(schedulers), erlang:system_info(schedulers_online), and erlang:system_flag(schedulers_online, SchedulersOnline).
Since: OTP 17.0
dirty_cpu_schedulers_online— returns the number of dirty CPU schedulers online. The return value satisfies1 <= DirtyCPUSchedulersOnline <= N, whereNis the smallest of the return values oferlang:system_info(dirty_cpu_schedulers)anderlang:system_info(schedulers_online)💫.
The number of dirty CPU schedulers online can be set at startup by passing command-line flag +SDcpu in erl(1).
For more information, see erlang:system_info(dirty_cpu_schedulers), erlang:system_info(dirty_io_schedulers), erlang:system_info(schedulers_online), and erlang:system_flag(dirty_cpu_schedulers_online, DirtyCPUSchedulersOnline).
Since: OTP 17.0
dirty_io_schedulers— returns the number of dirty I/O schedulers as an integer. Dirty I/O schedulers execute I/O-bound native functions, such as NIFs and linked-in driver code, which cannot be managed cleanly by the normal emulator schedulers 🌸.
This value can be set at startup by passing command-line argument +SDio in erl(1).
For more information, see erlang:system_info(dirty_cpu_schedulers), erlang:system_info(dirty_cpu_schedulers_online), and erlang:system_flag(dirty_cpu_schedulers_online, DirtyCPUSchedulersOnline).
Since: OTP 17.0
multi_scheduling— returns one of the following:disabled— the emulator has been started with only one scheduler thread.blocked— the emulator has more than one scheduler thread, but all scheduler threads except one are blocked. That is, only one scheduler thread schedules Erlang processes and executes Erlang code.blocked_normal— the emulator has more than one scheduler thread, but all normal scheduler threads except one are blocked. Notice that dirty schedulers are not blocked, and can schedule Erlang processes and execute native code 👀.enabled— the emulator has more than one scheduler thread, and no scheduler threads are blocked. That is, all available scheduler threads schedule Erlang processes and execute Erlang code.
See also erlang:system_flag(multi_scheduling, BlockState), erlang:system_info(multi_scheduling_blockers), erlang:system_info(normal_multi_scheduling_blockers), and erlang:system_info(schedulers).
multi_scheduling_blockers— returns a list ofPids when multi-scheduling is blocked, otherwise the empty list is returned. ThePids in the list represent all the processes currently blocking multi-scheduling. APidoccurs only once in the list, even if the corresponding process has blocked multiple times. no dupes, we respect the algorithm 💅.
See also erlang:system_flag(multi_scheduling, BlockState), erlang:system_info(multi_scheduling), erlang:system_info(normal_multi_scheduling_blockers), and erlang:system_info(schedulers).
normal_multi_scheduling_blockers— returns a list ofPids when normal multi-scheduling is blocked (that is, all normal schedulers but one is blocked), otherwise the empty list is returned. ThePids in the list represent all the processes currently blocking normal multi-scheduling. APidoccurs only once in the list, even if the corresponding process has blocked multiple times 🎀.
See also erlang:system_flag(multi_scheduling, BlockState), erlang:system_info(multi_scheduling), erlang:system_info(multi_scheduling_blockers), and erlang:system_info(schedulers).
Since: OTP 19.0
scheduler_bind_type— returnsscheduler_bind_type(), which is the info about how the user has requested schedulers to be bound or not bound 🔗.
Notice that even though a user has requested schedulers to be bound, they can silently have failed to bind. sneaky!! To actually inspect the scheduler bindings, call erlang:system_info(scheduler_bindings).
For more information, see command-line argument +sbt in erl(1) and erlang:system_info(scheduler_bindings).
scheduler_bindings— tells you all about the scheduler bindings in play right now 💅
You get back a tuple that's the same size as erlang:system_info(schedulers). The elements are integers, or the atom unbound. Logical processor identifiers show up as integers. The Nth element of the tuple = the current binding for the scheduler whose scheduler identifier is N. Like, for example, if the schedulers are bound, then element(erlang:system_info(scheduler_id), erlang:system_info(scheduler_bindings)) hands you the identifier of the logical processor your calling process is running on. bestie that's kind of iconic.
Heads up tho: only schedulers online can be bound to logical processors. no cap.
Want more? Go see command-line argument +sbt in erl(1) and erlang:system_info(schedulers_online).
scheduler_id— the scheduler ID (SchedulerId) of the scheduler thread your calling process is executing on 🧚
SchedulerId is a positive integer, and 1 <= SchedulerId <= erlang:system_info(schedulers).
See also erlang:system_info(schedulers).
schedulers— the number of scheduler threads the emulator is using 👑
Scheduler threads online schedule Erlang processes and Erlang ports, and execute Erlang code and Erlang linked-in driver code.
The number of scheduler threads is decided at emulator boot time and literally cannot be changed later. But the number of schedulers online can be changed whenever you want, so that's the vibe.
See also erlang:system_flag(schedulers_online, SchedulersOnline), erlang:system_info(schedulers_online), erlang:system_info(scheduler_id), erlang:system_flag(multi_scheduling, BlockState), erlang:system_info(multi_scheduling), erlang:system_info(normal_multi_scheduling_blockers) and erlang:system_info(multi_scheduling_blockers).
schedulers_online— the number of schedulers online ✨
The scheduler identifiers of schedulers online satisfy the relationship 1 <= SchedulerId <= erlang:system_info(schedulers_online).
For more info, see erlang:system_info(schedulers) and erlang:system_flag(schedulers_online, SchedulersOnline).
smp_support— Returnstrue. 💖 that's it, that's the whole thing.threads— Returnstrue. 🫶 same energy.thread_pool_size— the number of async threads in the async thread pool used for asynchronous driver calls (erl_driver:driver_async()) 🌸
The value is given as an integer.
🌐 Distribution Information 🌐
Gives you info about Erlang Distribution in the current system, as specified by Item:
async_dist— the value of the command line argument+pad <boolean>that the runtime system uses 🦋
This value determines the default async_dist value for newly spawned processes.
Since: OTP 25.3
creation— the "creation" value of the local node, as an integer 🌈
The creation changes when a node is restarted. The creation of a node is stored in process identifiers, port identifiers, and references. That's how you can tell apart identifiers from different incarnations of a node. Creation values are currently 32-bit positive integers, but this may change in future releases (no promises, bestie). If the node is not alive, 0 is returned.
delayed_node_table_gc— the amount of time in seconds that garbage collection of an entry in a node table is delayed ⭐
This limit can be set on startup by passing command-line flag +zdntgc to erl(1). For more information, see the documentation of that command-line flag.
Since: OTP 18.0
dist— a binary containing a string of distribution information, formatted as in Erlang crash dumps 💀
For more information, see section How to interpret the Erlang crash dumps in the User's Guide.
dist_buf_busy_limit— the value of the distribution buffer busy limit, in bytes 🍓
This limit can be set at startup by passing command-line flag +zdbbl to erl(1).
Since: OTP R14B01
dist_ctrl— a list of tuples{Node :: node(), ControllingEntity :: port() | pid()}, one entry for every connected remote node 💜
Node is the node name and ControllingEntity is the port or process identifier responsible for the communication to that node. More specifically, ControllingEntity for nodes connected through TCP/IP (the normal case) is the socket used in communication with that specific node.
🖥️ System Information 🖥️
Gives you various info about the current system (emulator), as specified by Item:
c_compiler_used— a two-tuple describing the C compiler used when compiling the runtime system 💅
The first element is an atom describing the name of the compiler, or undefined if unknown. The second element is a term describing the version of the compiler, or undefined if unknown.
check_io— a list containing miscellaneous information about the emulator's internal I/O checking 🙈
Notice that the content of the returned list can vary between platforms and over time. It is only guaranteed that a list is returned. that's the whole promise.
debug_compiled—trueif the emulator has been debug-compiled, otherwisefalse🎀driver_version— a string containing the Erlang driver version used by the runtime system 🦋
It has the form "<major ver>.<minor ver>".
dynamic_trace— an atom describing the dynamic trace framework compiled into the virtual machine ✨
It can be dtrace, systemtap, or none. For a commercial or standard build, it is always none. The other return values indicate a custom configuration (for example, ./configure --with-dynamic-trace=dtrace). For more information about dynamic tracing, see the dyntrace(3) manual page and the README.dtrace/README.systemtap files in the Erlang source code top directory.
Since: OTP R15B01
dynamic_trace_probes— aboolean()indicating if dynamic trace probes (dtraceorsystemtap) are built into the emulator 🔥
This can only be true if the virtual machine was built for dynamic tracing (that is, system_info(dynamic_trace) returns dtrace or systemtap).
Since: OTP R15B01
embedded_3pps— a map with information about third party products embedded in the source code of the Erlang/OTP runtime system 💖
Note that often only parts (in some cases minuscule parts 😭) of these third party products have been embedded in the source code. Currently the returned map contains the following keys:
included— The value of this key is a list of atoms where each atom represents a third party product from which code has been embedded in the source code and also has been included into the built runtime system. 💅excluded— The value of this key is a list of atoms where each atom represents a third party product from which code has been embedded in the source code, but which has been completely excluded in the built runtime system. 🙈 The exclusion might be due to the functionality being disabled, due to the functionality being implemented using other primitives on the specific system, or due to the runtime system being linked against the same or another third party product installed on the system.
Note that the returned map may be extended with new key/value pairs at any time. so don't get too attached.
Since: OTP 28.5
emu_flavor— an atom describing the flavor of the runtime system 🍓
This will be either emu or jit. Possible return values can be added or removed at any time without prior notice.
Since: OTP 24.0
emu_type— an atom describing the build type of the runtime system 👑
This is normally the atom opt for optimized. Other possible return values are debug, gcov, valgrind, gprof, and lcnt. Possible return values can be added or removed at any time without prior notice.
Since: OTP 24.0
halt_flush_timeout— the default halt flush timeout set by theerl +zhft <Timeout>command line flag ⏰
Since: OTP 27.0
info— a binary containing a string of miscellaneous system information, formatted as in Erlang crash dumps 💀
For more information, see section How to interpret the Erlang crash dumps in the User's Guide.
kernel_poll—trueif the emulator uses some kind of kernel-poll implementation, otherwisefalse🌸loaded— a binary containing a string of loaded module information, formatted as in Erlang crash dumps 📦
For more information, see section How to interpret the Erlang crash dumps in the User's Guide.
machine— a string containing the Erlang machine name 🖥️modified_timing_level— the modified timing-level (aninteger()) if modified timing is enabled, otherwiseundefined⏱️
For more information about modified timing, see command-line flag +T in erl(1).
nif_version— a string containing the version of the Erlang NIF interface used by the runtime system 🧚
It is on the form "<major ver>.<minor ver>".
Since: OTP 17.4
otp_release— a string containing the OTP release number of the OTP release that the currently executing ERTS application is part of 🎀
As from Erlang/OTP 17, the OTP release number corresponds to the major OTP version number. No erlang:system_info() argument gives the exact OTP version. This is because the exact OTP version in the general case is difficult to determine. For more information, see the description of versions in System principles in System Documentation.
outstanding_system_requests_limit— the limit on the amount of outstanding requests made by a system process orchestrating system wide changes 🌀
See erlang:system_flag(outstanding_system_requests_limit, Limit) for more information.
Since: OTP 24.2
port_parallelism— the default port parallelism scheduling hint used 🌈
For more information, see command-line argument +spp in erl(1).
Since: OTP R16B
system_architecture— a string containing the processor and OS architecture the emulator is built for 💻system_logger— the currentsystem_loggeras set byerlang:system_flag(system_logger, *)📝
Since: OTP 21.3
system_version— a string containing version number and some important properties, such as the number of schedulers ⭐trace_control_word— the value of the node trace control word 🔍
For more information, see function get_tcw in section Match Specifications in Erlang in the User's Guide.
version— a string containing the version number of the emulator 🦋wordsize— Same as{wordsize, internal}. 💖 literally the exact same thing.{wordsize, internal}— the size of Erlang term words in bytes, as an integer. So like, you get4back on a 32-bit architecture and8back on a 64-bit architecture. that's it that's the whole vibe 💅{wordsize, external}— the true word size of the emulator, aka the size of a pointer 👑. The value comes back as an integer in bytes. On a pure 32-bit architecture you get4. On a 64-bit architecture you get8. no notes.
🌸 system_monitor()
system_monitor() -> MonSettings
when
MonSettings ::
undefined | {MonitorPid, Options},
MonitorPid :: pid(),
Options :: [system_monitor_option()].
Returns the current system monitoring settings that were set by erlang:system_monitor/2, formatted as {MonitorPid, Options}. If literally no settings exist it hands you back undefined.
Heads up tho bestie 🫶: the order of the options can come back different from the order you originally set them in. it's giving alphabet-adjacent chaos, not a bug.
🌈 system_monitor(Arg)
system_monitor(Arg) -> MonSettings
when
Arg :: undefined | {MonitorPid, Options},
MonSettings ::
undefined | {MonitorPid, Options},
MonitorPid :: pid(),
Options :: [system_monitor_option()].
- Call it with
undefinedand all system performance monitoring settings get cleared. poof, gone 💀 - Call it with
{MonitorPid, Options}and it's exactly the same as callingerlang:system_monitor(MonitorPid, Options). same energy, shorter typing ✨
Returns the previous system monitor settings, just like erlang:system_monitor/0 does.
🦋 system_monitor(MonitorPid, Options)
system_monitor(MonitorPid, Options) -> MonSettings
when
MonitorPid :: pid(),
Options :: [system_monitor_option()],
MonSettings ::
undefined | {OldMonitorPid, OldOptions},
OldMonitorPid :: pid(),
OldOptions :: [system_monitor_option()].
Sets the system event monitoring options. MonitorPid is a local process identifier (a pid) that receives the system monitor messages.
Change 💀 — This function is superseded by trace:system/3 that operate on dynamic trace sessions. so like, it still works, but the cool kids moved on.
The second argument is a list of monitoring options to enable:
{long_gc, Time}{long_message_queue, {Disable, Enable}}{long_schedule, Time}{large_heap, Size}busy_portbusy_dist_port
For way more detailed descriptions about the monitoring options, go peek at trace:system/3.
Unlike trace:system/3, the arguments to system_monitor/2 specify how all system monitoring should be set — not how it should be changed. Which means: only one process at a time (MonitorPid) can be the receiver of messages from system monitoring set with this function. that's the rule, no sharing 🎀. Also, the way you clear a specific monitor option is simply to not include it in the Options list. That said, all system monitoring gets cleared anyway if the process identified by MonitorPid terminates.
There are no special option values (like zero) to clear an option — sorry bestie, no cheat code 🙈. Some of the options have an unspecified minimum value, and lower values will be adjusted up to that minimum. For example, it is currently not possible to monitor all garbage collections with {long_gc, 0}.
Returns the previous system monitor settings, just like erlang:system_monitor/0.
NOTE: If a monitoring process gets so large that it itself starts to cause system monitor messages when garbage collecting, the messages enlarge the process message queue and probably make the problem worse. Keep the monitoring process neat and do not set the system monitor limits too tight. fr fr, this is a real trap 😭
Failures:
badarg— IfMonitorPiddoes not exist.badarg— IfMonitorPidis not a local process.
💜 system_profile()
system_profile() -> ProfilerSettings
when
ProfilerSettings ::
undefined | {ProfilerPid, Options},
ProfilerPid :: pid() | port(),
Options :: [system_profile_option()].
Returns the current system profiling settings set by erlang:system_profile/2 as {ProfilerPid, Options}, or undefined if there are no settings at all. And yeah — the order of the options can be different from the one that was set. same chaotic energy as above ✨
🧚 system_profile(ProfilerPid, Options)
system_profile(ProfilerPid, Options) -> ProfilerSettings
when
ProfilerPid :: pid() | port() | undefined,
Options :: [system_profile_option()],
ProfilerSettings ::
undefined |
{pid() | port(),
[system_profile_option()]}.
Sets system profiler options. ProfilerPid is a local process identifier (pid) or port that receives the profiling messages. Fun fact: the receiver is excluded from all profiling 👑. The second argument is a list of profiling options:
exclusive— If a synchronous call to a port from a process is done, the calling process is considered not runnable during the call runtime to the port. The calling process is notified as inactive, and later active when the port callback returns.monotonic_timestamp— Time stamps in profile messages use Erlang monotonic time. The time stamp (Ts) has the same format and value as produced byerlang:monotonic_time(nanosecond).runnable_procs— If a process is put into or removed from the run queue, a message,{profile, Pid, State, Mfa, Ts}, is sent toProfilerPid. Running processes that are reinserted into the run queue after having been pre-empted do not trigger this message.runnable_ports— If a port is put into or removed from the run queue, a message,{profile, Port, State, 0, Ts}, is sent toProfilerPid.scheduler— If a scheduler is put to sleep or awoken, a message,{profile, scheduler, Id, State, NoScheds, Ts}, is sent toProfilerPid.strict_monotonic_timestamp— Time stamps in profile messages consist of Erlang monotonic time and a monotonically increasing integer. The time stamp (Ts) has the same format and value as produced by{erlang:monotonic_time(nanosecond), erlang:unique_integer([monotonic])}.timestamp— Time stamps in profile messages include a time stamp (Ts) that has the same form as returned byerlang:now(). This is also the default if no time stamp flag is specified. Ifcpu_timestamphas been enabled throughtrace:process/4, this also effects the time stamp produced in profiling messages when flagtimestampis enabled.
NOTE: erlang:system_profile behavior can change in a future release. 👀 so don't get too attached to the details.
⭐ system_time()
system_time() -> integer().
Returns the current Erlang system time in native time unit.
Calling erlang:system_time() is equivalent to erlang:monotonic_time()+erlang:time_offset().
NOTE: This time is not a monotonically increasing time in the general case. For more information, see the documentation of time warp modes in the User's Guide. time is a liar sometimes 😭
🌸 system_time(Unit)
system_time(Unit) -> integer() when Unit :: time_unit().
Returns the current Erlang system time, converted into the Unit you passed as the argument.
Calling erlang:system_time(Unit) is equivalent to erlang:convert_time_unit(erlang:system_time(), native, Unit).
NOTE: This time is not a monotonically increasing time in the general case either. For more information, see the documentation of time warp modes in the User's Guide. same warning, same vibe check 🫶
🎀 term_to_binary(Term)
term_to_binary(Term) -> ext_binary() when Term :: term().
Returns a binary data object that is the result of encoding Term according to the Erlang external term format. it's giving term → ✨binary✨.
This can be used for a bunch of things, such as efficiently writing a term to a file, or sending an Erlang term through a communication channel that distributed Erlang doesn't support. versatile icon behavior 💅
See also binary_to_term/1.
NOTE: There is no guarantee that this function will always return the same encoded representation for the same term. so don't you dare compare the bytes and expect them to match every single time 🙈
Examples
1> Bin = term_to_binary(hello).
<<131,119,5,104,101,108,108,111>>
2> hello = binary_to_term(Bin).
hello
💖 term_to_binary(Term, Options)
term_to_binary(Term, Options) -> ext_binary()
when
Term :: term(),
Options ::
[compressed |
{compressed, Level :: 0..9} |
deterministic |
{minor_version, Version :: 0..2} |
local].
Returns a binary data object that is the result of encoding Term according to the Erlang external term format. (yeah, same sentence as before, it's a series bestie 😌)
Supported options:
compressed— Compress the external term format. The compressed format is automatically recognized bybinary_to_term/1as from Erlang/OTP R7B.{compressed, Level}— Compress the external term format to a given level. The compression level is specified byLevel, which is an integer in the range0to9, where:0— No compression is applied (equivalent to omitting thecompressedoption).1— Fastest compression but may not compress as well as the higher levels.6— Default level when thecompressedoption is provided.9— Highest compression level, taking the longest time while attempting to produce the smallest result. However, depending on the input term, level9compression may not always produce a smaller result than level1compression. (so yes, 9 is not always the winner, plot twist 🔥)
{minor_version, Version}(Since R11B-4) — The option can be used to control some encoding details. Valid values forVersionare:0— Floats are encoded using a textual representation.
- Floats are encoded in a more space-efficient and exact way (namely in the 64-bit IEEE format, rather than converted to a textual representation). As from Erlang/OTP R11B-4,
binary_to_term/1can decode this representation.
Atoms that can be represented by a latin1 string are encoded using latin1 while only atoms that cannot be represented by latin1 are encoded using utf8.
- This is as of Erlang/OTP 26.0 the default. Atoms are unconditionally encoded using utf8. Erlang/OTP systems as of R16B can decode this representation.
deterministic(Since OTP 24.1) 💖 — bestie, this one is here to make sure that, within the same major release of Erlang/OTP, you get the same encoded representation back for the same term. That said, no cap: there's still no guarantee the encoded representation stays the same between major releases of Erlang/OTP.
This option cannot be combined with the local option. pick one, babe 🫶
local(Since OTP 26.0) — this one encodes Term in an alternative local version of the external term format 🌈. When it gets decoded by the same runtime system instance, it produces a term identical to the original term, even if the node name and/or creation of the runtime system instance changed between encoding and decoding. iconic behaviour, honestly ✨
When encoding without the local option, local identifiers such as pids, ports, and references will not remain the same if node name and/or creation of the runtime system instance changed between encoding and decoding. Why? Because those identifiers refer to a specific node by node name and creation. 💅
The node name and creation change when the distribution is started or stopped 🦋. The distribution starts when the runtime system is started with the -name or -sname command-line arguments. Note that the actual start of the distribution occurs after other code in the startup phase has already begun executing. The distribution can also be started by calling net_kernel:start/2 and stopped by calling net_kernel:stop/1, provided it was not started via the command line.
When decoding a term encoded with the local option using, for example, binary_to_term/1, the runtime system attempts to verify that the term was encoded by the same runtime system instance. In most cases, decoding will fail if it was encoded by a different instance. However, this verification is not foolproof. You should ensure that terms encoded with the local option are only decoded by the same Erlang runtime system instance that encoded them. 🙈
Since only the runtime system that encoded a term using the local option can decode it, the local encoding is typically pieced together with something else to produce a reply to where the local encoding originates. If a term encoded with the local option has its leading version number stripped, it can be embedded as part of a larger term (for example as an element in a tuple) when encoding in the external term format using, for example, EI. In this case, you would strip the version number using ei_decode_version() and append the remaining local encoding using, for example, ei_x_append_buf().
A common use case for the local option is when making a request from a process to a port driver driver while leveraging the selective receive optimization for handling the reply. 🎀
In this scenario:
- A reference is created.
- The reference is serialized using the external term format with the
localoption. - This serialized reference is passed to the driver in the request.
- The process then waits for a reply message in a selective receive, matching on the reference.
The driver should send the reply using either erl_drv_output_term() or erl_drv_send_term() using the term type ERL_DRV_EXT2TERM for the reference previously received in the request.
Note that you should not strip the leading version number from the local encoding when using the term typeERL_DRV_EXT2TERM. If the reference is not encoded with thelocaloption, and distribution is started or stopped while the request is ongoing, the requesting process will hang indefinitely because the reference in the reply message will never match. 💀
This option cannot be combined with the deterministic option.
For more details, see LOCAL_EXT.
See also binary_to_term/1.
✨ Examples ✨
1> List = lists:duplicate(20, $=).
"===================="
2> term_to_binary(List, []).
<<131,107,0,20,61,61,61,61,61,61,61,61,61,61,61,61,61,61,
61,61,61,61,61,61>>
3> term_to_binary(List, [compressed]).
<<131,80,0,0,0,23,120,156,203,102,16,177,197,2,0,61,98,5,
68>>
term_to_iovec(Term) -> ext_iovec() when Term :: term().
Returns the encoding of Term according to the Erlang external term format as ext_iovec/0. 💫
This function produce the same encoding as term_to_binary/1, but with another return type. The call iolist_to_binary(term_to_iovec(Term)) will produce exactly the same result as the call term_to_binary(Term). literally the same bytes, bestie, no notes 🫶
term_to_iovec/1 is a pure optimization of the functionality provided by term_to_binary/1. For example, it can reference off-heap binaries directly instead of copying their contents into the result. 🔥
See also term_to_binary/1.
✨ Examples ✨
1> term_to_iovec({binary:copy(~"a", 65), binary:copy(~"b", 65)}).
[<<131,104,2,109,0,0,0,65>>,
<<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">>,
<<109,0,0,0,65>>,
<<"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb">>]
term_to_iovec(Term, Options) -> ext_iovec() when
Term :: term(),
Options ::
[compressed |
{compressed, Level :: 0..9} |
deterministic |
{minor_version, Version :: 0..2} |
local].
Returns the encoding of Term according to the Erlang external term format as ext_iovec/0. 🌸
This function produce the same encoding as term_to_binary/2, but with another return type. The call iolist_to_binary(term_to_iovec(Term, Opts)) will produce exactly the same result as term_to_binary(Term, Opts).
This function supports all options supported by term_to_binary/2. 👑
term_to_iovec/2 is a pure optimization of the functionality provided by term_to_binary/2. For example, it can reference off-heap binaries directly instead of copying their contents into the result.
See also term_to_binary/2.
✨ Examples ✨
1> term_to_iovec({binary:copy(~"a", 65), binary:copy(~"b", 65)}, [deterministic]).
[<<131,104,2,109,0,0,0,65>>,
<<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">>,
<<109,0,0,0,65>>,
<<"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb">>]
throw(Any) -> no_return() when Any :: term().
Raises an exception of class throw. Intended to be used to do non-local returns from functions. 🎯
If evaluated within a catch expression, the catch expression returns value Any.
For example:
1> catch throw({hello, there}).
{hello,there}
If evaluated within a try-block of a try expression, the value Any can be caught within the catch block.
For example:
1> try
throw({my_exception, "Something happened"})
catch
throw:{my_exception, Desc} ->
io:format(standard_error, "Error: ~s~n", [Desc])
end.
%% Output to standard error: Error: Something happened
If throw/1 is not evaluated within a catch, a nocatch run-time error occurs. she said what she said 😭
See the guide about errors and error handling for additional information.
time() -> Time when Time :: calendar:time().
Returns the current time as {Hour, Minute, Second}. ⏰✨
The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time.
For example:
> time().
{9,42,44}
time_offset() -> integer().
Returns the current time offset between Erlang monotonic time and Erlang system time in native time unit. Current time offset added to an Erlang monotonic time gives corresponding Erlang system time. 🕰️
The time offset may or may not change during operation depending on the time warp mode used.
NOTE: A change in time offset can be observed at slightly different points in time by different processes. If the runtime system is in multi-time warp mode, the time offset is changed when the runtime system detects that the OS system time has changed. The runtime system will, however, not detect this immediately when it occurs. A task checking the time offset is scheduled to execute at least once a minute; so, under normal operation this is to be detected within a minute, but during heavy load it can take longer time. lowkey giving "eventually, bestie" energy 💜
time_offset(Unit) -> integer() when Unit :: time_unit().
Returns the current time offset between Erlang monotonic time and Erlang system time converted into the Unit passed as argument. 🌈
Same energy as calling erlang:convert_time_unit(erlang:time_offset(), native, Unit), except it's been glow-upped and optimized for the Units that everybody actually uses ✨
timestamp() — the nostalgia-core one 💜
timestamp() -> Timestamp
when Timestamp :: timestamp().
Hands you the current Erlang system time in the format {MegaSecs, Secs, MicroSecs} 🕰️
It's the exact same format that os:timestamp/0 and the deprecated erlang:now/0 use. Lowkey the only reason erlang:timestamp() even exists is so that legacy code which assumes this timestamp shape doesn't have to change. If you're writing something new, bestie — you can grab the current Erlang system time way more efficiently, in whatever time unit you want, with erlang:system_time/1. Periodt 💅
The erlang:timestamp() BIF is literally equivalent to this:
timestamp() ->
ErlangSystemTime = erlang:system_time(microsecond),
MegaSecs = ErlangSystemTime div 1000_000_000_000,
Secs = ErlangSystemTime div 1000_000 - MegaSecs*1000_000,
MicroSecs = ErlangSystemTime rem 1000_000,
{MegaSecs, Secs, MicroSecs}.
However 👀 it uses a native implementation that doesn't build garbage on the heap and performs slightly better. So it's the same vibes, just faster and cleaner.
NOTE: This time is not a monotonically increasing time in the general case. For more info, check the docs on time warp modes in the User's Guide. Do not come for me, I'm just the messenger 😭
tl(List) — gimme the tail 🦋
tl(List) -> Tail
when List :: nonempty_maybe_improper_list(), Tail :: term().
Returns the tail of List, which is just the list minus its first element. Iconic, simple, does what it says 💖
It works with improper lists too, no judgment.
Examples ✨
1> tl([geesties, guilies, beasties]).
[guilies, beasties]
2> tl([geesties]).
[]
3> tl([geesties, guilies, beasties | improper_end]).
[guilies, beasties | improper_end]
4> tl([geesties | improper_end]).
improper_end
5> tl([]).
** exception error: bad argument
in function tl/1
called as tl([])
*** argument 1: not a nonempty list
Failure: badarg if List is an empty list []. Yeah she does not play about the empty list 💀
trace(PidPortSpec, How, FlagList) — the og tracing girlie 🔍
trace(PidPortSpec, How, FlagList) -> integer()
when
PidPortSpec ::
pid() |
port() |
all | processes | ports | existing |
existing_processes | existing_ports | new |
new_processes | new_ports,
How :: boolean(),
FlagList :: [trace_flag()].
Turns trace flags on or off for processes or ports, for the static legacy trace session ✨
Change 🚨 This function is superseded bytrace:process/4andtrace:port/4, which operate on dynamic trace sessions. Just so you know, bestie — not me being dramatic, it's literally in the docs.
The FlagList argument can hold two extra options:
{tracer, Tracer}— tells it where to send the trace messages. Tracer has to be the process identifier of a local process, or the port identifier of a local port.{tracer, TracerModule, TracerState}— says a tracer module should be called instead of sending a trace message. The tracer module can then ignore or change the trace message. For the full tea on writing a tracer module, go look aterl_tracer🎀
If you don't specify a tracer at all, the calling process receives all the trace messages. The legacy trace session has no specified tracer, fyi.
For more docs, see trace:process/4 and trace:port/4 🫶
trace_delivered(Tracee) — no trace left behind 💅
trace_delivered(Tracee) -> Ref
when Tracee :: pid() | all, Ref :: reference().
Calling this function makes sure all trace messages have been delivered. Sounds simple, it is not, stay with me 🌸
Trace message delivery (the ones generated by erlang:trace/3, seq_trace, or erlang:system_profile/2) is dislocated on the timeline compared to other events in the system. So if you know Tracee has passed some specific point in its execution, and you wanna know when at least all the trace messages for events up to that point have reached the tracer, you call erlang:trace_delivered(Tracee).
Once it's guaranteed that all trace messages have been delivered to the tracer up to the point Tracee reached at the time of the call to erlang:trace_delivered(Tracee), a {trace_delivered, Tracee, Ref} message gets sent to whoever called erlang:trace_delivered(Tracee) 💌
Heads up though 👇
Notice that the messagetrace_delivereddoes not imply that trace messages have been delivered. It implies that all trace messages that are to be delivered have been delivered. And it's not an error if Tracee isn't — and hasn't been — traced by anyone, but if that's the case, no trace messages have been delivered by the time thetrace_deliveredmessage shows up. So maybe chill before you assume 👀
Another thing: Tracee must refer to a process currently or previously existing on the same node as the caller of erlang:trace_delivered(Tracee) lives on. The special Tracee atom all denotes all processes that currently are traced in the node 🌐
When used together with a Tracer Module, any message sent in the trace callback is guaranteed to have reached its recipient before the trace_delivered message is sent. Slay ✨
Example: Process A is Tracee, port B is the tracer, and process C is the port owner of B. C wants to close B when A exits. To make sure the trace isn't truncated, C can call erlang:trace_delivered(A) when A exits, and wait for the message {trace_delivered, A, Ref} before closing B. Chef's kiss, no cap 👑
Failure: badarg if Tracee does not refer to a process (dead or alive) on the same node as the caller of erlang:trace_delivered(Tracee) resides on. Wrong node, wrong vibe, hard no 🙅
trace_info(PidPortFuncEvent, Item) — spill the trace tea ☕
trace_info(PidPortFuncEvent, Item) -> Res
when
PidPortFuncEvent ::
pid() |
port() |
new | new_processes | new_ports |
{Module, Function, Arity} |
on_load | send | 'receive',
Module :: module(),
Function :: atom(),
Arity :: arity(),
Item ::
flags | tracer | traced | match_spec |
meta | meta_match_spec | call_count |
call_time | call_memory | all,
Res :: trace_info_return().
Returns trace info about a port, process, function, or event, for the static legacy trace session 🔎
Change 🚨 This function is superseded by trace:info/3, which operates on dynamic trace sessions.
trace_pattern(MFA, MatchSpec) — the shorthand 💫
trace_pattern(MFA, MatchSpec) -> non_neg_integer()
when
MFA :: trace_pattern_mfa() | send |
'receive',
MatchSpec ::
(MatchSpecList :: trace_match_spec()) |
boolean() |
restart | pause.
Equivalent to erlang:trace_pattern(Event, MatchSpec, []), kept around purely for backward compatibility. Blast from the past, we respect her 🎀
trace_pattern/3 — the full version 🌈
trace_pattern(send, MatchSpec, []) -> non_neg_integer()
when
MatchSpec ::
(MatchSpecList :: trace_match_spec()) |
boolean();
('receive', MatchSpec, []) -> non_neg_integer()
when
MatchSpec ::
(MatchSpecList :: trace_match_spec()) |
boolean();
(MFA, MatchSpec, FlagList) -> non_neg_integer()
when
MFA :: trace_pattern_mfa(),
MatchSpec ::
(MatchSpecList :: trace_match_spec()) |
boolean() |
restart | pause,
FlagList :: [trace_pattern_flag()].
Sets the trace pattern for call, send and receive tracing on the static legacy trace session ✨
Change 🚨 This function is superseded bytrace:function/4,trace:send/3andtrace:recv/3, which operate on dynamic trace sessions. Yeah, she's legacy, we still love her 💜
The FlagList argument can hold one extra option for call tracing:
{meta, Pid}|{meta, TracerModule, TracerState}— turns meta-tracing on or off for all types of function calls. Trace messages get sent to the tracer whenever any of the specified functions are called. If no tracer is specified,self/0is used as the default tracer process 👑 (yes, you become the tracer, main character energy)
For further docs, see trace:function/4, trace:send/3 and trace:recv/3 🫶
trunc(Number) — cut the decimals ✂️
trunc(Number) -> integer() when Number :: number().
Truncates the decimals of Number. Just chops them right off, no rounding, no mercy 💅
See also round/1, floor/1, and ceil/1 — the whole squad 🎀
Examples ✨
1> trunc(5.7).
5
2> trunc(-5.7).
-5
3> trunc(5).
5
4> trunc(36028797018963969.0).
36028797018963968
Now, that last one 👀 trunc(36028797018963969.0) evaluates to 36028797018963968. This happens because the number 36028797018963969.0 cannot be represented exactly as a floating-point value. Instead, it's represented as 36028797018963968.0, which is the closest representable floating-point value. See Representation of Floating Point Numbers for additional info 🌸 Floating point stays floating, bestie 😭
tuple_size(Tuple) — how many in there? 📦
tuple_size(Tuple) -> non_neg_integer() when Tuple :: tuple().
Returns the number of elements in Tuple. That's it, that's the whole function 💖
Examples ✨
1> tuple_size({a, b, c}).
3
tuple_to_list(Tuple) — tuple glow-up to list 🦋
tuple_to_list(Tuple) -> [term()] when Tuple :: tuple().
Returns a list corresponding to Tuple. Same contents, different outfit ✨
Examples ✨
1> tuple_to_list({share, {'Ericsson_B', 163}}).
[share,{'Ericsson_B',163}]
unalias(Alias) — bye bye alias 👋
unalias(Alias) -> boolean() when Alias :: reference().
Deactivates the alias Alias that was previously created by the calling process. Turning it off, closing the tab, logging out 💅
An alias can, for example, be created via alias/0 or monitor/3. unalias/1 will always deactivate the alias, regardless of what options were used when the alias was created. No exceptions, no loopholes.
Returns true if Alias was a currently active alias for the current processes; otherwise, false. Simple as that 🫶
🌈 unique_integer()
psst — for more info on process aliases, go check the Process Aliases section of the Erlang Reference Manual 💖
unique_integer() -> integer().
Generates and returns an integer that's unique on the current runtime system instance. It's literally the same thing as calling erlang:unique_integer([]) — same energy, less typing. ✨
💫 Examples
> erlang:unique_integer().
-576460752303422335
🦋 unique_integer(ModifierList)
unique_integer(ModifierList) -> integer()
when
ModifierList :: [Modifier],
Modifier :: positive | monotonic.
Generates and returns an integer unique on the current runtime system instance. 💅
It's unique in the sense that this BIF, using the same set of modifiers, does not return the same integer more than once on the current runtime system instance. Each integer value can of course be constructed by other means, so like… don't read too much into it. 😌
By default, when [] is passed as ModifierList, both negative and positive integers can be returned. Why? To use the range of integers that don't need heap memory allocation as much as possible, bestie — it's giving efficiency. By default the returned integers are also only guaranteed to be unique, that is, any returned integer can be smaller or larger than previously returned integers. No ordering promises, none, zero. 🙈
Modifiers:
positive— Returns only positive integers.
heads up: by passing the positive modifier you will get heap allocated integers (bignums) quicker. ⚠️
monotonic— Returns strictly monotonically increasing integers corresponding to creation time. That is, the integer returned is always larger than previously returned integers on the current runtime system instance.
These values can be used to determine order between events on the runtime system instance. That is, if both X = erlang:unique_integer([monotonic]) and Y = erlang:unique_integer([monotonic]) are executed by different processes (or the same process) on the same runtime system instance and X < Y, we know that X was created before Y. 👑
WARNING: Strictly monotonically increasing values are inherently quite expensive to generate and scales poorly. This is because the values need to be synchronized between CPU cores. That is, do not pass the monotonic modifier unless you really need strictly monotonically increasing values. fr fr, this one bites. 😭
All valid Modifiers can be combined. Repeated (valid) Modifiers in the ModifierList are ignored. ✨
NOTE: The set of integers returned byerlang:unique_integer/1using different sets ofModifiers will overlap. For example, by callingunique_integer([monotonic]), andunique_integer([positive, monotonic])repeatedly, you will eventually see some integers that are returned by both calls. 😳
Failures:
badarg— ifModifierListis not a proper list.badarg— ifModifieris not a valid modifier.
🍓 Examples
> erlang:unique_integer([positive]).
1186
⭐ universaltime()
universaltime() -> DateTime when DateTime :: calendar:datetime().
Returns the current date and time according to Universal Time Coordinated (UTC) in the form {{Year, Month, Day}, {Hour, Minute, Second}} if supported by the underlying OS. Otherwise erlang:universaltime() is equivalent to erlang:localtime(). The return value is based on the OS System Time. 🕰️
For example:
> erlang:universaltime().
{{1996,11,6},{14,18,43}}
🌸 universaltime_to_localtime(Universaltime)
universaltime_to_localtime(Universaltime) -> Localtime
when
Localtime ::
calendar:datetime(),
Universaltime ::
calendar:datetime().
Converts Universal Time Coordinated (UTC) date and time to local date and time in the form {{Year, Month, Day}, {Hour, Minute, Second}} if supported by the underlying OS. Otherwise no conversion is done, and Universaltime is returned as-is. 💖
For example:
> erlang:universaltime_to_localtime({{1996,11,6},{14,18,43}}).
{{1996,11,7},{15,18,43}}
Failure: badarg if Universaltime denotes an invalid date and time. 🚫
💅 unlink(Id)
unlink(Id) -> true when Id :: pid() | port().
Removes a link between the calling process and another process or a port identified by Id. 💫
We will from here on call the identified process or port unlinkee. yes, it's a real word now, we made it official.
A link can be set up using the link/1 BIF. For more information on links and exit signals due to links, see the Processes chapter in the Erlang Reference Manual:
- Links
- Sending Exit Signals
- Receiving Exit Signals
Once unlink(Id) has returned, it is guaranteed that the link between the caller and the unlinkee has no effect on the caller in the future (unless the link is setup again). Note that if the caller is trapping exits, an {'EXIT', Id, ExitReason} message due to the link may have been placed in the message queue of the caller before the unlink(Id) call completed. Also note that the {'EXIT', Id, ExitReason} message may be the result of the link, but may also be the result of the unlinkee sending the caller an exit signal by calling the exit_signal/2 BIF. So it's giving… ambiguous. 🙈 Therefore, it may or may not be appropriate to clean up the message queue after a call to unlink(Id) as follows, when trapping exits:
unlink(Id),
receive
{'EXIT', Id, _} ->
true
after 0 ->
true
end
The link removal is performed asynchronously. If such a link does not exist, nothing is done. A detailed description of the link protocol can be found in the Distribution Protocol chapter of the ERTS User's Guide. 📚
NOTE: For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual. 🔥
Failure: badarg if Id does not identify a process or a node local port.
🎀 unregister(RegName)
unregister(RegName) -> true when RegName :: atom().
Removes the registered name RegName associated with a process identifier or a port identifier from the name registry. bye bestie 👋
For example:
> unregister(db).
true
Keep in mind that you can still receive signals associated with the registered name after it has been unregistered, as the sender may have looked up the name before sending to it. sneaky but valid. 😌
Users are advised not to unregister system processes. 🚫
Failure: badarg if RegName is not a registered name.
🦋 whereis(RegName)
whereis(RegName) -> pid() | port() | undefined
when RegName :: atom().
Returns the process identifier or port identifier with the registered name RegName from the name registry. Returns undefined if the name is not registered. no name, no pid, that's the vibe check. 💫
For example:
> whereis(db).
<0.43.0>
👑 yield()
yield() -> true.
Tries to give other processes with the same or higher priority (if any) a chance to execute before returning. There is no guarantee that any other process runs between the invocation and return of erlang:yield/0. it's giving "maybe, maybe not" ✨
See the documentation for receive-after expressions for how to make the current process sleep for a specific number of milliseconds. 😴
WARNING: There is seldom or never any need to use this BIF. Using this BIF without a thorough grasp of how the scheduler works can cause performance degradation. The current implementation of this function puts the current process last in the current scheduler's queue for processes of the same priority as the current process. 💀 like… just don't, bestie.
and that's a wrap on erlang(3)!! 🎉 this page came to you from Ericsson AB, running the erts 17.0.6 era of the docs — go forth and spawn responsibly, you absolute icon. periodt. 💅💖
📦 where this page comes from
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 · Apache-2.0
- 💖 girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms