erlang(3erl)

โœจ NAME โœจ

erlang โ€” the Erlang BIFs and the predefined types ๐Ÿ’– (this is the erlang(3erl) page, aka the Erlang Module Definition, and honestly bestie it's kind of the main character of the whole manual)


๐ŸŒธ DESCRIPTION ๐ŸŒธ

Okay so here's the vibe: by convention, basically most of the Built-In Functions (BIFs) and all of the predefined types live in this module. Some of those BIFs โ€” and every single one of the predefined types โ€” are viewed more or less as part of the Erlang programming language itself, which means they're auto-imported. So you don't have to specify the module name, no cap. For example, these two calls are literally identical:

atom_to_list(erlang)
erlang:atom_to_list(erlang)

Notes on how the list in this reference is laid out, because it matters:

  • Auto-imported BIFs are listed without a module prefix. ๐Ÿซถ
  • BIFs listed with a module prefix are not auto-imported.

Predefined types are listed in the Predefined datatypes section of this reference manual, and also in the Types and Function Specifications section of the Erlang Reference Manual. ๐Ÿ“š

Now, the tea on failure: BIFs can fail for various reasons. All BIFs fail with reason badarg if they're called with arguments of an incorrect type. The other reasons are described in the description of each individual BIF โ€” so like, read the specific one, bestie.

Some BIFs can be used in guard tests and are marked with "Allowed in guard tests". ๐Ÿ‘‘


๐Ÿฆ‹ DATA TYPES ๐Ÿฆ‹

โœจ Predefined datatypes โœจ

any() = any()

All possible Erlang terms. It's a synonym for term(). Literally everything. ๐ŸŒˆ

arity() = arity()

The arity of a function or type.

atom() = atom()

An Erlang atom. ๐ŸŽ€

binary() = <<_:_*8>>

An Erlang binary โ€” that is, a bitstring with a size divisible by 8. Clean. Neat. Byte-aligned. ๐Ÿ’…

bitstring() = <<_:_*1>>

An Erlang bitstring.

boolean() = true | false

A boolean value. Yes or no, queen. โœจ

byte() = 0..255

A byte of data represented by an integer.

char() = 0..1114111

An ASCII character or a unicode codepoint presented by an integer.

float() = float()

An Erlang float.

function() = function()

An Erlang fun. ๐Ÿงš

identifier() = pid() | port() | reference()

A unique identifier for some entity โ€” for example a process, port or monitor.

integer() = integer()

An Erlang integer.

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() term to binary() you can use iolist_to_binary/2. To transcode a string() or unicode:chardata() to iodata() you can use unicode:characters_to_binary/1.

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() instead of this type. Like, genuinely. Take the hint. ๐Ÿ™ˆ

list() = [any()]

An Erlang list containing terms of any type.

list(ContentType) = [ContentType]

An Erlang list containing terms of the type ContentType.

map() = #{any() => any()}

An Erlang map containing any number of key and value associations. ๐Ÿ—บ๏ธ

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)

An Erlang list that is not guaranteed to end with a [], and where the list elements are of the type ContentType.

mfa() = {module(), atom(), arity()}

A three-tuple representing a Module:Function/Arity function signature. iykyk ๐Ÿ’…

module() = atom()

An Erlang module represented by an atom.

neg_integer() = integer() =< -1

A negative integer.

nil() = []

The empty list().

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

An Erlang node represented by an atom.

non_neg_integer() = integer() >= 0

A non-negative integer โ€” that is, any positive integer or 0.

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() for the sake of clarity. โœจ

nonempty_binary() = <<_:8, _:_*8>>

A binary() that contains some data.

nonempty_bitstring() = <<_:1, _:_*1>>

A bitstring() that contains some data.

nonempty_improper_list(ContentType, TerminationType) = nonempty_improper_list(ContentType, TerminationType)

A maybe_improper_list/2 that contains some items.

nonempty_list() = [any(), ...]

A list() that contains some items.

nonempty_list(ContentType) = [ContentType, ...]

A list(ContentType) that contains some items.

nonempty_maybe_improper_list() = nonempty_maybe_improper_list(any(), any())

A maybe_improper_list() that contains some items.

nonempty_maybe_improper_list(ContentType, TerminationType) = nonempty_maybe_improper_list(ContentType, TerminationType)

A maybe_improper_list(ContentType, TerminationType) that contains some items.

nonempty_string() = [char(), ...]

A string() that contains some characters.

number() = integer() | float()

An Erlang number.

pid() = pid()

An Erlang process identifier. ๐Ÿซถ

port() = port()

An Erlang port identifier.

pos_integer() = integer() >= 1

An integer greater than zero.

reference() = reference()

An Erlang reference.

string() = [char()]

A character string represented by a list of ASCII characters or unicode codepoints.

term() = any()

All possible Erlang terms. Synonym for any(). ๐ŸŒ€

timeout() = infinity | integer() >= 0

A timeout value that can be passed to a receive expression.

tuple() = tuple()

An Erlang tuple.


๐Ÿ’œ Other Datatypes ๐Ÿ’œ

ext_binary() = binary()

A binary data object, structured according to the Erlang external term format.

ext_iovec() = iovec()

A term of type iovec(), structured according to the Erlang external term format.

iovec() = [binary()]

A list of binaries. This datatype is useful to use together with enif_inspect_iovec.

message_queue_data() = off_heap | on_heap

See process_flag(message_queue_data, MQD).

monitor_option() = {alias, explicit_unalias | demonitor | reply_demonitor} | {tag, term()}

See monitor/3.

timestamp() = {MegaSecs :: integer() >= 0, Secs :: integer() >= 0, MicroSecs :: integer() >= 0}

See erlang:timestamp/0.

time_unit() = integer() >= 1 | second | millisecond | microsecond | nanosecond | native | perf_counter | deprecated_time_unit()

Supported time unit representations, bestie โ€” here's the whole roster:

  • 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 at runtime system start, and remains the same until the runtime system terminates. If a runtime system is stopped and then started again (even on the same machine), the native time unit of the new runtime system instance can differ from the native time unit of the old runtime system instance.

One 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 does not add up to a whole number, the result is 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 gives no information about the accuracy of time values. The resolution of the native time unit and the resolution of time values can differ significantly. โš ๏ธ
  • 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() โ€” deprecated symbolic representations kept for backwards-compatibility.

The time_unit/0 type can be extended. To convert time values between time units, use erlang:convert_time_unit/3.

deprecated_time_unit() = seconds | milli_seconds | micro_seconds | nano_seconds

The time_unit() type also consists of the following deprecated symbolic time units โ€” they're giving "still here for legacy reasons" ๐Ÿ’€:

  • seconds โ€” same as second.
  • milli_seconds โ€” same as millisecond.
  • micro_seconds โ€” same as microsecond.
  • nano_seconds โ€” same as nanosecond.

dist_handle()

An opaque handle identifying a distribution channel.

nif_resource()

An opaque handle identifying a NIF resource object.

Options for spawn_opt(). ๐Ÿ‘‘

  • priority_level() = low | normal | high | max โ€” it's the process priority level, bestie. For more info see process_flag(priority, Level) ๐Ÿ’…
  • max_heap_size() =
integer() >= 0 |
#{size => integer() >= 0,
  kill => boolean(),
  error_logger => boolean()}

That's the process max heap size configuration ๐ŸŒธ For more info see process_flag(max_heap_size, MaxHeapSize)

  • message_queue_data() = off_heap | on_heap โ€” process message queue data configuration โœจ For more information, see process_flag(message_queue_data, MQD)
  • stacktrace() =
[{module(),
  atom(),
  arity() | [term()],
  [stacktrace_extrainfo()]} |
 {function(), arity() | [term()], [stacktrace_extrainfo()]}]
  • stacktrace_extrainfo() =
{line, integer() >= 1} |
{file, unicode:chardata()} |
{error_info,
 #{module => module(), function => atom(), cause => term()}} |
{atom(), term()}

An Erlang stacktrace, exactly as described by the Errors and Error Handling section in the Erlang Reference Manual ๐Ÿซถ

  • send_destination() =
pid() |
reference() |
port() |
(RegName :: atom()) |
{RegName :: atom(), Node :: node()}

This is the destination for a send operation โ€” could be a remote or local process identifier, a (local) port, a reference denoting a process alias, a locally registered name, or a tuple {RegName, Node} for a registered name at another node ๐Ÿ“ฌ iykyk


โœจ EXPORTS โœจ

abs/1

abs(Float) -> float()

abs(Int) -> integer() >= 0

Types:

  • Int = integer()

Returns an integer or float that's the arithmetical absolute value of Float or Int โ€” negativity cancelled, periodt โœจ For example:

> abs(-3.33).
3.33
> abs(-3).
3

Allowed in guard tests ๐Ÿ‘‘


erlang:adler32/1

erlang:adler32(Data) -> integer() >= 0

Types:

  • Data = iodata()

Computes and returns the adler32 checksum for Data ๐Ÿงฎ slay


erlang:adler32/2

erlang:adler32(OldAdler, Data) -> integer() >= 0

Types:

  • OldAdler = integer() >= 0
  • Data = iodata()

Keeps computing the adler32 checksum by combining the previous checksum, OldAdler, with the checksum of Data ๐Ÿ’–

So this code:

X = erlang:adler32(Data1),
Y = erlang:adler32(X,Data2).

assigns the same value to Y as this does:

Y = erlang:adler32([Data1,Data2]).

erlang:adler32_combine/3

erlang:adler32_combine(FirstAdler, SecondAdler, SecondSize) ->
                          integer() >= 0

Types:

  • FirstAdler = SecondAdler = SecondSize = integer() >= 0

Combines two previously computed adler32 checksums ๐Ÿงš This computation needs the size of the data object for the second checksum to be known โ€” no guessing allowed, fr fr.

So this code:

Y = erlang:adler32(Data1),
Z = erlang:adler32(Y,Data2).

assigns the same value to Z as this does:

X = erlang:adler32(Data1),
Y = erlang:adler32(Data2),
Z = erlang:adler32_combine(X,Y,iolist_size(Data2)).

alias/0, alias/1

alias() -> Alias

alias(Opts) -> Alias

Types:

  • Alias = reference()
  • Opts = [explicit_unalias | reply]

Creates an alias ๐Ÿ’ซ which 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. An alias can be deactivated with unalias/1. Currently available options for alias/1:

  • explicit_unalias โ€” the alias can only be deactivated via a call to unalias/1. This is also the default behaviour if no options are passed or if alias/0 is called ๐ŸŽ€
  • reply โ€” the alias is automatically deactivated when a reply message sent via the alias is received. The alias can also still be deactivated via a call to unalias/1 ๐Ÿ‘‘

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.
Heads up bestie: 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 ๐ŸŒˆ


erlang:append_element/2

erlang:append_element(Tuple1, Term) -> Tuple2

Types:

  • Tuple1 = Tuple2 = tuple()
  • Term = term()

Returns a new tuple with one more element than Tuple1, containing the elements in Tuple1 followed by Term as the last element ๐Ÿงฉ Semantically equivalent to list_to_tuple(tuple_to_list(Tuple1) ++ [Term]), but much faster ๐Ÿ”ฅ Example:

> erlang:append_element({one, two}, three).
{one,two,three}

apply/2

apply(Fun, Args) -> term()

Types:

  • Fun = function()
  • Args = [term()]

Calls a fun, passing the elements in Args as arguments ๐Ÿ’–

If the number of elements in the arguments is known at compile time, the call is better written as Fun(Arg1, Arg2, ... ArgN) โœจ

Warning: โš ๏ธ Earlier, Fun could also be specified as {Module, Function}, equivalent to apply(Module, Function, Args). This use is deprecated and will stop working in a future release. So likeโ€ฆ don't ๐Ÿ’€

apply/3

apply(Module, Function, Args) -> term()

Types:

  • 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. Example:

> apply(lists, reverse, [[a, b, c]]).
[c,b,a]
> apply(erlang, atom_to_list, ['Erlang']).
"Erlang"

If the number of arguments is 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 isn't 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 ๐Ÿ˜ญ


atom_to_binary/1

atom_to_binary(Atom) -> binary()

Types:

  • Atom = atom()

The same as atom_to_binary(Atom, utf8) ๐Ÿ’ซ


atom_to_binary/2

atom_to_binary(Atom, Encoding) -> binary()

Types:

  • Atom = atom()
  • Encoding = latin1 | unicode | utf8

Returns a binary corresponding to the text representation of Atom ๐Ÿฆ‹ If Encoding is latin1, one byte exists for each character in the text representation. If Encoding is utf8 or unicode, the characters are encoded using UTF-8, where characters may require multiple bytes โœจ

Note: 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 ๐Ÿ’€

Example:

> atom_to_binary('Erlang', latin1).
<<"Erlang">>

atom_to_list/1

atom_to_list(Atom) -> string()

Types:

  • Atom = atom()

Returns a list of unicode code points corresponding to the text representation of Atom, for example ๐ŸŒธ:

> atom_to_list('Erlang').
"Erlang"

> atom_to_list('ไฝ ๅฅฝ').
[20320,22909]

See unicode(3erl) for how to convert the resulting list to different formats ๐Ÿซถ


binary_part/2

binary_part(Subject, PosLen) -> binary()

Types:

  • Subject = binary()
  • PosLen = {Start :: integer() >= 0, Length :: integer()}

Extracts the part of the binary described by PosLen โœ‚๏ธ

Negative length can be used to extract bytes at the end of a binary, for example:

1> Bin = <<1,2,3,4,5,6,7,8,9,10>>.
2> binary_part(Bin,{byte_size(Bin), -5}).
<<6,7,8,9,10>>

Failure: badarg if PosLen in any way references outside the binary ๐Ÿšซ

Start is zero-based, that is:

1> Bin = <<1,2,3>>
2> binary_part(Bin,{0,2}).
<<1,2>>

For details about the PosLen semantics, see binary(3erl) ๐Ÿ“–

Allowed in guard tests ๐Ÿ‘‘


binary_part/3

binary_part(Subject, Start, Length) -> binary()

Types:

  • Subject = binary()
  • Start = integer() >= 0
  • Length = integer()

The same as binary_part(Subject, {Start, Length}) ๐Ÿ’…

Allowed in guard tests ๐Ÿ‘‘


binary_to_atom/1

binary_to_atom(Binary) -> atom()

Types:

  • Binary = binary()

The same as binary_to_atom(Binary, utf8) โœจ


binary_to_atom/2

binary_to_atom(Binary, Encoding) -> atom()

Types:

  • Binary = binary()
  • Encoding = latin1 | unicode | utf8

Returns the atom whose text representation is Binary ๐ŸŽ€ If Encoding is utf8 or unicode, the binary must contain valid UTF-8 sequences.

Note: as from Erlang/OTP 20, binary_to_atom(Binary, utf8) is capable of decoding any Unicode character. Earlier versions would fail if the binary contained Unicode characters > 255.
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 Advanced) ๐Ÿ“
Note: there is a configurable limit on how many atoms that can exist, and atoms are not garbage collected ๐Ÿ—‘๏ธ So it's recommended to consider whether binary_to_existing_atom/2 is a better option than binary_to_atom/2. The default limits can be found in the efficiency guide (section Advanced).

Examples:

> binary_to_atom(<<"Erlang">>, latin1).
'Erlang'

> binary_to_atom(<<1024/utf8>>, utf8).

binary_to_existing_atom(Binary) -> atom()

Types:

Binary = binary()

Literally the same vibe as binary_to_existing_atom(Binary, utf8) โ€” same function, just with the encoding picked for you ๐Ÿ’ซ

binary_to_existing_atom(Binary, Encoding) -> atom()

Types:

Binary = binary()
Encoding = latin1 | unicode | utf8

So it's binary_to_atom/2 but with trust issues โ€” the atom has to already exist, no exceptions ๐Ÿซถ

Bestie, listen: the Erlang system has a configurable limit for the total number of atoms that can exist, and atoms are not garbage collected. So it is not safe to create loads of atoms from binaries that come from an untrusted source (like, say, a file you fetched from the Internet, iykyk) โ€” for example 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's created programmatically (for example by binary_to_atom/2). And there's a note further down with an example of when an atom exists in the source code of an Erlang module but not in the compiled version of that same module. Sneaky ๐Ÿ‘€

Failure: badarg if the atom does not exist.

Note: the compiler may optimize atoms away. Like, it will rewrite atom_to_list(some_atom) to "some_atom". If that expression is the only mention of the atom some_atom in the containing module, the atom will not be created when the module is loaded, and a subsequent call to binary_to_existing_atom(<<"some_atom">>, utf8) will fail. Rude but true ๐Ÿ˜ญ
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 Advanced).

binary_to_float(Binary) -> float()

Types:

Binary = binary()

Returns the float whose text representation is Binary, for example:

> binary_to_float(<<"2.2017764e+0">>).
2.2017764

The float string format is the same as the format for Erlang float literals, except that underscores are not permitted โ€” so no pretty-printing your numbers here, bestie ๐ŸŽ€

Failure: badarg if Binary contains a bad representation of a float.

binary_to_integer(Binary) -> integer()

Types:

Binary = binary()

Returns an integer whose text representation is Binary, for example:

> binary_to_integer(<<"123">>).
123

binary_to_integer/1 accepts the same string formats as list_to_integer/1 โœจ

Failure: badarg if Binary contains a bad representation of an integer.

binary_to_integer(Binary, Base) -> integer()

Types:

Binary = binary()
Base = 2..36

Returns an integer whose text representation in base Base is Binary, for example:

> binary_to_integer(<<"3FF">>, 16).
1023

binary_to_integer/2 accepts the same string formats as list_to_integer/2 ๐Ÿ’…

Failure: badarg if Binary contains a bad representation of an integer.

binary_to_list(Binary) -> [byte()]

Types:

Binary = binary()

Returns a list of integers corresponding to the bytes of Binary. Simple as that, slay ๐ŸŒธ

binary_to_list(Binary, Start, Stop) -> [byte()]

Types:

Binary = binary()
Start = Stop = integer() >= 1
  1..byte_size(Binary)

Same as binary_to_list/1, but returns a list of integers corresponding to the bytes from position Start to position Stop in Binary. Heads up: the positions in the binary are numbered starting from 1 ๐Ÿฆ‹

Note: the one-based indexing for binaries used by this function is deprecated. New code is to use binary:bin_to_list/3 in STDLIB instead. All functions in module binary consistently use zero-based indexing. So like, this one's a little vintage, no cap ๐Ÿ’€

binary_to_term(Binary) -> term()

Types:

Binary = ext_binary()

Returns an Erlang term that is the result of decoding the binary object Binary, which must be encoded according to the Erlang external term format ๐Ÿ”ฅ

> Bin = term_to_binary(hello).
<<131,100,0,5,104,101,108,108,111>>
> hello = binary_to_term(Bin).
hello
โš ๏ธ 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 attack. In such cases, consider using binary_to_term/2 with the safe option. Please please please, bestie ๐Ÿ™ˆ

See also term_to_binary/1 and binary_to_term/2.

binary_to_term(Binary, Opts) -> term() | {term(), Used}

Types:

Binary = ext_binary()
Opt = safe | used
Opts = [Opt]
Used = integer() >= 1

As binary_to_term/1, but it takes these options ๐Ÿ‘‡

  • 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 ๐Ÿ’€

This prevents creation of new atoms directly, creation of new atoms indirectly (as they're embedded in certain structures, such as process identifiers, refs, and funs), and creation of new external function references. None of those resources are garbage collected, so unchecked creation of them can exhaust available memory. So yeah, main character energy for your memory, but in a bad way ๐Ÿ˜ญ

> binary_to_term(<<131,100,0,5,"hello">>, [safe]).
** exception error: bad argument
> hello.
hello
> binary_to_term(<<131,100,0,5,"hello">>, [safe]).
hello
โš ๏ธ Warning: the safe option ensures the data is safely processed by the Erlang runtime, but it does not guarantee the data is safe to your application. You must always validate data from untrusted sources. And if the binary is stored or transits through untrusted sources, you should also consider cryptographically signing it. Fr fr, do the extra work ๐Ÿซถ
  • used โ€” changes the return value to {Term, Used} where Used is the number of bytes actually read from Binary.
> Input = <<131,100,0,5,"hello","world">>.
<<131,100,0,5,104,101,108,108,111,119,111,114,108,100>>
> {Term, Used} = binary_to_term(Input, [used]).
{hello, 9}
> split_binary(Input, Used).
{<<131,100,0,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) -> integer() >= 0

Types:

Bitstring = bitstring()

Returns an integer that is the size in bits of Bitstring, for example:

> bit_size(<<433:16,3:3>>).
19
> bit_size(<<1,2,3>>).
24

Allowed in guard tests โœจ (guard-test icon behavior, we love to see it)

bitstring_to_list(Bitstring) -> [byte() | bitstring()]

Types:

Bitstring = bitstring()

Returns a list of integers corresponding to the bytes of Bitstring. But here's the twist ๐ŸŒ€ โ€” if the number of bits in the binary is not divisible by 8, the last element of the list is a bitstring containing the remaining 1-7 bits. Examples:

> bitstring_to_list(<<433:16>>).
[1,177]

> bitstring_to_list(<<433:16,3:3>>).
[1,177,<<3:3>>]

See, that last one is just a tiny bitstring vibing at the end ๐Ÿ‘‘

erlang:bump_reductions(Reductions) -> true

Types:

Reductions = integer() >= 1

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 like, don't build your whole personality on it ๐Ÿ’€

byte_size(Bitstring) -> integer() >= 0

Types:

Bitstring = bitstring()

Returns an integer that is the number of bytes needed to contain Bitstring. That is, if the number of bits in Bitstring is not divisible by 8, the resulting number of bytes is rounded up ๐Ÿงš Examples:

> byte_size(<<433:16,3:3>>).
3
> byte_size(<<1,2,3>>).
3

Allowed in guard tests ๐ŸŒˆ

erlang:cancel_timer(TimerRef) -> Result

Types:

TimerRef = reference()
Time = integer() >= 0
Result = Time | false

Cancels a timer โฐ The same as calling erlang:cancel_timer(TimerRef, []).

erlang:cancel_timer(TimerRef, Options) -> Result | ok

Types:

TimerRef = reference()
Async = Info = boolean()
Option = {async, Async} | {info, Info}
Options = [Option]
Time = integer() >= 0
Result = Time | false

Cancels a timer that has been created by erlang:start_timer or erlang:send_after. TimerRef identifies the timer, and was returned by the BIF that created the timer ๐Ÿซถ

Options:

  • {async, Async} โ€” asynchronous request for cancellation. Async defaults to false, which causes the cancellation to be performed synchronously. When Async is set to true, the cancel operation is performed asynchronously. That is, cancel_timer() sends an asynchronous request for cancellation to the timer service that manages the timer, and then returns ok ๐Ÿ’…
  • {info, Info} โ€” requests information about the Result of the cancellation. Info defaults to true, which means the Result is given. When Info is set to false, no information about the result of the cancellation is given ๐Ÿ™ˆ
    • When Async is false: if Info is true, the Result is returned by erlang:cancel_timer(). otherwise ok is returned.
  • When Async is true: if Info is true, a message on the form {cancel_timer, TimerRef, Result} is sent to the caller of erlang:cancel_timer() when the cancellation operation has been performed, otherwise no message is sent.

More Options may be added in the future. fr fr, they left the door open for more options later ๐Ÿ‘€

If Result is an integer, it represents the time in milliseconds left until the canceled timer would have expired.

If Result is false, a timer corresponding to TimerRef could not be found. This can be either because the timer had expired, already had been canceled, or because TimerRef never corresponded to a timer. Even if the timer had expired, it does not tell you if the time-out message has arrived at its destination yet.

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 critical path, and can do other things while waiting for the result of this operation, or is not interested in the result of the operation, you want to use option {async, true}. If using option {async, false}, the calling process blocks until the operation has been performed.

See also erlang:send_after/4, erlang:start_timer/4, and erlang:read_timer/2. iykyk โฑ๏ธโœจ


ceil(Number) -> integer()

Types:

Number = number()

Returns the smallest integer not less than Number. For example:

> ceil(5.5).
6

Allowed in guard tests. slay โœ…


check_old_code(Module) -> boolean()

Types:

Module = module()

Returns true if Module has old code, otherwise false.

See also code(3erl). old-code detective era ๐Ÿ”


check_process_code(Pid, Module) -> CheckResult

Types:

Pid = pid()
Module = module()
CheckResult = boolean()

The same as check_process_code(Pid, Module, []).


check_process_code(Pid, Module, OptionList) -> CheckResult | async

Types:

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 executes old code for Module.

Options:

  • {allow_gc, boolean()} โ€” Determines if garbage collection is allowed when performing the operation. If {allow_gc, false} is passed, and a garbage collection is needed to determine the result of the operation, the operation is aborted (see information on CheckResult below). The default is to allow garbage collection, that is, {allow_gc, true}.
  • {async, RequestId} โ€” The function check_process_code/3 returns the value async immediately 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 {check_process_code, RequestId, CheckResult}.

If Pid equals self(), and no async option has been passed, the operation is performed at once. Otherwise a request for the operation is sent to the process identified by Pid, and is handled when appropriate. If no async option has been passed, the caller blocks until CheckResult is available and can be returned.

CheckResult informs about the result of the request as follows:

  • true โ€” The process identified by Pid executes old code for Module. 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 references old code for this module.
  • false โ€” The process identified by Pid does not execute old code for Module.
  • aborted โ€” The operation was aborted, as the process needed to be garbage collected to determine the operation result, and the operation was requested by passing option {allow_gc, false}.
Note: Up until ERTS version 8.*, the check process code operation checks 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(3erl). ERTS lore drop ๐Ÿ“š

Failures:

  • badarg โ€” If Pid is not a node local process identifier.
  • badarg โ€” If Module is not an atom.
  • badarg โ€” If OptionList is an invalid list of options.

erlang:convert_time_unit(Time, FromUnit, ToUnit) -> ConvertedTime

Types:

Time = ConvertedTime = integer()
FromUnit = ToUnit = time_unit()

Converts the Time value of time unit FromUnit to the corresponding ConvertedTime value of time unit ToUnit. The result is rounded using the floor function.

Warning: You can lose accuracy and precision when converting between time units. To minimize such loss, collect all data at native time unit and do the conversion on the end result.

math girlie warning โš ๏ธ๐Ÿ’…


erlang:crc32(Data) -> integer() >= 0

Types:

Data = iodata()

Computes and returns the crc32 (IEEE 802.3 style) checksum for Data.


erlang:crc32(OldCrc, Data) -> integer() >= 0

Types:

OldCrc = integer() >= 0
Data = iodata()

Continues computing the crc32 checksum by combining the previous checksum, OldCrc, with the checksum of Data.

The following code:

X = erlang:crc32(Data1),
Y = erlang:crc32(X,Data2).

assigns the same value to Y as this:

Y = erlang:crc32([Data1,Data2]).

checksum continuity, no cap ๐Ÿงฎโœจ


erlang:crc32_combine(FirstCrc, SecondCrc, SecondSize) -> integer() >= 0

Types:

FirstCrc = SecondCrc = SecondSize = integer() >= 0

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:

Y = erlang:crc32(Data1),
Z = erlang:crc32(Y,Data2).

assigns the same value to Z as this:

X = erlang:crc32(Data1),
Y = erlang:crc32(Data2),
Z = erlang:crc32_combine(X,Y,iolist_size(Data2)).

date() -> Date

Types:

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. Example:

> date().
{1995,2,19}

calendar core memory unlocked ๐Ÿ—“๏ธ๐Ÿซถ


erlang:decode_packet(Type, Bin, Options) -> {ok, Packet, Rest} | {more, Length} | {error, Reason}

Okay this one is a big type situation, bestie โ€” every alternative is listed here, no skipping ๐Ÿ’…

Types:

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, integer() >= 0} |
    {line_length, integer() >= 0}
Packet = binary() | HttpPacket
Rest = binary()
Length = integer() >= 0 | 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 :: integer() >= 0, Minor :: integer() >= 0}
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 decode_packet takes Bin and decodes it according to whichever packet protocol Type names ๐Ÿ’… โ€” literally the same packet shuffling the sockets do when you hand them {packet,Type}.

If the whole packet is sitting in Bin, bestie, you get it back with the leftovers as {ok,Packet,Rest} โœจ

If Bin doesn't have the entire packet yet? You get {more,Length}. Length is either the expected total size of the packet, or undefined if the expected packet size is unknown ๐Ÿคทโ€โ™€๏ธ โ€” then just call decode_packet again with more data piled on.

If the packet is out here not conforming to the protocol format at all, you get {error,Reason} ๐Ÿ’€

โœจ Types โœจ

  • raw | 0 โ€” no packet handling whatsoever, the entire binary comes back unless it's empty ๐Ÿซถ
  • 1 | 2 | 4 โ€” packets are a header saying how many bytes are in the packet, followed by exactly that many bytes. Header length can be one, two, or four bytes, and the byte order is big-endian. The header gets stripped off when the packet is returned โœ‚๏ธ
  • line โ€” a packet is line-terminated by a delimiter byte, default is the latin-1 newline character. The delimiter byte is included in the returned packet unless the line was truncated according to option line_length ๐ŸŽ€
  • asn1 | cdr | sunrm | fcgi | tpkt โ€” the header is not stripped off. The meanings, for the curious:
    • asn1 โ€” ASN.1 BER:
    • sunrm โ€” Sun's RPC encoding:
    • cdr โ€” CORBA (GIOP 1.1):
    • fcgi โ€” Fast CGI:
    • tpkt โ€” TPKT format [RFC1006]:
  • http | httph | http_bin | httph_bin โ€” the Hypertext Transfer Protocol, bestie ๐ŸŒˆ Packets come back in the format according to HttpPacket described earlier. A packet is either a request, a response, a header, or an end of header mark. Invalid lines are returned as HttpError ๐Ÿ˜ญ

Recognized request methods and header fields are returned as atoms ๐Ÿ’– Others are returned as strings. Strings of unrecognized header fields are formatted with only capital letters first and after hyphen characters, for example, "Sec-Websocket-Key". Header field names are also returned in UnmodifiedField as strings, without any conversion or formatting โ€” raw and unfiltered, we love that for them ๐Ÿ‘‘

The protocol type http is only to be used for the first line when an HttpRequest or an HttpResponse is expected. The following calls are to use httph to get HttpHeaders until http_eoh is returned, which marks the end of the headers and the beginning of any following message body ๐Ÿฆ‹

The variants http_bin and httph_bin return strings (HttpString) as binaries instead of lists.

โœจ Options โœจ

  • {packet_size, integer() >= 0} โ€” sets the maximum allowed size of the packet body. If the packet header indicates that the length of the packet is longer than the maximum allowed length, the packet is considered invalid ๐Ÿšซ Defaults to 0, which means no size limit.
  • {line_length, integer() >= 0} โ€” for packet type line, lines longer than the indicated length are truncated โœ‚๏ธ

Option line_length also applies to http* packet types as an alias for option packet_size if packet_size itself is not set. This use is only intended for backward compatibility, iykyk ๐Ÿซถ

  • {line_delimiter, 0 =< byte() =< 255} โ€” for packet type line, sets the delimiting byte. Default is the latin-1 character $\n ๐ŸŒธ

โœจ Examples โœจ

> erlang:decode_packet(1,<<3,"abcd">>,[]).
{ok,<<"abc">>,<<"d">>}
> erlang:decode_packet(1,<<5,"abcd">>,[]).
{more,6}

erlang:delete_element(Index, Tuple1) -> Tuple2

Types

Index = integer() >= 1
  1..tuple_size(Tuple1)
Tuple1 = Tuple2 = tuple()

Returns a brand new tuple with the element at Index removed from tuple Tuple1 ๐ŸŽ€ like so:

> erlang:delete_element(2, {one, two, three}).
{one,three}

Gone. Not invited. Periodt ๐Ÿ’…

delete_module(Module) -> true | undefined

Types

Module = module()

Makes the current code for Module become old code and deletes all references for this module from the export table ๐Ÿ—‘๏ธ Returns undefined if the module does not exist, otherwise true.

Warning: this BIF is intended for the code server (see code(3erl)) and is not to be used elsewhere ๐Ÿ™ˆ

Failure: badarg if there already is an old version of Module ๐Ÿ’€

demonitor(MonitorRef) -> true

Types

MonitorRef = reference()

If MonitorRef is a reference that the calling process obtained by calling monitor/2, this monitoring is turned off ๐Ÿ›‘ If the monitoring is already turned off, nothing happens โ€” no drama, no consequences.

Once demonitor(MonitorRef) has returned, it is guaranteed that no {'DOWN', MonitorRef, _, _, _} message, because of the monitor, will be placed in the caller message queue in the future ๐Ÿ‘‘ However, a {'DOWN', MonitorRef, _, _, _} message can have been placed in the caller message queue before the call ๐Ÿ˜ญ It is therefore usually advisable to remove such a 'DOWN' message from the message queue after monitoring has been stopped. demonitor(MonitorRef, [flush]) can be used instead of demonitor(MonitorRef) if this cleanup is wanted ๐Ÿงน

Note: before Erlang/OTP R11B (ERTS 5.5) demonitor/1 behaved completely asynchronously, that is, the monitor was active until the "demonitor signal" reached the monitored entity. This had one undesirable effect: you could never know when you were guaranteed not to receive a DOWN message because of the monitor ๐Ÿ˜ตโ€๐Ÿ’ซ The current behavior can be viewed as two combined operations: asynchronously send a "demonitor signal" to the monitored entity and ignore any future results of the monitor โœจ

Failure: it is an error if MonitorRef refers to a monitoring started by another process. Not all such cases are cheap to check. If checking is cheap, the call fails with badarg, for example if MonitorRef is a remote reference ๐Ÿ’€

demonitor(MonitorRef, OptionList) -> boolean()

Types

MonitorRef = reference()
OptionList = [Option]
Option = flush | info

The returned value is true unless info is part of OptionList ๐Ÿซถ

demonitor(MonitorRef, []) is equivalent to demonitor(MonitorRef).

โœจ Options โœจ

  • 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 these babies:
    • 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 ๐Ÿ’–

Note: more options can be added in a future release ๐Ÿ‘€

Failures

  • badarg โ€” if OptionList is not a list.
  • badarg โ€” if Option is an invalid option.
  • badarg โ€” the same failure as for demonitor/1.

disconnect_node(Node) -> boolean() | ignored

Types

Node = node()

Forces the disconnection of a node ๐Ÿ˜ค This appears to the node Node as if the local node has crashed โ€” brutal, honestly. 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 ๐Ÿซถ

erlang:display(Term) -> true

Types

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.

erlang:dist_ctrl_get_data(DHandle) -> {Size, Data} | Data | none

Types

Size = integer() >= 0
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. One 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 ๐ŸŒธ

erlang:dist_ctrl_get_opt(DHandle, Opt :: get_size) -> Value

Types

Types:

DHandle = dist_handle()
Value = boolean()

Okay so this one hands you back the value of the get_size option on the distribution channel identified by DHandle. For the full tea on that option, 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.

erlang:dist_ctrl_get_data_notification(DHandle) -> ok

Types:

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. When more data is present, the caller will be sent the message dist_data. Once a dist_data messages has been sent, no more dist_data messages will be sent until the dist_ctrl_get_data_notification/1 function has been called again. ๐Ÿฆ‹

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.

erlang:dist_ctrl_input_handler(DHandle, InputHandler) -> ok

Types:

DHandle = dist_handle()
InputHandler = pid()

Register an alternate input handler process for the distribution channel identified by DHandle. 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: 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.

erlang:dist_ctrl_put_data(DHandle, Data) -> ok

Types:

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 by DHandle is allowed to call this function unless an alternate input handler process has been registered using erlang: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 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.

erlang:dist_ctrl_set_opt(DHandle, Opt :: get_size, Value) -> OldValue

Types:

DHandle = dist_handle()
Value = 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 DHandle used when setting this option. When the get_size option is:

  • false โ€” and there are distribution data available, a call to erlang:dist_ctrl_get_data(DHandle) will just return Data to pass over the channel. This is the default value of the get_size option.
  • true โ€” and there are distribution data available, a call to erlang:dist_ctrl_get_data(DHandle) will return Data to pass over the channel as well as the Size of Data in bytes. This is returned as a tuple on 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. 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.

element(N, Tuple) -> term()

Types:

N = integer() >= 1
  1..tuple_size(Tuple)
Tuple = tuple()

Returns the Nth element (numbering from 1) of Tuple, for example:

> element(2, {a, b, c}).
b

Allowed in guard tests. โœจ

erase() -> [{Key, Val}]

Types:

Key = Val = term()

Returns the process dictionary and deletes it, for example:

> put(key1, {1, 2, 3}),
put(key2, [a, b, c]),
erase().
[{key1,{1,2,3}},{key2,[a,b,c]}]

erase(Key) -> Val | undefined

Types:

Key = Val = term()

Returns the value Val associated with Key and deletes it from the process dictionary. Returns undefined if no value is associated with Key. 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. Example:

> put(key1, {merry, lambs, are, playing}),
X = erase(key1),
{X, erase(key1)}.
{{merry,lambs,are,playing},undefined}

error(Reason) -> no_return()

Types:

Reason = term()

Raises an exception of class error with the reason Reason. As evaluating this function causes an exception to be thrown, it has no return value.

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. Example:

> catch error(foobar).
{'EXIT',{foobar,[{shell,apply_fun,3,
                        [{file,"shell.erl"},{line,906}]},
                 {erl_eval,do_apply,6,[{file,"erl_eval.erl"},{line,677}]},
                 {erl_eval,expr,5,[{file,"erl_eval.erl"},{line,430}]},
                 {shell,exprs,7,[{file,"shell.erl"},{line,687}]},
                 {shell,eval_exprs,7,[{file,"shell.erl"},{line,642}]},
                 {shell,eval_loop,3,[{file,"shell.erl"},{line,627}]}]}}

error(Reason, Args) -> no_return()

Types:

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 it is a list, it is used to provide the arguments for the current function in the stack back-trace. If it is none, the arity of the calling function is used in the stacktrace. As evaluating this function causes an exception to be raised, it has no return value.

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. Example:

test.erl:

-module(test).
-export([example_fun/2]).

example_fun(A1, A2) ->
    erlang:error(my_error, [A1, A2]).

Erlang shell:

6> c(test).
{ok,test}
7> 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()

Types:

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 it is a list, it is used to provide the arguments for the current function in the stack back-trace. If it is none, the arity of the calling function is used in the stacktrace. As evaluating this function causes an exception to be raised, it has no return value.

If the error_info option is given, the ErrorInfoMap will be inserted into the stacktrace. The information given in the ErrorInfoMap is to be used by error formatters such as erl_error to provide more context around an error.

The default module of the ErrorInfoMap is the module that 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

...the whole point of the exception class error is to shout "bestie, something UNEXPECTED happened" โ€” like a function getting called with a parameter that has the wrong type. ๐Ÿšจ Want the full tea? Check the guide about errors and error handling.

exit(Reason) -> no_return()

Types:

Reason = term()

Raises an exception of class exit with exit reason Reason. And because evaluating this function throws an exception, it never returns anything โ€” it's giving "I'm out, no forwarding address" energy. ๐Ÿ’…

The whole intent of the exception class exit is that the current process should be stopped โ€” like when a process gets a message saying "okay you can go now". ๐Ÿซถ

How is this different from error/1,2,3? Two things: it raises an exception of a different class, and its reason does not include the list of functions from the call stack. Lowkey cleaner that way.

See the guide about errors and error handling for the extra lore.

Example:

> exit(foobar).
** exception exit: foobar
> catch exit(foobar).
{'EXIT',foobar}
Note: If a process calls exit(kill) and does not catch the exception, it will terminate with exit reason kill and also emit exit signals with exit reason kill (not killed) to all linked processes. Those exit signals with exit reason kill can be trapped by the linked processes. So heads up: signals with exit reason kill behave differently depending on how they're sent, because the signal is untrappable if a process sends such a signal to another process with erlang:exit/2. Wild, ik. ๐Ÿ˜ญ

exit(Pid, Reason) -> true

Types:

Pid = pid() | port()
Reason = term()

Sends an exit signal with exit reason Reason to the process or port identified by Pid. โœจ

Here's what goes down if Reason is any term except normal or kill, and P is the process or port identified by Pid:

  • 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}, where From is the process identifier of the process that sent the exit signal, and it gets delivered to the message queue of P.

And here's the vibe if Reason is the term normal and Pid is the identifier of a process P which is not the same as the process that invoked erlang:exit(Pid, normal) โ€” (the case where a process sends a signal with the normal reason to itself is covered in the warning below ๐Ÿ‘‡):

  • If P is trapping exits, the exit signal is transformed into a message {'EXIT', From, normal}, where From is the process identifier of the process that sent the exit signal, and it's delivered to P's message queue.
  • The signal has no effect if P is not trapping exits.

If Reason is the atom kill โ€” that is, if exit(Pid, kill) is called โ€” an untrappable exit signal gets sent to the process identified by Pid, which unconditionally exits with exit reason killed. ๐Ÿ’€ The exit reason gets changed from kill to killed to hint to linked processes that the killed process got killed by a call to exit(Pid, kill). Sneaky but helpful.

Note: The functions erlang:exit/1 and erlang:exit/2 have similar names but provide very different functionalities. Use erlang:exit/1 when your intent is to stop the current process, and erlang:exit/2 when your intent is to send an exit signal to another process. Also note that erlang:exit/1 raises an exception that can be caught, while erlang:exit/2 does not cause any exception to be raised at all. Different beasts, same-ish name, iykyk. ๐Ÿฆ‹
Warning: There's exactly one scenario the description above didn't cover: when a process P sends an exit signal with reason normal to itself, that is erlang:exit(self(), normal). Here's how that goes: - If P is trapping exits, the exit signal is transformed into a message {'EXIT', From, normal}, where From is P's process identifier, and delivered to P's message queue. - P exits with reason normal if P is not trapping exits. Note that this behavior is different from when a process sends an exit signal with reason normal to another process. Is that arguably strange? Yeah bestie, it kinda is ๐Ÿ™ˆ โ€” but it's kept around for backward compatibility reasons.

erlang:external_size(Term) -> integer() >= 0

Types:

Term = term()

Calculates the maximum byte size for a term encoded in the Erlang external term format โ€” without actually doing the encoding. Efficiency icon behavior. โœจ

This condition always holds:

> Size1 = byte_size(term_to_binary(Term)),
> Size2 = erlang:external_size(Term),
> true = Size1 =< Size2.
true

It's literally equivalent to a call to:

erlang:external_size(Term, [])

erlang:external_size(Term, Options) -> integer() >= 0

Types:

Term = term()
Options = [{minor_version, Version :: integer() >= 0}]

Same deal: calculates the maximum byte size for a term encoded in the Erlang external term format, without encoding it. And this condition always holds:

> Size1 = byte_size(term_to_binary(Term, Options)),
> Size2 = erlang:external_size(Term, Options),
> true = Size1 =< Size2.
true

The option {minor_version, Version} specifies how floats are encoded โ€” for the full breakdown, peep term_to_binary/2.

float(Number) -> float()

Types:

Number = number()

Returns a float by converting Number to a float. Slay, look:

> float(55).
55.0

Allowed in guard tests. โœ…

Note: If you use it on the top level in a guard, it tests whether the argument is a floating point number โ€” but for clarity, just use is_float/1 instead. ๐ŸŽ€ When float/1 shows up in an expression in a guard, like 'float(A) == 4.0', it converts a number as described earlier.

float_to_binary(Float) -> binary()

Types:

Float = float()

The same as float_to_binary(Float,[{scientific,20}]).

float_to_binary(Float, Options) -> binary()

Types:

Float = 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 exactly the same way as in float_to_list/2. Examples, because seeing it is believing:

> float_to_binary(7.12, [{decimals, 4}]).
<<"7.1200">>
> float_to_binary(7.12, [{decimals, 4}, compact]).
<<"7.12">>
> float_to_binary(7.12, [{scientific, 3}]).
<<"7.120e+00">>
> float_to_binary(7.12, [short]).
<<"7.12">>
> float_to_binary(0.1+0.2, [short]).
<<"0.30000000000000004">>
> float_to_binary(0.1+0.2)
<<"3.00000000000000044409e-01">>

float_to_list(Float) -> string()

Types:

Float = float()

The same as float_to_list(Float,[{scientific,20}]).

float_to_list(Float, Options) -> string()

Types:

Float = 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. ๐Ÿ’–

Available options, bestie:

  • If option decimals is specified, the returned value contains at most Decimals number of digits past the decimal point. If the number doesn't fit in the internal static buffer of 256 bytes, the function throws badarg. ๐Ÿ˜ค
  • If option compact is specified, the trailing zeros at the end of the list are truncated. This option is only meaningful together with option decimals.
  • If option scientific is specified, the float is formatted using scientific notation with Decimals digits of precision.
  • If option short is specified, the float is formatted with the smallest number of digits that still guarantees that F =:= 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. ๐Ÿงš
  • If Options is [], the function behaves as float_to_list/1.

Examples:

> float_to_list(7.12, [{decimals, 4}]).
"7.1200"
> float_to_list(7.12, [{decimals, 4}, compact]).
"7.12"
> float_to_list(7.12, [{scientific, 3}]).
"7.120e+00"
> float_to_list(7.12, [short]).
"7.12"
> float_to_list(0.1+0.2, [short]).
"0.30000000000000004"
> float_to_list(0.1+0.2)
"3.00000000000000044409e-01"

In that last example, float_to_list(0.1+0.2) evaluates to "3.00000000000000044409e-01". Why? Glad you asked โ€” the reason is explained in Representation of Floating Point Numbers. ๐Ÿฆ‹

floor(Number) -> integer()

Types:

Number = number()

Returns the largest integer not greater than Number. Like so:

> floor(-10.5).
-11

Allowed in guard tests. โœ…

erlang:fun_info(Fun) -> [{Item, Info}]

Types:

Fun = 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. Each list element is a tuple. Heads up though: the order of the tuples is undefined, and more tuples can be added in a future release. So don't go assuming, bestie. ๐Ÿ’…

Warning: This BIF is mainly intended for debugging, but it can sometimes be useful in library functions that need to verify, for example, the arity of a fun. ๐ŸŽ€

Two types of funs have slightly different semantics, and this is where it gets real:

  • A fun made with fun M:F/A is an external fun. Call it and it always calls the function F with arity A in the latest code for module M. And bestie, module M does not even need to be loaded when fun M:F/A is created. ๐Ÿคฏ
  • Every other fun is called local. When a local fun is called, it calls the same version of the code that created the fun, even if a newer version of the module has been loaded. No cap.

For both local and external funs, these elements are always present in the list:

  • {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 where the fun is defined.
    • If Fun is an external fun, Module is the module 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.

These elements are only present in the list if Fun is local:

  • {pid, Pid} โ€” Pid is the process identifier of the process that originally created the fun.

It might point to the init process if Fun was statically allocated when the module was loaded (this optimisation is performed for local functions that do not capture the environment).

  • {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.

erlang:fun_info(Fun, Item) -> {Item, Info} โœจ

Types:

Fun = function()
Item = fun_info_item()
Info = term()
fun_info_item() =
    arity | env | index | name | module | new_index | new_uniq |
    pid | type | uniq

Returns information about Fun as specified by Item, in the form {Item,Info}.

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

See erlang:fun_info/1.

erlang:fun_to_list(Fun) -> String :: string() ๐ŸŽ€

Types:

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>", where M, I and U correspond to the values named module, index and uniq in the result of erlang: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 use fun_to_list/1 to check if two funs are equal, because fun_to_list/1 does not take the fun's environment into account. See erlang:fun_info/1 for how to get the environment of a fun. ๐Ÿ’…
Note: 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.

erlang:function_exported(Module, Function, Arity) -> boolean() ๐Ÿฆ‹

Types:

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. ๐Ÿ˜ญ

garbage_collect(Pid) -> GCResult

Types:

Pid = pid()
GCResult = boolean()

The same as garbage_collect(Pid, []).

garbage_collect(Pid, OptionList) -> GCResult | async

Types:

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 function garbage_collect/2 returns the value async immediately 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(), 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 by Pid has been garbage collected.
  • false โ€” No garbage collection was performed, as the process identified by Pid terminated before the request could be satisfied.

Notice that the same caveats apply as for garbage_collect/0.

Failures:

  • badarg โ€” If Pid is not a node local process identifier.
  • badarg โ€” If OptionList is an invalid list of options.

get() -> [{Key, Val}] ๐Ÿ“

Types:

Key = Val = term()

Returns the process dictionary as a list of {Key, Val} tuples. The items in the returned list can be in any order. Example:

> put(key1, merry),
put(key2, lambs),
put(key3, {are, playing}),
get().
[{key1,merry},{key2,lambs},{key3,{are,playing}}]

get(Key) -> Val | undefined

Types:

Key = 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. Example:

> put(key1, merry),
put(key2, lambs),
put({any, [valid, term]}, {are, playing}),
get({any, [valid, term]}).
{are,playing}

Types:

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.

Types:

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] ๐Ÿ”‘

Types:

Key = term()

Returns a list of all keys that are currently chilling in the process dictionary, bestie. The order? Absolutely unhinged, no promises, the items can come back in any order. Example:

> put(dog, {animal,1}),
put(cow, {animal,2}),
put(lamb, {animal,3}),
get_keys().
[dog,cow,lamb]

get_keys(Val) -> [Key]

Types: Val = Key = term()

Okay so this one is giving "search by vibe" โ€” it returns a list of keys that are associated with the value Val in the process dictionary. Same deal as before: the order in the returned list is literally whatever, don't @ me. Example:

> put(mary, {1, 2}),
put(had, {1, 2}),
put(a, {1, 2}),
put(little, {1, 2}),
put(dog, {1, 3}),
put(lamb, {1, 2}),
get_keys({1, 2}).
[mary,had,a,little,lamb]

group_leader() -> pid()

Returns the process identifier of the group leader for the process that's evaluating the function. ๐Ÿซถ

So every process is a member of some process group, and every group has a group leader. All I/O from the group gets channeled to the group leader โ€” yes, all of it. When a new process is spawned, it inherits the same group leader as the spawning process (main character nepotism, honestly). At system startup, init is both its own group leader and the group leader of all processes. Iconic.

group_leader(GroupLeader, Pid) -> true

Types: GroupLeader = Pid = pid()

Sets the group leader of Pid to GroupLeader. Typically this is used when a process started from a certain shell needs to have a different group leader than init โ€” like, it wants to sit at a different lunch table. ๐Ÿ“

Gen Z warning bestie: the group leader should rarely be changed in applications that have a supervision tree, because OTP assumes that the group leader of their processes is their application master. So likeโ€ฆ don't just go changing it for fun, fr fr.

Setting the group leader follows the signal ordering guarantees described in the Processes Chapter in the Erlang Reference Manual.

See also group_leader/0 and the OTP design principles related to starting and stopping applications. โœจ

halt() -> no_return()

Exactly the same as halt(0, []). No cap. Example:

> halt().
os_prompt%

halt(Status) -> no_return()

Types: Status = integer() >= 0 | abort | string()

Same as halt(Status, []). Example:

> halt(17).
os_prompt% echo $?
17
os_prompt%

halt(Status, Options) -> no_return()

Types:

Status = integer() >= 0 | abort | string()
Options = [Option]
Option = {flush, boolean()}

Status must be a non-negative integer, a string, or the atom abort. This halts the Erlang runtime system. It has no return value โ€” it's giving exit, stage left, permanently. ๐Ÿ’€ Depending on Status, here's what goes down:

  • integer() โ€” the runtime system exits with the integer value Status as the status code handed to the calling environment (the OS).
Note: on many platforms, the OS only supports status codes 0-255. A too-large status code gets truncated by clearing the high bits. So your 256 is about to become a very humbling number.
  • string() โ€” an Erlang crash dump is produced with Status as the slogan. Then the runtime system exits with status code 1. The string gets truncated if it's longer than 200 characters.
Note: before ERTS 9.1 (OTP-20.1) only code points in the range 0-255 were accepted in the string. Now any unicode string is valid. We love progress. ๐Ÿฆ‹
  • abort โ€” the runtime system aborts, producing a core dump, if that's enabled in the OS.

For an integer Status, the Erlang runtime system closes all ports and allows async threads to finish their operations before exiting. Wanna dip out without that flushing? Pass the option as {flush,false}.

For the string() and abort statuses, the flush option is ignored and flushing is not done. Periodt.

hd(List) -> term()

Types: List = [term(), ...]

Returns the head of List โ€” that is, the first element. The literal first born. Example:

> hd([1,2,3,4,5]).
1

Allowed in guard tests. ๐Ÿ‘‘

Failure: badarg if List is the empty list []. (Empty list has no head, bestie, it's just vibes.)

erlang:hibernate(Module, Function, Args) -> no_return()

Types:

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. This is super useful if the process isn't expecting to receive any messages any time soon โ€” it's the "going to sleep with a face mask on" of concurrency. ๐Ÿงš

The process gets 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 the process terminates when that function returns. So erlang:hibernate/3 never returns to its caller, like, ever. The resume function Module:Function/Arity must be exported (Arity =:= length(Args)).

If the process has any message in its message queue, it gets awakened immediately, same way as described above.

Getting more technical (ngl this part is kind of a flex): erlang:hibernate/3 discards the call stack for the process, and then garbage collects the process. After that, all live data sits in one continuous heap. The heap is then shrunken to the exact same size as the live data 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 that happens after the process is awakened makes sure the heap size is changed to a size not smaller than the minimum heap size.

Heads up queen: emptying the call stack means any surrounding catch is removed and has to be re-inserted after hibernation. One effect of this is that processes started using proc_lib (also indirectly, such as gen_server processes) should use proc_lib:hibernate/3 instead, to make sure the exception handler keeps working when the process wakes up. Don't skip this, it's important fr fr. ๐Ÿ˜ญ

erlang:insert_element(Index, Tuple1, Term) -> Tuple2

Types:

Index = integer() >= 1
  1..tuple_size(Tuple1) + 1
Tuple1 = Tuple2 = tuple()
Term = term()

Returns a new tuple with element Term inserted at position Index in tuple Tuple1. Every element from position Index and upwards gets pushed one step higher in the new tuple Tuple2. Shove over, everyone, we're making room. Example:

> erlang:insert_element(2, {one, two, three}, new).
{one,new,two,three}

integer_to_binary(Integer) -> binary()

Types: Integer = integer()

Returns a binary corresponding to the text representation of Integer. Look at it go. Example:

> integer_to_binary(77).
<<"77">>

integer_to_binary(Integer, Base) -> binary()

Types:

Integer = integer()
Base = 2..36

Returns a binary corresponding to the text representation of Integer in base Base. Base goes from 2 to 36, so pick your fighter. Example:

> integer_to_binary(1023, 16).
<<"3FF">>

integer_to_list(Integer) -> string()

Types: Integer = integer()

Returns a string corresponding to the text representation of Integer. Same energy as integer_to_binary/1 but make it a list. Example:

> integer_to_list(77).
"77"

integer_to_list(Integer, Base) -> string()

Types:

Integer = integer()
Base = 2..36

Returns a string corresponding to the text representation of Integer in base Base. Again: base 2 through 36. Example:

> integer_to_list(1023, 16).
"3FF"

iolist_size(Item) -> integer() >= 0

Types: Item = iolist() | binary()

Returns an integer, that is the size in bytes, of the binary that would be the result of iolist_to_binary(Item). So it's like, window shopping for the size instead of buying the whole binary. Very efficient of you. Example:

> iolist_size([1,2|<<3,4>>]).
4

iolist_to_binary(IoListOrBinary) -> binary()

Types: IoListOrBinary = iolist() | binary()

Returns a binary that's made from the integers and binaries in IoListOrBinary. Glow-up into a single flat binary. โœจ Example:

> Bin1 = <<1,2,3>>.
<<1,2,3>>
> Bin2 = <<4,5>>.
<<4,5>>
> Bin3 = <<6>>.
<<6>>
> iolist_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6>>

erlang:iolist_to_iovec(IoListOrBinary) -> iovec()

Types: IoListOrBinary = iolist() | binary()

Returns an iovec that's made from the integers and binaries in IoListOrBinary. This function is useful when you want to flatten an iolist but you do not need a single binary โ€” honestly kind of a niche queen move. This can be useful for passing the data to NIF functions such as enif_inspect_iovec or for doing more efficient message passing. The advantage of using this function over iolist_to_binary/1 is that it doesn't have to copy off-heap binaries. Zero copying, maximum slay. Example:

> Bin1 = <<1,2,3>>.
<<1,2,3>>
> Bin2 = <<4,5>>.
<<4,5>>
> Bin3 = <<6>>.
<<6>>
%% If you pass small binaries and integers it works as iolist_to_binary
> erlang:iolist_to_iovec([Bin1,1,[2,3,Bin2],4|Bin3]).
[<<1,2,3,1,2,3,4,5,4,6>>]
%% If you pass larger binaries, they are split and returned in a form
%% optimized for calling the C function writev.
> 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,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 (that is, if the node can be part of a distributed system), otherwise false. A node is alive if it's started with:

  • "erl -name LONGNAME" or,
  • "erl -sname SHORTNAME".

A node can also be alive if it has gotten a name from a call to net_kernel:start/1 and hasn't been stopped by a call to net_kernel:stop/0. Consortium of liveness, basically. ๐ŸŒˆ

is_atom(Term) -> boolean()

Types: Term = term()

Returns true if Term is an atom, otherwise false.

Allowed in guard tests. ๐Ÿ’…

is_binary(Term) -> boolean()

Types: Term = term()

Returns true if Term is a binary, otherwise false.

A binary always contains a complete number of bytes โ€” no half-byte shenanigans, we don't do that here.

Allowed in guard tests. โญ

is_bitstring(Term) -> boolean()

Types:

is_bitstring(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a bitstring (that includes a binary, bestie โœจ), otherwise false.

Allowed in guard tests.


is_boolean(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is the atom true or the atom false (like, an actual boolean ๐Ÿ’…). Otherwise it's giving false.

Allowed in guard tests.


erlang:is_builtin(Module, Function, Arity) -> boolean()

Types:

  • Module = module()
  • Function = atom()
  • Arity = arity()

This BIF is lowkey for the builders of cross-reference tools ๐Ÿ”ง like fr that's its whole thing.

Returns true if Module:Function/Arity is a BIF implemented in C, otherwise false. No cap.


is_float(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a floating point number, otherwise false.

Allowed in guard tests.


is_function(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a fun ๐ŸŽ€, otherwise false.

Allowed in guard tests.


is_function(Term, Arity) -> boolean()

Types:

  • Term = term()
  • Arity = arity()

Returns true if Term is a fun that can be applied with Arity number of arguments, otherwise false.

Allowed in guard tests.


is_integer(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is an integer, otherwise false.

Allowed in guard tests.


is_list(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a list with zero or more elements, otherwise false. Yes, even the empty list counts, she's valid ๐Ÿ’…

Allowed in guard tests.


is_map(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a map, otherwise false.

Allowed in guard tests.


is_map_key(Key, Map) -> boolean()

Types:

  • Key = term()
  • Map = map()

Returns true if map Map contains Key and returns false if it does not contain the Key ๐Ÿ—๏ธ

The call fails with a {badmap,Map} exception if Map is not a map. Like, if you hand her something that isn't even a map? she's not doing that ๐Ÿ’€

Example:

> Map = #{"42" => value}.
#{"42" => value}
> is_map_key("42",Map).
true
> is_map_key(value,Map).
false

Allowed in guard tests.


is_number(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is an integer or a floating point number. Otherwise returns false.

Allowed in guard tests.


is_pid(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a process identifier, otherwise false.

Allowed in guard tests.


is_port(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a port identifier, otherwise false.

Allowed in guard tests.


is_process_alive(Pid) -> boolean()

Types:

  • Pid = pid()

Pid must refer to a process at the local node. Local only, bestie, no long-distance vibes ๐Ÿ›ฐ๏ธ

Returns true if the process exists and is alive, that is, is not exiting and has not exited. Otherwise returns false.

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 that one can use is_process_alive/1 to let a process P1 wait until a process P2, which has got an exit signal with reason kill from P1, is killed. Example:

exit(P2Pid, kill),
% P2 might not be killed
is_process_alive(P2Pid),
% P2 is not alive (the call above always return false)

See the documentation about signals and erlang:exit/2 for more information about signals and exit signals. It's giving required reading ๐Ÿ“š


is_record(Term, RecordTag) -> boolean()

Types:

  • Term = term()
  • RecordTag = atom()

Returns true if Term is a tuple and its first element is RecordTag. Otherwise returns false.

Note: Normally the compiler treats calls to is_record/2 especially. It emits code to verify that Term is a tuple, that its first element is RecordTag, and that the size is correct. However, if RecordTag is not a literal atom, the BIF is_record/2 is called instead and the size of the tuple is not verified. ๐Ÿ™ˆ

Allowed in guard tests, if RecordTag is a literal atom.


is_record(Term, RecordTag, Size) -> boolean()

Types:

  • Term = term()
  • RecordTag = atom()
  • Size = integer() >= 0

RecordTag must be an atom. Non-negotiable ๐Ÿ’…

Returns true if Term is a tuple, its first element is RecordTag, and its size is Size. Otherwise returns false.

Allowed in guard tests if RecordTag is a literal atom and Size is a literal integer.

Note: This BIF is documented for completeness. Usually is_record/2 is to be used. Like, is_record/3 is the understudy, not the main character ๐Ÿ‘‘

is_reference(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a reference, otherwise false.

Allowed in guard tests.


is_tuple(Term) -> boolean()

Types:

  • Term = term()

Returns true if Term is a tuple, otherwise false.

Allowed in guard tests.


length(List) -> integer() >= 0

Types:

  • List = [term()]

Returns the length of List, for example:

> length([1,2,3,4,5,6,7,8,9]).
9

Allowed in guard tests.


link(PidOrPort) -> true

Types:

  • PidOrPort = pid() | port()

Sets up and activates a link between the calling process and another process or a port identified by PidOrPort. We will from here on call the identified process or port linkee. Yes, that's the technical term, we don't make the rules ๐Ÿซถ 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 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

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.

Failure:

  • badarg if PidOrPort does not identify a process or a node local port.
  • noproc linkee does not exist and it is "cheap" to check if it exists as described above.

list_to_atom(String) -> atom()

Types:

  • String = string()

Returns the atom whose text representation is String.

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: The number of characters that are permitted in an atom name is limited. The default limits can be found in the efficiency guide (section Advanced).
Note: There is configurable limit on how many atoms that can exist and atoms are not garbage collected. Therefore, it is recommended to consider if list_to_existing_atom/1 is a better option than list_to_atom/1. The default limits can be found in the efficiency guide (section Advanced). Bestie pls don't spawn infinite atoms, they never leave ๐ŸงŸโ€โ™€๏ธ

Example:

> list_to_atom("Erlang").
'Erlang'

list_to_binary(IoList) -> binary()

Types:

  • IoList = iolist()

Returns a binary that is made from the integers and binaries in IoList, for example:

> Bin1 = <<1,2,3>>.
<<1,2,3>>
> Bin2 = <<4,5>>.
<<4,5>>
> Bin3 = <<6>>.
<<6>>
> 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()

Types:

  • BitstringList = bitstring_list()
  • bitstring_list() = maybe_improper_list(byte() | bitstring() | bitstring_list(), bitstring() | [])

Returns a bitstring that is made from the integers and bitstrings in BitstringList. (The last tail in BitstringList is allowed to be a bitstring.) Example:

> Bin1 = <<1,2,3>>.
<<1,2,3>>
> Bin2 = <<4,5>>.
<<4,5>>
> Bin3 = <<6,7:4>>.
<<6,7: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()

Types:

  • String = string()

Returns the atom whose text representation is String, but only if there already exists such atom. An atom exists if it has been created by the run-time system by either loading code or creating a term in which the atom is part. Like, she only knows atoms she's already been introduced to ๐Ÿ’… iykyk

Failure: badarg if there does not already exist an atom whose text representation is String.

๐Ÿ’– okay so, tiny but MASSIVE note before we keep going: the compiler can literally optimize away atoms. Like, it will rewrite atom_to_list(some_atom) into "some_atom" right there at compile time. So if that expression is the only place some_atom is mentioned in the whole module, the atom never gets created when the module loads โ€” and then your later call to list_to_existing_atom("some_atom") will fail. Not a bug, bestie, just the compiler being efficient. ๐Ÿซถ

list_to_float(String) -> float()

Types:

String = string()

Gives you back the float whose text representation is String. Example time:

> list_to_float("2.2017764e+0").
2.2017764

The float string format is the same as the format for Erlang float literals โ€” except underscores aren't allowed. Sorry. ๐Ÿ™ˆ

Failure: badarg if String contains a bad representation of a float.


list_to_integer(String) -> integer()

Types:

String = string()

Returns an integer whose text representation is String. Watch:

> list_to_integer("123").
123

> list_to_integer("-123").
-123

> list_to_integer("+123234982304982309482093833234234").
123234982304982309482093833234234

String has to contain at least one digit character, and it can have an optional prefix of a single "+" or "-". Basically, String must match the regular expression "^[+-]?[0-9]+$". That's the vibe check it has to pass. โœจ

Failure: badarg if String contains a bad representation of an integer.


list_to_integer(String, Base) -> integer()

Types:

String = string()
Base = 2..36

Same deal, but the integer's text representation is in base Base. Observe:

> list_to_integer("3FF", 16).
1023

> list_to_integer("+3FF", 16).
1023

> list_to_integer("3ff", 16).
1023

> list_to_integer("3fF", 16).
1023

> list_to_integer("-3FF", 16).
-1023

So for example, when Base is 16, String must match "^[+-]?([0-9]|[A-F]|[a-f])+$". Case-insensitive slay. ๐Ÿ’…

Failure: badarg if String contains a bad representation of an integer.


list_to_pid(String) -> pid()

Types:

String = string()

Hands you a process identifier whose text representation is String. Like:

> list_to_pid("<0.4.1>").
<0.4.1>

Failure: badarg if String contains a bad representation of a process identifier.

๐Ÿšจ Warning: this BIF is intended for debugging and is not to be used in application programs. It's a backstage-pass function, not a main-character one.

list_to_port(String) -> port()

Types:

String = string()

Returns a port identifier whose text representation is String:

> list_to_port("#Port<0.4>").
#Port<0.4>

Failure: badarg if String contains a bad representation of a port identifier.

๐Ÿšจ Warning: again, this BIF is for debugging only โ€” do not use it in application programs, fr fr.

list_to_ref(String) -> reference()

Types:

String = string()

Returns a reference whose text representation is String. Behold:

> list_to_ref("#Ref<0.4192537678.4073193475.71181>").
#Ref<0.4192537678.4073193475.71181>

Failure: badarg if String contains a bad representation of a reference.

๐Ÿšจ Warning: yes queen, debugging BIF again. Not for application programs. ๐Ÿ˜ญ

list_to_tuple(List) -> tuple()

Types:

List = [term()]

Returns a tuple that corresponds to List. Example:

> list_to_tuple([share, ['Ericsson_B', 163]]).
{share, ['Ericsson_B', 163]}

And List can hold any Erlang terms. Anything. No judgement. ๐ŸŒˆ


load_module(Module, Binary) -> {module, Module} | {error, Reason}

Types:

Module = module()
Binary = binary()
Reason =
    badfile | not_purged | on_load |
    {features_not_allowed, [atom()]}

If Binary contains the object code for module Module, this BIF loads that object code. And if code for Module already exists? All export references get replaced so they point to the newly loaded code โ€” and the previously loaded code sticks around in the system as old code, because there can still be processes out there executing it. Can't just vanish on them. ๐Ÿซถ

Returns either {module, Module}, or {error, Reason} if loading fails. Reason is one of these bad boys:

  • badfile โ€” the object code in Binary has an incorrect format, or the object code actually contains code for a different module than Module. Catfish behaviour.
  • not_purged โ€” Binary contains a module that can't be loaded because old code for this module already exists.
  • on_load โ€” the code in Binary contains an on_load declaration that must be executed before Binary can become the current code. Any previous current code for Module stays put until the on_load call has finished.
  • not_allowed โ€” the code in Binary was compiled with features that are currently not enabled in the runtime system. ๐Ÿ’€
๐Ÿšจ Warning: this BIF is intended for the code server (see code(3erl)) and is not to be used elsewhere. Stay in your lane, bestie.

erlang:load_nif(Path, LoadInfo) -> ok | Error

Types:

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. 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). Heads up though: on most OSs the library has to have a different name on disc when you upgrade the NIF โ€” because if the name is the same but the contents differ, the old library may get loaded instead. Sneaky. ๐Ÿ˜ญ For info on how to actually implement a NIF library, go see erl_nif(3erl).

LoadInfo can be any term. It gets passed on to the library as part of the initialization, and a good practice is to include a module version number to support future code upgrade scenarios. Future-proofing, iconic behaviour. โœจ

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, and Text is a human-readable string that can give you more info about the failure:

  • load_failed โ€” the OS failed to load the NIF library.
  • 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. Gone gone.
  • old_code โ€” the call to load_nif/2 was made from the old code of a module that has been upgraded; this is not allowed. Nope. ๐Ÿ™…

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 don't have to be implemented by the dynamic library โ€” which is actually a whole vibe, because it lets a target-independent Erlang file contain fallback implementations for functions that may lack NIF support depending on the target OS/hardware platform. Best of both worlds. ๐Ÿฆ‹


erlang:loaded() -> [Module]

Types:

Module = module()

Returns a list of all loaded Erlang modules (current and old code), including preloaded modules. Everybody's invited to this party. ๐ŸŽ€

See also code(3erl).


erlang:localtime() -> DateTime

Types:

DateTime = calendar:datetime()

Gives you the current local date and time as {{Year, Month, Day}, {Hour, Minute, Second}}. Like:

> erlang:localtime().
{{1996,11,6},{14,45,17}}

The time zone and Daylight Saving Time correction depend on the underlying OS, and the return value is based on the OS System Time. So it's the OS's world, we're just living in it. ๐Ÿ’œ


erlang:localtime_to_universaltime(Localtime) -> Universaltime

Types:

Localtime = Universaltime = calendar:datetime()

Converts local date and time to Universal Time Coordinated (UTC) โ€” if the underlying OS supports it. Otherwise no conversion happens and you just get Localtime straight back. 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.


erlang:localtime_to_universaltime(Localtime, IsDst) -> Universaltime

Types:

Localtime = Universaltime = calendar:datetime()
IsDst = true | false | undefined

Same conversion as erlang:localtime_to_universaltime/1, except you get to decide whether Daylight Saving Time is active instead of letting the OS guess. Main character energy. ๐Ÿ‘‘

  • If IsDst == true, then Localtime is during Daylight Saving Time.
  • If IsDst == false, it is not.
  • If IsDst == undefined, the underlying OS can guess โ€” which is literally the same as calling erlang:localtime_to_universaltime(Localtime).

Examples, because we love receipts:

> 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. It's unique among connected nodes. โœจ

๐Ÿšจ Warning: before OTP-23, when a node was restarted multiple times with the same node name, references created on a newer node could be mistaken for a reference created on an older node with the same node name. So if you're on ancient OTP... be aware. ๐Ÿ’€

erlang:make_tuple(Arity, InitialValue) -> tuple()

Types:

โ€ฆand the types are literally right there, so stay tuned for the next message, bestie ๐ŸŽ€๐Ÿ’–

           Arity = arity()
           InitialValue = term()

so like, erlang:make_tuple/2 (the one from before, we're still on it bestie, don't scroll away) โ€” it creates a brand-new tuple of the size you asked for, Arity, and literally every single element is just InitialValue copied over and over. iconic lazy-girl behavior honestly. example:

> erlang:make_tuple(4, []).
{[],[],[],[]}

๐ŸŽ€ erlang:make_tuple(Arity, DefaultValue, InitList) -> tuple() ๐ŸŽ€

Types:

Arity = arity()
DefaultValue = term()
InitList = [{Position :: integer() >= 1, term()}]

okay so this one is the fancy version. it makes a tuple of size Arity where every element is DefaultValue, and then it goes through InitList and fills in the specific spots you care about. ๐Ÿ’…

every list element inside InitList has to be a two-tuple: first element is a position in the freshly created tuple, second element is literally any term you want. and heads up โ€” if a position shows up more than once in the list, the term from the last occurrence is the one that wins. no cap. example:

> erlang:make_tuple(5, [], [{2,ignored},{5,zz},{2,aa}]).
{[],aa,[],[],zz}

see how {2,ignored} got completely ghosted by {2,aa}? yeah. last one eats. ๐Ÿ“

๐Ÿฆ‹ map_get(Key, Map) -> Value ๐Ÿฆ‹

Types:

Map = map()
Key = Value = any()

returns the Value that's associated with Key, but only if Map actually contains Key.

the call fails with a {badmap,Map} exception if Map isn't a map at all, or with a {badkey,Key} exception if there's just no value associated with Key. like, it's not gonna be nice about it. ๐Ÿ˜ญ

Example:

> Key = 1337,
  Map = #{42 => value_two,1337 => "value one","a" => 1},
  map_get(Key,Map).
"value one"

Allowed in guard tests. โœจ

๐Ÿ’œ map_size(Map) -> integer() >= 0 ๐Ÿ’œ

Types:

Map = map()

returns an integer, and that integer is literally how many key-value pairs are living inside Map. that's it, that's the whole function. for example:

> map_size(#{a=>1, b=>2, c=>3}).
3

Allowed in guard tests. ๐Ÿซถ


๐ŸŒˆ erlang:match_spec_test(MatchAgainst, MatchSpec, Type) -> TestResult ๐ŸŒˆ

Types:

MatchAgainst = [term()] | tuple()
MatchSpec = term()
Type = table | trace
TestResult =
    {ok, term(), [return_trace], [{error | warning, string()}]} |
    {error, [{error | warning, string()}]}

this one tests a match specification โ€” you know, the same kind of thing used in calls to ets:select/2 and erlang:trace_pattern/3. it checks both the "syntactic" correctness and actually runs the match spec against the object you gave it. double duty, main character energy fr. ๐Ÿ‘‘

if the match specification has errors in it, you get back {error, Errors} โ€” and Errors is a list of natural language descriptions of what was wrong with your match spec. so it's basically a little therapist for your match specs.

now, if Type is table, then the object to match against has to be a tuple. the function then returns {ok,Result,[],Warnings}, where Result is what would've been the result in a real ets:select/2 call โ€” or false if the match specification doesn't match the object tuple.

if Type is trace, then the object to match against has to be a list. the function returns {ok, Result, Flags, Warnings}, where Result is one of these:

  • true if a trace message is to be emitted
  • false if a trace message is not to be emitted
  • The message term to be appended to the trace message

Flags is a list containing all the trace flags to be enabled, and currently that's only return_trace.

this is a genuinely useful debugging and test tool, especially when you're out here writing complicated match specifications. it's giving "test your fit before you leave the house."

see also ets:test_ms/2. ๐Ÿ’–

โญ max(Term1, Term2) -> Maximum โญ

Types:

Term1 = Term2 = Maximum = term()

returns the largest of Term1 and Term2. but here's the little plot twist: if the terms compare equal with the == operator, then Term1 is the one that gets returned. periodt.

the Expressions section contains descriptions of the == operator and how terms are ordered, iykyk.

Examples:

> max(1, 2).
2

> max(1.0, 1).
1.0

> max(1, 1.0).
1

> max("abc", "b").
"b"

look at those last two โ€” 1.0 first means you get 1.0, 1 first means you get 1. tie goes to the one on the left. ๐Ÿ’…

๐Ÿ”ฅ erlang:md5(Data) -> Digest ๐Ÿ”ฅ

Types:

Data = iodata()
Digest = binary()

computes an MD5 message digest from Data, and the length of that 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 security era bestie, I'm begging. ๐Ÿ˜ญ

๐Ÿงš erlang:md5_final(Context) -> Digest ๐Ÿงš

Types:

Context = Digest = binary()

finishes the update of an MD5 Context and returns the computed MD5 message digest. it's the closing act. the finale. the last bow. ๐ŸŽ€

๐ŸŽ€ erlang:md5_init() -> Context ๐ŸŽ€

Types:

Context = binary()

creates an MD5 context, which you then use in the following calls to md5_update/2. it's the opening scene, the setup. โœจ

๐ŸŒธ erlang:md5_update(Context, Data) -> NewContext ๐ŸŒธ

Types:

Context = binary()
Data = iodata()
NewContext = binary()

updates an MD5 Context with Data and returns a NewContext. feed it data, get a new context, repeat. it's giving little incremental steps, honestly very demure.


๐Ÿ‘‘ erlang:memory() -> [{Type, Size}] ๐Ÿ‘‘

Types:

Type = memory_type()
Size = integer() >= 0
memory_type() =
    total | processes | processes_used | system | atom |
    atom_used | binary | code | ets

returns a list with info about memory dynamically allocated by the Erlang emulator. each list element is a tuple {Type, Size}. first element Type is an atom describing the memory type, second element Size is the memory size in bytes. a whole little memory buffet. ๐Ÿ’œ

Memory types, let's go:

  • total: the total amount of memory currently allocated. this is the same as the sum of the memory size for processes and system.
  • 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 as processes memory.
  • system: the total amount of memory currently allocated for the emulator that is not directly related to any Erlang process. memory presented as processes is not included in this memory. instrument(3erl) can 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 as system memory.
  • atom_used: the total amount of memory currently used for atoms. this memory is part of the memory presented as atom memory.
  • binary: the total amount of memory currently allocated for binaries. this memory is part of the memory presented as system memory.
  • code: the total amount of memory currently allocated for Erlang code. this memory is part of the memory presented as system memory.
  • ets: the total amount of memory currently allocated for ETS tables. this memory is part of the memory presented as system memory.
  • 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(3erl) and/or erl(1).

๐Ÿ“Œ Note: the system value is not complete. some allocated memory that is to be part of this value is not. when the emulator is run with instrumentation, the system value is more accurate, but memory directly allocated for malloc (and friends) is still not part of the system value. direct calls to malloc are 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 the total value is the sum of processes and system, the error in system propagates to the total value. the different amounts of memory that are summed are not gathered atomically, which introduces an error in the result. the different values have the following relation to each other. values beginning with an uppercase letter are 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. so like, don't hardcode your assumptions, bestie. ๐Ÿ™ˆ

๐Ÿ“Œ Note: the total value 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, the total value 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.
๐Ÿšจ Note: as from ERTS 5.6.4, erlang:memory/0 requires that all erts_alloc(3erl) allocators are enabled (default behavior). Failure: notsup if an erts_alloc(3erl) allocator has been disabled.

๐Ÿฆ‹ erlang:memory(Type :: memory_type()) -> integer() >= 0 ๐Ÿฆ‹

๐Ÿฆ‹ erlang:memory(TypeList :: [memory_type()]) -> [{memory_type(), integer() >= 0}] ๐Ÿฆ‹

Types:

memory_type() =
    total | processes | processes_used | system | atom |
    atom_used | binary | code | ets

returns the memory size in bytes allocated for memory of type Type. but plot twist โ€” the argument can also be a list of memory_type() atoms, and in that case you get a corresponding list of {memory_type(), Size :: integer >= 0} tuples back. flexible queen. โœจ

๐Ÿ“Œ Note: as from ERTS 5.6.4, erlang:memory/1 requires that all erts_alloc(3erl) allocators are enabled (default behavior). Failures:
  • badarg โ€” thrown when Type isn't one of the memory types that erlang:memory/0 lists in its description. Like, wrong word entirely, bestie ๐Ÿ’…
  • badarg โ€” also thrown if you pass maximum as Type and the emulator isn't running in instrumented mode. Yeah. That one. ๐Ÿ™ˆ
  • notsup โ€” thrown if an erts_alloc(3erl) allocator has been disabled. No can do, it's giving "not supported" energy ๐Ÿ’€

See also erlang:memory/0. ๐Ÿซถ


โœจ min(Term1, Term2) -> Minimum โœจ

Types:

Term1 = Term2 = Minimum = term()

Returns whichever of Term1 and Term2 is the smallest ๐Ÿ’–. But here's the little plot twist: if the two terms compare equal using the == operator, then Term1 is what comes back. No cap, first one wins the tie.

The Expressions section has the whole lore on the == operator and how terms get ordered, so go read that if you need the full breakdown ๐Ÿ“–

Examples, bestie, look:

> min(1, 2).
1

> min(1.0, 1).
1.0

> min(1, 1.0).
1

> min("abc", "b").
"abc"

See how 1.0 vs 1 flips depending on the order you pass them? That's the == tie-break doing its thing, lowkey iconic ๐ŸŒธ


โœจ module_loaded(Module) -> boolean() โœจ

Types:

Module = module()

Returns true if the module Module is loaded as current code โ€” otherwise false ๐Ÿ˜Œ. And important: it does not attempt to load the module. It's just a vibe check on what's already there, not a "go get it for me" ๐Ÿงš


โœจ monitor(Type :: process, Item :: monitor_process_identifier()) -> MonitorRef โœจ

โœจ monitor(Type :: port, Item :: monitor_port_identifier()) -> MonitorRef โœจ

โœจ monitor(Type :: time_offset, Item :: clock_service) -> MonitorRef โœจ

Types:

MonitorRef = reference()
registered_name() = atom()
registered_process_identifier() =
    registered_name() | {registered_name(), node()}
monitor_process_identifier() =
    pid() | registered_process_identifier()
monitor_port_identifier() = port() | registered_name()

Sends a monitor request of type Type to the entity identified by Item ๐Ÿ‘€. And if the thing you're monitoring doesn't exist, or it changes its monitored state, the caller of monitor/2 gets notified by a message shaped exactly like this:

{Tag, MonitorRef, Type, Object, Info}
Note: the monitor request is an asynchronous signal. Translation: it takes time before the signal actually reaches its destination. Don't be out here expecting instant results, bestie โณ

Type can be one of these atoms: process, port, or time_offset ๐ŸŽ€

A process or port monitor triggers only once โ€” after that it's removed from both the monitoring process and the monitored entity. Gone, periodt. Monitors fire when the monitored process or port terminates, when it doesn't exist at the moment of creation, or if the connection to it is lost. And if the connection is lost, we genuinely do not know whether it still exists ๐Ÿ˜ญ. Monitoring also gets turned off when demonitor/1 is called.

A process or port monitor by name resolves the RegisteredName to a pid() or port() only once, at the moment the monitor is instantiated. Any later changes to the name registration won't affect the existing monitor. Snapshot taken, that's it ๐Ÿ“ธ

When a process or port monitor is triggered, 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 above, and then:

  • Object โ€” the monitored entity that triggered the event. When you're monitoring a process or a local port, Object equals the pid() or port() that was being monitored. When monitoring a process or port by name, Object has the format {RegisteredName, Node} where RegisteredName is the name used in the monitor/2 call and Node is the local or remote node name (and for ports monitored by name, Node is always the local node name) ๐ŸŒˆ
  • Info โ€” either the exit reason of the process, noproc (the process or port did not exist at the time the monitor was created), or noconnection (no connection to the node where the monitored process resides) ๐Ÿ’€

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 elsewhere ๐Ÿ”ฅ

Note: before ERTS 10.0 (OTP 21.0), monitoring a process could fail with badarg if the monitored process resided on a primitive node (like erl_interface or jinterface), where remote process monitoring isn't implemented. Nowadays that call to monitor succeeds instead, and a monitor gets created. But the monitor will only supervise the connection. Meaning: a {'DOWN', _, process, _, noconnection} is the only message you may receive, because the primitive node has no way of reporting the status of the monitored process. So like... that's all you're getting from it ๐Ÿคทโ€โ™€๏ธ

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. Heads up though โ€” attempting to monitor a remote port will result in badarg. Not allowed, bestie ๐Ÿšซ

Monitoring a time_offset: monitors changes in the time offset between Erlang monotonic time and Erlang system time โฐ. There's exactly one valid Item to pair with the time_offset Type, and it's the atom clock_service. And notice โ€” clock_service is not the registered name of a process. In this case it serves as an identifier for the runtime system's internal clock service at the current runtime system instance, iykyk ๐Ÿ•ฐ๏ธ

The monitor is triggered when the time offset changes. That's either when the time offset value changes, or when the offset changes from preliminary to final during finalization of the time offset when the single time warp mode is used. When a change from preliminary to final time offset happens, the monitor is triggered 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 detect this immediately when it occurs, though ๐Ÿ™ˆ. A task checking the time offset is scheduled to execute at least once a minute, so under normal operation this gets detected within a minute โ€” but during heavy load it can take longer. Heavy load said "not today" ๐Ÿ˜ญ

The monitor is not automatically removed after it's been triggered. So repeated changes of the time offset trigger the monitor repeatedly. It's very much main character energy, it keeps coming back ๐Ÿ‘‘

When the monitor is triggered, 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 ๐Ÿ’ซ

When the 'CHANGE' message has been received, you're guaranteed not to retrieve the old time offset when calling erlang:time_offset(). Small catch though: you can observe the change of the time offset by calling erlang:time_offset() before you get the 'CHANGE' message ๐Ÿ‘€

Making several calls to monitor/2 for the same Item and/or Type is not an error โ€” it results in as many independent monitoring instances. Stack 'em up, bestie, they're all separate ๐ŸŽ€

The monitor functionality is expected to be extended. So other Types and Items are expected to be supported in a future release โ€” watch this space ๐Ÿ”ฎ

Note: if or when monitor/2 gets extended, other possible values for Tag, Object, and Info in the monitor message will be introduced. So don't go hardcoding your pattern matches too tight, okay? ๐Ÿซถ

โœจ monitor(Type :: process, Item :: monitor_process_identifier(), Opts :: [monitor_option()]) -> MonitorRef โœจ

โœจ monitor(Type :: port, Item :: monitor_port_identifier(), Opts :: [monitor_option()]) -> MonitorRef โœจ

โœจ monitor(Type :: time_offset, Item :: clock_service, Opts :: [monitor_option()]) -> MonitorRef โœจ

Types:

MonitorRef = reference()
registered_name() = atom()
registered_process_identifier() =
    registered_name() | {registered_name(), node()}
monitor_process_identifier() =
    pid() | registered_process_identifier()
monitor_port_identifier() = port() | registered_name()

Gives you an option list for modifying the monitoring functionality that monitor/2 provides ๐Ÿ’…. The Type and Item arguments mean exactly 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. So the returned reference can be used for sending messages to the calling process ๐Ÿ‘‘. See also alias/0. The UnaliasOpt decides how the alias gets deactivated:
    • explicit_unalias โ€” only an explicit call to unalias/1 will deactivate the alias. No shortcuts, no auto-cleanup ๐ŸŒธ
    • demonitor โ€” the alias is automatically deactivated when the monitor is removed. That's either via an explicit call to demonitor/1, or when it's automatically removed at the same time as a 'DOWN' message is delivered due to the monitor. And the alias can still be deactivated via a call to unalias/1 too, if you feel like it ๐Ÿฆ‹
  • reply_demonitor โ€” the alias gets auto-deactivated the moment the monitor is removed (that's the demonitor option up there โฌ†๏ธ) or a reply message comes in through the alias. And bestie, when a reply arrives via the alias, the monitor gets yeeted automatically too ๐Ÿ˜Œ. This is chef's kiss for client/server setups where the client monitors the server and gets the reply through the alias โ€” once the response lands, both the alias and the monitor are gone, no cap, whether the response is a reply or a 'DOWN' message. You can still deactivate the alias manually with a call to unalias/1 if you're like that. โš ๏ธ But heads up: if you remove the alias with the unalias/1 BIF, the monitor stays active โ€” it does NOT come along for the ride.

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.
๐Ÿซถ Little note: in this example, both the server and the client have to be running on at least OTP 24 systems for it to work. No time-traveling, sorry.

Wanna know more about process aliases? Go peek at the Process Aliases section of the Erlang Reference Manual ๐Ÿ“–.

  • {tag, UserDefinedTag} โ€” swaps the default Tag for UserDefinedTag in the monitor message that gets delivered when the monitor fires ๐Ÿ””. So like, when you're monitoring a process, the 'DOWN' tag in the down message gets replaced by UserDefinedTag. Obsessed, honestly.

Here's how you'd use {tag, UserDefinedTag} to unlock the new selective receive optimization (introduced in OTP 24, iykyk) when you're firing off a bunch of 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]).
๐Ÿ’… For this to actually work as intended, the client has to be on at least an OTP 24 system โ€” but the servers can be out here running older versions, living their truth. Slay for backwards compatibility.

โœจ erlang:monitor_node/2 โœจ

monitor_node(Node, Flag) -> true

Types:

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 โ€” nope, it's totally valid. It just gives you that many independent monitoring instances. Stack 'em up, bestie ๐Ÿซถ.

If Node fails or doesn't even exist, the message {nodedown, Node} gets delivered to the process ๐Ÿ’Œ. So if a process made two calls to monitor_node(Node, true) and Node terminates, you get two nodedown messages delivered. Two for the price of two, fr fr. If there's no connection to Node, an attempt is made to create one โ€” and if that fails, a nodedown message gets delivered.

โš ๏ธ Big caveat, listen up: 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 use net_kernel:monitor_nodes/1 instead. Don't come crying to me when your ordering is chaotic ๐Ÿ˜ญ.

Nodes connected through hidden connections can be monitored just like any other nodes. Equal opportunity monitoring ๐Ÿ’–.

Failure: notalive if the local node is not alive.


โœจ erlang:monitor_node/3 โœจ

erlang:monitor_node(Node, Flag, Options) -> true

Types:

Node = node()
Flag = boolean()
Options = [Option]
Option = allow_passive_connect

Behaves exactly like monitor_node/2 โ€” except it lets you pass an extra option, namely 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 (like, it's blocked ๐Ÿšซ). And the only way you even get into that state is by using the Kernel option dist_auto_connect once. If that option isn't in play, allow_passive_connect has no effect whatsoever. Zero. Nada.

๐Ÿ“Œ Note: the allow_passive_connect option is used internally and is seldom needed in applications where the network topology and the Kernel options in effect are known in advance. It's giving "you probably don't need this" energy.

Failure: badarg if the local node is not alive or the option list is malformed.


โœจ erlang:monotonic_time/0 โœจ

erlang:monotonic_time() -> integer()

Returns the current Erlang monotonic time in native time unit โฑ๏ธ. It's a monotonically increasing time since some unspecified point in time. Mysterious. Iconic.

๐Ÿ“Œ Note: this is a monotonically increasing time, but not a strictly monotonically increasing time. Which means consecutive calls to erlang:monotonic_time/0 can literally hand you the same result. Yes, same value, twice. It's fine. Breathe. ๐Ÿ˜Œ

Different runtime system instances use different unspecified points in time as the base for their Erlang monotonic clocks. Translation: comparing monotonic times from different runtime system instances is pointless ๐Ÿ’€ โ€” don't do it. And different runtime system instances can also place this unspecified point in time differently relative to runtime system start. It can be in the future (time at start is a negative value), in the past (time at start is a positive value), or right at the runtime system start (time at start is zero). Wild, I know. If you want the monotonic time at runtime system start, just call erlang:system_info(start_time) ๐ŸŽ€.


โœจ erlang:monotonic_time/1 โœจ

erlang:monotonic_time(Unit) -> integer()

Types:

Unit = time_unit()

Returns the current Erlang monotonic time, converted into the Unit you passed as the argument ๐Ÿฆ‹.

It's the same as calling erlang:convert_time_unit(erlang:monotonic_time(), native, Unit) โ€” except it's optimized for commonly used *Unit*s โšก. Faster. Sexier. Same result.


โœจ erlang:nif_error/1 โœจ

erlang:nif_error(Reason) -> no_return()

Types:

Reason = term()

Works exactly like error/1, but 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. Peace and quiet, finally ๐Ÿง˜โ€โ™€๏ธ.


โœจ erlang:nif_error/2 โœจ

erlang:nif_error(Reason, Args) -> no_return()

Types:

Reason = term()
Args = [term()]

Works exactly like error/2, but โ€” you guessed it โ€” Dialyzer thinks this BIF will return an arbitrary term ๐Ÿซถ. Same deal: used in a stub function for a NIF to generate an exception when the NIF library isn't loaded, and Dialyzer generates zero false warnings. A whole vibe.


โœจ node/0 โœจ

node() -> Node

Types:

Node = node()

Returns the name of the local node ๐Ÿ . If the node isn't alive, you get nonode@nohost instead. Sad but valid.

Allowed in guard tests โœ….


โœจ node/1 โœจ

node(Arg) -> Node

Types:

Arg = pid() | port() | reference()
Node = node()

Returns the node where Arg originates from ๐ŸŒ. Arg can be a process identifier, a reference, or a port โ€” pick your fave. If Arg originates from the local node and the local node isn't alive, you get nonode@nohost back.

Allowed in guard tests โœ….


โœจ nodes/0 โœจ

nodes() -> Nodes

Types:

Nodes = [node()]

Returns a list of all nodes connected to this node through normal connections โ€” so hidden nodes are not listed, they're not invited to this party ๐Ÿ™ˆ. Same as nodes(visible).


โœจ nodes/1 โœจ

nodes(Arg) -> Nodes

Types:

Arg = NodeType | [NodeType]
NodeType = visible | hidden | connected | this | known
Nodes = [node()]

Returns a list of nodes according to the argument you specified ๐ŸŽฏ. And when the argument is a list, the result is the list of nodes satisfying the disjunction(s) of the list elements โ€” aka, match any of them and you're in ๐Ÿ’….

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. Everyone. The whole group chat.
  • this โ€” this node. Just you. Main character energy ๐Ÿ‘‘.
  • known โ€” nodes this node knows about. Basically: nodes that are connected plus any node that gets mentioned by a process identifier, a port identifier, or a reference sitting on this node. The set of known nodes gets garbage collected ๐Ÿ—‘๏ธ โ€” but heads up, that garbage collection can be delayed. For the receipts, see erlang:system_info(delayed_node_table_gc).

Some equalities to keep in your notes, bestie ๐Ÿ“: [node()] = nodes(this), nodes(connected) = nodes([visible, hidden]), and nodes() = nodes(visible).

๐Ÿ’ซ nodes(Arg, InfoOpts) -> [NodeInfo]

Types:

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, gorgeous. The first element of each tuple is the node name. Which nodes actually show up is decided by the first argument Arg, exactly the same way as for nodes(Arg). The second element of the NodeInfo tuple is a map with extra deets about the node named in the first element. What's inside that map is decided by the InfoOpts map you pass as the second argument. Right now these are the associations allowed in the InfoOpts map:

  • connection_id => boolean() โ€” if this association's value is true, then the Info map in the result you get back will contain the key connection_id, associated with the value ConnectionId. If ConnectionId equals undefined, then the node is not connected to the node the caller is running on โ€” or it is the node the caller is running on. If ConnectionId is an integer, then the node is currently connected to the node the caller is running on.

So like, the integer connection identifier value together with a node name identifies one specific connection instance to the node with that node name. And the connection identifier value is node local โ€” meaning on the other node, that connection identifier will not be the same value ๐Ÿ”€. If a connection goes down and then comes back up, the connection identifier value changes for the connection to that node. The amount of values for connection identifiers is limited, so yes, you could see the same value for different instances โ€” but it's quite unlikely. And how the value changes between two consecutive connection instances is simply undefined. No promises ๐Ÿ’€.

  • node_type => boolean() โ€” if this association's value is true, then the Info map in the result you get back will contain the key node_type, associated with the value NodeTypeInfo. Currently these node types exist:
    • visible โ€” the node is connected to the calling process's node through an ordinary visible connection. Which means: the node name would show up in the result of nodes/0.
    • hidden โ€” the node is connected to the calling process's node through a hidden connection. Which means: the node name would not show up in the result of nodes/0.
    • this โ€” this is the calling process's own node. main character energy ๐Ÿ‘‘.
    • known โ€” the node isn't connected, but it is known to the calling process's node.

Example, feast your eyes ๐Ÿ˜:

(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

Types:

Timestamp = timestamp()
timestamp() =
    {MegaSecs :: integer() >= 0,
     Secs :: integer() >= 0,
     MicroSecs :: integer() >= 0}
โš ๏ธ Warning: this function is deprecated. Do not use it. Like, genuinely, don't ๐Ÿ™ˆ.

For more info, see section Time and Time Correction in the User's Guide. Specifically, section Dos and Dont's describes what to use instead of erlang:now/0.

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 it. Otherwise some other point in time gets chosen, ngl. It's also guaranteed that consecutive calls to this BIF return continuously increasing values. So the return value from erlang:now/0 can be used to generate unique time stamps โœจ. But if you call it in a tight loop on a fast machine, the node's time can become skewed ๐Ÿ˜ฌ.

Can only be used to check the local time of day if the time-zone information of the underlying OS is properly configured.

๐Ÿฆ‹ open_port(PortName, PortSettings) -> port()

Types:

PortName =
    {spawn, Command :: string() | binary()} |
    {spawn_driver, Command :: string() | binary()} |
    {spawn_executable, FileName :: file:name_all()} |
    {fd, In :: integer() >= 0, Out :: integer() >= 0}
PortSettings = [Opt]
Opt =
    {packet, N :: 1 | 2 | 4} |
    stream |
    {line, L :: integer() >= 0} |
    {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,
     {integer() >= 0, integer() >= 0} | disabled} |
    {busy_limits_msgq,
     {integer() >= 0, integer() >= 0} | disabled}

Returns a port identifier as the result of opening a shiny new Erlang port ๐Ÿ’–. A port can be seen as an external Erlang process.

The name of the executable, plus the arguments you specify in cd, env, args, and arg0, are all subject to Unicode filename translation if the system is running in Unicode filename mode. Wanna avoid translation, or force, like, UTF-8? Then pass the executable and/or arguments as a binary in the correct encoding. Deets in the module file(3erl), 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 it's specified as a list) can only be > 255 if the Erlang virtual machine was started in Unicode filename translation mode. Otherwise the executable's name is limited to the ISO Latin-1 character set.

PortNames โ€” the flavours ๐Ÿ“:

  • {spawn, Command} โ€” starts an external program. Command is the name of the external program to run. Command runs outside the Erlang work space unless an Erlang driver with the name Command is found โ€” if it is found, that driver gets started. A driver runs inside the Erlang work space, which means it's linked with the Erlang runtime system.

For external programs, PATH is searched (or an equivalent method is used to find programs, depending on the OS). This is done by invoking the shell on certain platforms. The first space-separated token of the command is considered the name of the executable (or driver). This (among other things) makes this option unsuitable for running programs with spaces in filenames or directory names ๐Ÿ’€. If you want spaces in executable filenames, use {spawn_executable, Command} instead.

  • {spawn_driver, Command} โ€” works like {spawn, Command}, but demands that the first (space-separated) token of the command is the name of a loaded driver. If no driver with that name is loaded, a badarg error is raised ๐Ÿ˜ญ.
  • {spawn_executable, FileName} โ€” works like {spawn, FileName}, but only runs external executables. FileName in its whole is used as the name of the executable, including any spaces โœจ. Wanna pass arguments? The PortSettings args and arg0 are your girls.

The shell is usually not invoked to start the program โ€” it gets executed directly. PATH (or equivalent) is not searched. 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 there's still no command-argument expansion and no implicit PATH search.

If FileName can't be run, an error exception is raised, with the POSIX error code as the reason. The error reason can differ between OSs. Typically the error 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.

  • {fd, In, Out} โ€” lets an Erlang process access any currently opened file descriptors used by Erlang. The file descriptor In can be used for standard input, and the file descriptor Out for standard output. It's only used for various servers in the Erlang OS (shell and user). Hence, its use is limited ๐Ÿ™ƒ.

PortSettings is a list of settings for the port. The valid settings are as follows, bestie:

  • {packet, N} โ€” messages are preceded by their length, sent in N bytes, with the most significant byte first. The valid values for N are 1, 2, and 4.
  • 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 get delivered one line at a time, bestie. each line (split on whatever newline sequence your OS fancies) shows up as its own message, formatted as {Flag, Line} where Flag is eol or noeol and Line is the actual data (newline sequence not included, we're clean here ๐Ÿ’…).

L is the max line length in bytes. lines longer than that get chopped into multiple messages, with Flag set to noeol for every message except the last one. and if EOF hits anywhere other than right after a newline sequence, that final line also comes through with Flag set to noeol. otherwise? lines arrive with Flag set to eol. periodt.

ngl, {packet, N} and {line, L} are mutually exclusive โ€” pick one, you can't have both ๐Ÿ™…โ€โ™€๏ธ

  • {cd, Dir} โ€” only valid for {spawn, Command} and {spawn_executable, FileName}. the external program starts with Dir as its working directory. Dir has to be a string. slay.
  • {env, Env} โ€”
Types:
Name = os:env_var_name()
Val = os:env_var_value() | false
Env = [{Name, Val}]

only valid for {spawn, Command} and {spawn_executable, FileName}. the environment of the started process gets extended using the env specs in Env.

Env is a list of tuples {Name, Val}, where Name is the name of an environment variable and Val is the value it should have inside the spawned port process. both Name and Val must be strings โ€” the one exception being Val as the atom false (shamelessly mirroring os:getenv/1, which removes the environment variable).

for the encoding requirements tea, go check the docs for the types of Name and Val โ˜•

  • {args, [ string() | binary() ]} โ€” only valid for {spawn_executable, FileName}, and it specifies arguments for the executable. each argument is its own separate string and (on Unix) ends up as one element each in the argument vector. on other platforms, similar behavior is mimicked. iconic.

these arguments are not expanded by the shell before being handed to the executable. most importantly: file wildcard expansion does not happen. want wildcards expanded for the arguments? use filelib:wildcard/1. and heads up โ€” even if the program is a Unix shell script, meaning the shell eventually gets invoked, wildcard expansion still doesn't happen, and the script receives the untouched arguments. on Windows, wildcard expansion is always the program's own problem, so this isn't an issue there.

the executable name (a.k.a. argv[0]) is not to be specified in this list. the proper executable name gets used automatically as argv[0], where applicable ๐Ÿ’–

if you explicitly want to set the program name in the argument vector, use the arg0 option.

  • {arg0, string() | binary()} โ€” only valid for {spawn_executable, FileName}, and it explicitly sets the program name argument when running an executable. in some circumstances, on some OSs, this can be desirable. how the program responds to it is highly system-dependent and no specific effect is guaranteed. lowkey a vibe check you can't predict ๐Ÿ™ˆ
  • exit_status โ€” only valid for {spawn, Command} where Command refers 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 that external process. if the program aborts on Unix, the same convention as the shells is used (that is, 128+signal).

if you also specify option eof, the messages eof and exit_status appear in an unspecified order. don't @ me, that's just how it is ๐Ÿ˜ญ

if the port program closes its stdout without exiting, option exit_status does not work. rip.

  • use_stdio โ€” only valid for {spawn, Command} and {spawn_executable, FileName}. it lets the standard input and output (file descriptors 0 and 1) of the spawned (Unix) process do the talking with Erlang. classic.
  • nouse_stdio โ€” the opposite of use_stdio. it uses file descriptors 3 and 4 for communication with Erlang. contrarian queen ๐Ÿ’…
  • stderr_to_stdout โ€” affects ports to external programs. the executed program gets its standard error file redirected onto its standard output file. stderr_to_stdout and nouse_stdio are mutually exclusive, so pick a lane bestie.
  • overlapped_io โ€” affects ports to external programs on Windows only. the standard input and standard output handles of the port program are, if this option is supplied, opened with flag FILE_FLAG_OVERLAPPED, so the port program can (and must) do overlapped I/O on its standard handles. this is not normally the case for simple port programs, but it's an option of value for the experienced Windows programmer โœจ on all other platforms, this option is silently discarded. poof, gone.
  • 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. no cap.
  • eof โ€” the port is not closed at the end of the file and does not produce an exit signal. instead it stays open and a {Port, eof} message is sent to the process holding the port. she stays ๐Ÿซถ
  • 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 the scheduler hint for port parallelism. if set to true, the virtual machine schedules port tasks, and by doing so it improves parallelism in the system ๐Ÿ”ฅ if set to false, the virtual machine tries to perform port tasks immediately, which improves latency at the expense of parallelism. the default can be set at system startup by passing command-line argument +spp to erl(1).
  • {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 busy, processes sending commands to it get suspended until the port leaves the busy state. "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 will never enter the busy state. she's off duty, permanently ๐ŸŒธ

the defaults are Low = 4096 and High = 8192.

note that this option is only valid when spawning an executable (port program) by opening the spawn driver and when opening the fd driver. this option causes a failure with a badarg exception when opening other drivers. ๐Ÿ’€
  • {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 busy, processes sending commands to it get suspended until it leaves the busy state. commands, again, 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 that if the driver statically has disabled the use of this feature, a failure with a badarg exception is raised unless this option is also set to disable or not passed at all. ๐Ÿ˜ญ

the defaults are Low = 4096 and High = 8192 unless the driver itself modifies these values.

note that 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. good for them honestly ๐ŸŒˆ

for more info, see the documentation erl_drv_busy_msgq_limits().


default is stream for all port types and use_stdio for spawned ports. the blueprint, the standard, the moment ๐Ÿ‘‘

Failure: 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 to open_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 โ€” the FileName you put in {spawn_executable, FileName} does not point out an existing file. ๐Ÿ’€

Okay so during use of a port opened using {spawn, Name}, {spawn_driver, Name}, or {spawn_executable, Name}, errors that pop up 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(3erl).

The maximum number of ports that can be open at the same time can be configured by passing command-line flag +Q to erl(1). โœจ


erlang:phash(Term, Range) -> Hash

Types:

Term = term()
Range = Hash = integer() >= 1
  Range = 1..2^32, Hash = 1..Range
โš ๏ธ Warning: This function is deprecated โ€” erlang:phash2/2 should be used for new code. And note that erlang:phash(X,N) is not necessarily equal to erlang: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. ๐Ÿซถ


erlang:phash2(Term) -> Hash

erlang:phash2(Term, Range) -> Hash

Types:

Term = term()
Range = integer() >= 1
  1..2^32
Hash = integer() >= 0
  0..Range-1

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 5.2). The function returns a hash value for Term within the range 0..Range-1. The maximum value for Range is 2^32. When 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. It distributes small integers better than phash/2, and it is faster for bignums and binaries. ๐Ÿ”ฅ

Notice that the range 0..Range-1 is different from the range of phash/2, which is 1..Range. ๐Ÿ‘€


pid_to_list(Pid) -> string()

Types:

Pid = pid()

Returns a string corresponding to the text representation of Pid. Example:

> erlang:pid_to_list(self()).
"<0.85.0>"
Note: The creation for the node is not included in the list representation of Pid. This means that processes in different incarnations of a node with a specific name can get the same list representation. ๐ŸŒ€

erlang:port_call(Port, Operation, Data) -> term()

Types:

Port = port() | atom()
Operation = integer()
Data = term()

Performs a synchronous call to a port. The meaning of Operation and Data depends on the port, that is, on the port driver. Not all port drivers 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. ๐Ÿ’…

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 this badarg exception 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).
โš ๏ธ Warning: Do not call port_call with an unknown Port identifier and expect a badarg exception. Any undefined behavior is possible (including node crash) depending on how the port driver interprets the supplied arguments. ๐Ÿ˜ญ

port_close(Port) -> true

Types:

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}. Any process can close a port with port_close/1, not only the port owner (the connected process). 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: 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.

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(Port, Data) -> true

Types:

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

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 this badarg exception 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. ๐Ÿ’€

port_command(Port, Data, OptionList) -> boolean()

Types:

Port = port() | atom()
Data = iodata()
Option = force | nosuspend
OptionList = [Option]

Sends data to a port. port_command(Port, Data, []) equals port_command(Port, Data).

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 a notsup exception if the driver of the port does not support this. For more information, see driver flag ERL_DRV_FLAG_SOFT_BUSY.
  • nosuspend โ€” the calling process is not suspended if the port is busy, instead the port command is aborted and false is returned.
Note: More options can be added in a future release.

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 this badarg exception occurs.
  • badarg โ€” if Data is an invalid I/O list.
  • badarg โ€” if OptionList is an invalid option list.
  • notsup โ€” if option force has been passed, but the driver of the port does not allow forcing through a busy port.
โš ๏ธ 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(Port, Pid) -> true

Types:

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:

  • The error behavior differs, see below.
  • The port does not reply with {Port,connected}.
  • port_connect/1 is 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. Any process can set the port owner to be any process with port_connect/2. ๐ŸŒธ

Okay so literally for comparison, bestie: Port ! {self(), {connect, Pid}} only fails with badarg if Port doesn't refer to a port or a process. That's it. If Port is a closed port, nothing happens โ€” no error, no drama, nothing. ๐Ÿซถ

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. And notice: the old port owner is still linked to the port, while the new one is not. Yeah, it's giving messy breakup energy. ๐Ÿ’€

If Port is an open port and the calling process is not the port owner, the port owner fails with badsig. The port owner also fails with badsig 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. Sneaky but legal. ๐Ÿ‘‘

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. Glow-up but with lore. โœจ

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 this badarg exception occurs.
  • badarg โ€” if the process identified by Pid is not an existing local process.

port_control(Port, Operation, Data) -> iodata() | binary()

Types:

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 โ€” some are just not that girl. ๐Ÿ™ˆ

Returns a list of integers in the range 0..255, or a binary, depending on the port driver. The meaning of the returned data also depends on the port driver. So likeโ€ฆ it returns something, and only the driver knows what it means. iykyk. ๐Ÿฆ‹

Failures:

  • badarg โ€” if Port is not an open port or the registered name of an open port.
  • badarg โ€” if Operation cannot 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).
Warning: Do not call port_control/3 with an unknown Port identifier and expect a badarg exception. Any undefined behavior is possible (including node crash) depending on how the port driver interprets the supplied arguments. Bestie. NODE CRASH. Do not test this on main. ๐Ÿ˜ญ

erlang:port_info(Port) -> Result

Types:

Port = port() | atom()
ResultItem =
    {registered_name, RegisteredName :: atom()} |
    {id, Index :: integer() >= 0} |
    {connected, Pid :: pid()} |
    {links, Pids :: [pid()]} |
    {name, String :: string()} |
    {input, Bytes :: integer() >= 0} |
    {output, Bytes :: integer() >= 0} |
    {os_pid, OsPid :: integer() >= 0 | undefined}
Result = [ResultItem] | undefined

Returns a list containing tuples with information about Port, or undefined if the port is not open. The order of the tuples is undefined, and all the tuples are not mandatory. So don't go assuming anything about the vibe of the list you get back, okay? ๐ŸŒธ

If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/1 returns undefined.

The result contains information about the following Items:

  1. registered_name (if the port has a registered name)
  2. id
  3. connected
  4. links
  5. name
  6. input
  7. output

For more information about the different Items, see port_info/2.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: connected) -> {connected, Pid} | undefined

Types:

Port = port() | atom()
Pid = pid()

Pid is the process identifier of the process connected to the port. Your port's plus-one, if you will. ๐Ÿซถ

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: id) -> {id, Index} | undefined

Types:

Port = port() | atom()
Index = integer() >= 0

Index is the internal index of the port. This index can be used to separate ports โ€” very handy when you've got multiple ports and need to tell them apart, like telling your mutuals apart in a group chat. ๐Ÿ’…

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: input) -> {input, Bytes} | undefined

Types:

Port = port() | atom()
Bytes = integer() >= 0

Bytes is the total number of bytes read from the port. The receipts, basically. ๐Ÿ“ฅ

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


Types:

Port = port() | atom()
Pids = [pid()]

Pids is a list of the process identifiers of the processes that the port is linked to. Its little linked-up circle. ๐Ÿ”—

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: locking) -> {locking, Locking} | undefined

Types:

Port = port() | atom()
Locking = false | port_level | driver_level

Locking is one of the following:

  • port_level (port-specific locking)
  • driver_level (driver-specific locking)
Notice that these results are highly implementation-specific and can change in a future release. So don't hardcode your whole personality around them. ๐Ÿ™ˆ

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: memory) -> {memory, Bytes} | undefined

Types:

Port = port() | atom()
Bytes = integer() >= 0

Bytes is the total number of bytes allocated for this port by the runtime system. The port itself can have allocated memory that is not included in Bytes โ€” so this is the runtime's tab, not the port's own secret spending. ๐Ÿ’ธ

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: monitors) -> {monitors, Monitors} | undefined

Types:

Port = port() | atom()
Monitors = [{process, pid()}]

Monitors represent processes monitored by this port. Yes, ports can monitor. Everyone's got a watchlist these days. ๐Ÿ‘€

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: monitored_by) -> {monitored_by, MonitoredBy} | undefined

Types:

Port = port() | atom()
MonitoredBy = [pid()]

Returns list of pids that are monitoring given port at the moment. The opposite direction of the vibe โ€” who's watching you. ๐Ÿ”

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: name) -> {name, Name} | undefined

Types:

Port = port() | atom()
Name = string()

Name is the command name set by open_port/2. Its government name, if you will. ๐ŸŽ€

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


erlang:port_info(Port, Item :: os_pid) -> {os_pid, OsPid} | undefined

Types:

Port = port() | atom()
OsPid = integer() >= 0 | undefined

OsPid is the process identifier (or equivalent) of an OS process created with open_port({spawn | spawn_executable, Command}, Options). If the port is not the result of spawning an OS process, the value is undefined. No OS process, no OsPid โ€” that's the whole rule. ๐Ÿฆ‹

๐Ÿ’… erlang:port_info(Port, Item :: output) -> {output, Bytes} | undefined

Types: Port = port() | atom() and Bytes = integer() >= 0.

Bytes is the total number of bytes written to the port from Erlang processes using port_command/2, port_command/3, or Port ! {Owner, {command, Data}.

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


๐Ÿฆ‹ erlang:port_info(Port, Item :: parallelism) -> {parallelism, Boolean} | undefined

Types: Port = port() | atom() and Boolean = boolean().

Boolean corresponds to the port parallelism hint used by this port. For more information, see option parallelism of open_port/2.


๐ŸŽ€ erlang:port_info(Port, Item :: queue_size) -> {queue_size, Bytes} | undefined

Types: Port = port() | atom() and Bytes = integer() >= 0.

Bytes is the total number of bytes queued by the port using the ERTS driver queue implementation.

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


๐ŸŒธ erlang:port_info(Port, Item :: registered_name) -> {registered_name, RegisteredName} | [] | undefined

Types: Port = port() | atom() and RegisteredName = atom().

RegisteredName is the registered name of the port. If the port has no registered name, [] is returned.

If the port identified by Port is not open, undefined is returned. If the port is closed and the calling process was previously linked to the port, the exit signal from the port is guaranteed to be delivered before port_info/2 returns undefined.

Failure: badarg if Port is not a local port identifier, or an atom.


๐Ÿ’– port_to_list(Port) -> string()

Types: Port = port().

Returns a string corresponding to the text representation of the port identifier Port.


โœจ erlang:ports() -> [port()]

Returns a list of port identifiers corresponding to all the ports existing on the local node.

Heads up, bestie: an exiting port exists, but it is not open.


๐Ÿงš 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.


๐Ÿ”ฅ erlang:process_display(Pid, Type) -> true

Types: Pid = pid() and 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.


๐Ÿ‘‘ process_flag(Flag :: async_dist, Boolean) -> OldBoolean

Types: Boolean = OldBoolean = boolean().

Enable or disable fully asynchronous distributed signaling for the calling process. When disabled, which is the default, the process sending a distributed signal will block in the send operation if the buffer for the distribution channel reaches the distribution buffer busy limit. The process will remain blocked until the buffer shrinks enough. This might in some cases take a substantial amount of time. When async_dist is enabled, send operations of distributed signals will always buffer the signal on the outgoing distribution channel and then immediately return. That is, these send operations will never block the sending process.

Note, bestie: Since no flow control is enforced by the runtime system when async_dist process flag is enabled, you need to make sure that flow control for such data is implemented, or that the amount of such data is known to always be limited. Unlimited signaling with async_dist enabled in the absence of flow control will typically cause the sending runtime system to crash on an out of memory condition. Blocking due to disabled async_dist can be monitored by erlang:system_montor() 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. 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}. 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).

Returns the old value of the async_dist flag.


๐Ÿซถ process_flag(Flag :: trap_exit, Boolean) -> OldBoolean

Types: Boolean = OldBoolean = boolean().

When trap_exit is set to true, exit signals arriving to a process are converted to {'EXIT', From, Reason} messages, which can be received as ordinary messages. If trap_exit is set to false, the process exits if it receives an exit signal other than normal and the exit signal is propagated to its linked processes. Application processes are normally not supposed to trap exits.

Returns the old value of the flag.

See also exit/2.


๐Ÿ“ process_flag(Flag :: error_handler, Module) -> OldModule

Types: Module = OldModule = atom().

Used by a process to redefine the error handler for undefined function calls and undefined registered processes. Inexperienced users are not supposed to use this flag, as code auto-loading depends on the correct operation of the error handling module.

Returns the old value of the flag.


๐ŸŒˆ process_flag(Flag :: fullsweep_after, FullsweepAfter) -> OldFullsweepAfter

Types: FullsweepAfter = OldFullsweepAfter = integer() >= 0.

Changes the maximum number of generational collections before forcing a fullsweep for the calling process.

Returns the old value of the flag.


๐Ÿ’œ process_flag(Flag :: min_heap_size, MinHeapSize) -> OldMinHeapSize

Types: MinHeapSize = OldMinHeapSize = integer() >= 0.

Changes the minimum heap size for the calling process.

Returns the old value of the flag.


๐Ÿฆ‹ process_flag(Flag :: min_bin_vheap_size, MinBinVHeapSize) -> OldMinBinVHeapSize

Types: MinBinVHeapSize = OldMinBinVHeapSize = integer() >= 0.

Changes the minimum binary virtual heap size for the calling process.

Returns the old value of the flag.


๐Ÿ’… process_flag(Flag :: max_heap_size, MaxHeapSize) -> OldMaxHeapSize

Types: MaxHeapSize = OldMaxHeapSize = max_heap_size().

max_heap_size() =
    integer() >= 0 |
    #{size => integer() >= 0,
      kill => boolean(),
      error_logger => boolean()}

This flag sets the maximum heap size for the calling process. If MaxHeapSize is an integer, the system default values for kill and error_logger are 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. badarg is thrown if the value is smaller than min_heap_size. 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. This 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).
  • kill โ€” When set to true, the runtime system sends an untrappable exit signal with reason kill to 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 to false, no exit signal is sent to the process, 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(1), or erlang:system_flag(max_heap_size, MaxHeapSize).
  • error_logger โ€” When set to true, the runtime system logs an error event via logger, containing details about the process when the maximum heap size is reached. One log event is sent each time the limit is reached.
  • process_flag(Flag :: message_queue_data, MQD) -> OldMQD

Types:

MQD = OldMQD = message_queue_data()
message_queue_data() = off_heap | on_heap

okay so this one is literally about where your messages live ๐Ÿ’… It decides how messages in the message queue get stored, like this:

  • off_heap โ€” every single message in the message queue gets stored outside the process heap. Translation: no messages in the queue are ever part of a garbage collection of that process. slay, no GC drama ๐ŸŽ€
  • on_heap โ€” all messages in the message queue will eventually be placed on the process heap. They can be temporarily stored off the heap too, tho. This is literally how messages have always been stored up until ERTS 8.0. classic behavior โœจ

The default value of the message_queue_data process flag is determined by the command-line argument +hmqd in erl(1).

ngl if your process might potentially accumulate a large number of messages in its queue, bestie, set this flag to off_heap. Why? Because garbage collection of a process that has a large number of messages stored on the heap can become extremely expensive and the process can eat up large amounts of memory ๐Ÿ˜ญ The performance of the actual message passing is, however, 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 the second you get control back ๐Ÿ™ˆ

Returns the old value of the flag. ๐Ÿ’–


  • process_flag(Flag :: priority, Level) -> OldLevel

Types:

Level = OldLevel = priority_level()
priority_level() = low | normal | high | max

Sets the process priority, periodt. Level is an atom. Four priority levels exist: low, normal, high, and max. Default is normal.

Note: Priority level max is reserved for internal use in the Erlang runtime system, and is not to be used by others. hands off, it's not for us ๐Ÿ’€

Internally in each priority level, processes are scheduled in a round robin fashion. iconic little rotation ๐ŸŒ€

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. But notice โ€” 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. parallelism said "I don't care about your priority labels" ๐Ÿ˜Œ

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. reductions are the vibe check here bestie ๐Ÿ”ฅ

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. fr fr, don't build your whole app on it ๐Ÿ™

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 on your own for that one ๐Ÿซถ

Making calls from a high priority process into code that you has 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. so like, surprise priority demotion, not the fun kind ๐Ÿ˜ญ

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. seriously, don't hog the high lane, it's giving main character syndrome ๐Ÿ’…

Returns the old value of the flag.


  • process_flag(Flag :: save_calls, N) -> OldN

Types:

N = OldN = 0..10000

N must be an integer in the interval 0..10000. If N > 0, call saving is made active for the process. This means that information about the N most recent global function calls, BIF calls, sends, and receives made by the process are saved in a list, which can be retrieved with process_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:

  • A tuple {Module, Function, Arity} for function calls
  • The atoms send, 'receive', and timeout for sends and receives ('receive' when a message is received and timeout when a receive times out)

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. fresh start, love that for you ๐ŸŒธ

Returns the old value of the flag.


  • process_flag(Flag :: sensitive, Boolean) -> OldBoolean

Types:

Boolean = OldBoolean = boolean()

Sets or clears flag sensitive for the current process. When a process has been marked as sensitive by calling process_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. like going private mode, nobody sees anything ๐Ÿ™ˆ

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 sensitive is 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). empty, as in "there's nothing to see here" ๐Ÿ˜Œ

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.) โœจ

Returns the old value of the flag.


  • process_flag(Pid, Flag, Value) -> OldValue

Types:

Pid = pid()
Flag = save_calls
Value = OldValue = integer() >= 0

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. just the one bestie, don't get greedy ๐ŸŽ€

Failure: badarg if Pid is not a local process. like, local only, no long-distance flag setting ๐Ÿ’€


  • process_info(Pid) -> Info

Types:

<!-- continuing in the next part, this one cuts off right here ๐Ÿฆ‹ -->

                 Pid = pid()
                 Info = [InfoTuple] | undefined
                 InfoTuple = process_info_result_item()
                 process_info_result_item() =
                     {async_dist, Enabled :: boolean()} |
                     {backtrace, Bin :: binary()} |
                     {binary,
                      BinInfo ::
                          [{integer() >= 0,
                            integer() >= 0,
                            integer() >= 0}]} |
                     {catchlevel, CatchLevel :: integer() >= 0} |
                     {current_function,
                      {Module :: module(), Function :: atom(), Arity :: arity()} |
                      undefined} |
                     {current_location,
                      {Module :: module(),
                       Function :: atom(),
                       Arity :: arity(),
                       Location ::
                           [{file, Filename :: string()} |
                            {line, Line :: integer() >= 1}]}} |
                     {current_stacktrace, Stack :: [stack_item()]} |
                     {dictionary, Dictionary :: [{Key :: term(), Value :: term()}]} |
                     {error_handler, Module :: module()} |
                     {garbage_collection, GCInfo :: [{atom(), integer() >= 0}]} |
                     {garbage_collection_info,
                      GCInfo :: [{atom(), integer() >= 0}]} |
                     {group_leader, GroupLeader :: pid()} |
                     {heap_size, Size :: integer() >= 0} |
                     {initial_call, mfa()} |
                     {links, PidsAndPorts :: [pid() | port()]} |
                     {last_calls, false | (Calls :: [mfa()])} |
                     {memory, Size :: integer() >= 0} |
                     {message_queue_len, MessageQueueLen :: integer() >= 0} |
                     {messages, MessageQueue :: [term()]} |
                     {min_heap_size, MinHeapSize :: integer() >= 0} |
                     {min_bin_vheap_size, MinBinVHeapSize :: integer() >= 0} |
                     {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()} |
                     {reductions, Number :: integer() >= 0} |
                     {registered_name, [] | (Atom :: atom())} |
                     {sequential_trace_token,
                      [] | (SequentialTraceToken :: term())} |
                     {stack_size, Size :: integer() >= 0} |
                     {status,
                      Status ::
                          exiting | garbage_collecting | waiting | running |
                          runnable | suspended} |
                     {suspending,
                      SuspendeeList ::
                          [{Suspendee :: pid(),
                            ActiveSuspendCount :: integer() >= 0,
                            OutstandingSuspendCount :: integer() >= 0}]} |
                     {total_heap_size, Size :: integer() >= 0} |
                     {trace, InternalTraceFlags :: integer() >= 0} |
                     {trap_exit, Boolean :: boolean()}
                 priority_level() = low | normal | high | max
                 stack_item() =
                     {Module :: module(),
                      Function :: atom(),
                      Arity :: arity() | (Args :: [term()]),
                      Location ::
                          [{file, Filename :: string()} |
                           {line, Line :: integer() >= 1}]}
                 max_heap_size() =
                     integer() >= 0 |
                     #{size => integer() >= 0,
                       kill => boolean(),
                       error_logger => boolean()}
                 message_queue_data() = off_heap | on_heap

So okay, this one hands you back a list of InfoTuples with all kinds of random lil facts about the process that Pid is pointing at โ€” and if that process is not alive, you get undefined. Rude but fair. ๐Ÿ’€

Heads up though: the order of those InfoTuples is literally undefined, and not every InfoTuple is guaranteed to show up. Also the set of InfoTuples that come back in the result can change without prior notice, so likeโ€ฆ don't build your whole personality on it, bestie. ๐Ÿ™ˆ

These are the InfoTuples that are part of the result:

  • current_function
  • initial_call
  • status
  • message_queue_len
  • links
  • dictionary
  • trap_exit
  • error_handler
  • priority
  • group_leader
  • total_heap_size
  • heap_size
  • stack_size
  • reductions
  • garbage_collection

And hiii, bonus round: if the process identified by Pid has a registered name, you also get an InfoTuple with item registered_name in there. ๐Ÿ‘‘

Want the tea on any specific InfoTuple? Go look at process_info/2, that's where the details live.

โš ๏ธ Warning: bestie listen to me โ€” this BIF is intended for debugging only. For all other purposes, use process_info/2. No cap.

Failure: badarg if Pid is not a local process.


๐Ÿ’… process_info(Pid, Item) -> InfoTuple | [] | undefined

๐Ÿ’… process_info(Pid, ItemList) -> InfoTupleList | [] | undefined

Types:

                 Pid = pid()
                 ItemList = [Item]
                 Item = process_info_item()
                 InfoTupleList = [InfoTuple]
                 InfoTuple = process_info_result_item()
                 process_info_item() =
                     async_dist | backtrace | binary | catchlevel |
                     current_function | current_location | current_stacktrace |
                     dictionary | error_handler | garbage_collection |
                     garbage_collection_info | group_leader | heap_size |
                     initial_call | links | last_calls | memory |
                     message_queue_len | messages | min_heap_size |
                     min_bin_vheap_size | monitored_by | monitors |
                     message_queue_data | parent | priority | reductions |
                     registered_name | sequential_trace_token | stack_size |
                     status | suspending | total_heap_size | trace | trap_exit
                 process_info_result_item() =
                     {async_dist, Enabled :: boolean()} |
                     {backtrace, Bin :: binary()} |
                     {binary,
                      BinInfo ::
                          [{integer() >= 0,
                            integer() >= 0,
                            integer() >= 0}]} |
                     {catchlevel, CatchLevel :: integer() >= 0} |
                     {current_function,
                      {Module :: module(), Function :: atom(), Arity :: arity()} |
                      undefined} |
                     {current_location,
                      {Module :: module(),
                       Function :: atom(),
                       Arity :: arity(),
                       Location ::
                           [{file, Filename :: string()} |
                            {line, Line :: integer() >= 1}]}} |
                     {current_stacktrace, Stack :: [stack_item()]} |
                     {dictionary, Dictionary :: [{Key :: term(), Value :: term()}]} |
                     {error_handler, Module :: module()} |
                     {garbage_collection, GCInfo :: [{atom(), integer() >= 0}]} |
                     {garbage_collection_info,
                      GCInfo :: [{atom(), integer() >= 0}]} |
                     {group_leader, GroupLeader :: pid()} |
                     {heap_size, Size :: integer() >= 0} |
                     {initial_call, mfa()} |
                     {links, PidsAndPorts :: [pid() | port()]} |
                     {last_calls, false | (Calls :: [mfa()])} |
                     {memory, Size :: integer() >= 0} |
                     {message_queue_len, MessageQueueLen :: integer() >= 0} |
                     {messages, MessageQueue :: [term()]} |
                     {min_heap_size, MinHeapSize :: integer() >= 0} |
                     {min_bin_vheap_size, MinBinVHeapSize :: integer() >= 0} |
                     {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()} |
                     {reductions, Number :: integer() >= 0} |
                     {registered_name, [] | (Atom :: atom())} |
                     {sequential_trace_token,
                      [] | (SequentialTraceToken :: term())} |
                     {stack_size, Size :: integer() >= 0} |
                     {status,
                      Status ::
                          exiting | garbage_collecting | waiting | running |
                          runnable | suspended} |
                     {suspending,
                      SuspendeeList ::
                          [{Suspendee :: pid(),
                            ActiveSuspendCount :: integer() >= 0,
                            OutstandingSuspendCount :: integer() >= 0}]} |
                     {total_heap_size, Size :: integer() >= 0} |
                     {trace, InternalTraceFlags :: integer() >= 0} |
                     {trap_exit, Boolean :: boolean()}
                 stack_item() =
                     {Module :: module(),
                      Function :: atom(),
                      Arity :: arity() | (Args :: [term()]),
                      Location ::
                          [{file, Filename :: string()} |
                           {line, Line :: integer() >= 1}]}
                 priority_level() = low | normal | high | max
                 max_heap_size() =
                     integer() >= 0 |
                     #{size => integer() >= 0,
                       kill => boolean(),
                       error_logger => boolean()}
                 message_queue_data() = off_heap | on_heap

This is the actual good one, slay. ๐Ÿ’– You pass in Pid plus an Item or an ItemList, and it gives you info about that process, exactly as you asked. If the process isn't alive? You get undefined. Simple as that.

Now here's the โœจquirkyโœจ part, and when I say quirky I mean it's giving "load-bearing historical baggage": if the process is alive and you asked for a single Item, you get back the matching InfoTuple โ€” unless Item =:= registered_name and the process has no registered name. In that specific case you get [] back instead. Why? Strange behavior, historical reasons, kept around for backward compatibility. So likeโ€ฆ yes it's weird, no we can't change it, hands are tied bestie. ๐Ÿซ 

If you pass an ItemList instead, the result is InfoTupleList. The InfoTuples inside it are included with the corresponding Items in the same order that the Items appeared in your ItemList. And yes, you're fully allowed to include valid Items multiple times in ItemList โ€” ask for status four times if that's your vibe. ๐ŸŒˆ

Getting process information follows the signal ordering guarantees described in the Processes Chapter in the Erlang Reference Manual.

Note: if registered_name is part of ItemList and the process has no name registered, a {registered_name, []} InfoTuple will be included in the resulting InfoTupleList. This behavior is different when a single Item =:= registered_name is specified, and when process_info/1 is used. okay so like, remember this one, it's a vibe-check gotcha ๐Ÿซถ

Valid InfoTuples with corresponding Items โ€” bestie there are a LOT of them, buckle up ๐ŸŽ€:

  • {async_dist, Enabled} โ€” since OTP 25.3, this is the current value of the async_dist process flag. โœจ
  • {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} โ€” BinInfo is a list containing miscellaneous information about binaries on the heap of this process. This InfoTuple can be changed or removed without prior notice. In the current implementation BinInfo is a list of tuples. The tuples contain; BinaryId, BinarySize, BinaryRefcCount. Depending on the value of the message_queue_data process flag the message queue may be stored on the heap. ๐Ÿฆ‹
  • {catchlevel, CatchLevel} โ€” CatchLevel is the number of currently active catches in this process. This InfoTuple can be changed or removed without prior notice.
  • {current_function, {Module, Function, Arity} | undefined} โ€” Module, Function, Arity is the current function call of the process. The value undefined can be returned if the process is currently executing native compiled code. ๐Ÿ˜ญ
  • {current_location, {Module, Function, Arity, Location}} โ€” Module, Function, Arity is the current function call of the process. Location is 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 a try. See The call-stack back trace (stacktrace). The depth of the stacktrace is truncated according to the backtrace_depth system flag setting. ๐Ÿ”ฅ
  • {dictionary, Dictionary} โ€” Dictionary is the process dictionary.
  • {error_handler, Module} โ€” Module is the error handler module used by the process (for undefined function calls, for example).
  • {garbage_collection, GCInfo} โ€” GCInfo is a list containing miscellaneous information about garbage collection for this process. The content of GCInfo can be changed without prior notice. ๐ŸŒธ
  • {garbage_collection_info, GCInfo} โ€” GCInfo is a list containing miscellaneous detailed information about garbage collection for this process. The content of GCInfo can be changed without prior notice. For details about the meaning of each item, see gc_minor_start in erlang:trace/3. โœจ
  • {group_leader, GroupLeader} โ€” GroupLeader is the group leader for the I/O of the process.
  • {heap_size, Size} โ€” Size is 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. ๐Ÿ’€ (fr, don't hardcode anything around this)
  • {initial_call, {Module, Function, Arity}} โ€” Module, Function, Arity is the initial function call with which the process was spawned.
  • {links, PidsAndPorts} โ€” PidsAndPorts is a list of process identifiers and port identifiers, with processes or ports to which the process has a link. ๐Ÿ”—
  • {last_calls, false|Calls} โ€” The value is false if call saving is not active for the process (see process_flag/3). If call saving is active, a list is returned, in which the last element is the most recent called.
  • {memory, Size} โ€” Size is the size in bytes of the process. This includes call stack, heap, and internal structures.
  • {message_queue_len, MessageQueueLen} โ€” MessageQueueLen is the number of messages currently in the message queue of the process. This is the length of the list MessageQueue returned as the information item messages (see below). ๐Ÿ“จ
  • {messages, MessageQueue} โ€” MessageQueue is a list of the messages to the process, which have not yet been processed.
  • {min_heap_size, MinHeapSize} โ€” MinHeapSize is the minimum heap size for the process.
  • {min_bin_vheap_size, MinBinVHeapSize} โ€” MinBinVHeapSize is 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 by monitor/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, so Node will always be the local node name. ๐Ÿซถ
  • {message_queue_data, MQD} โ€” MQD is the current value of the message_queue_data process flag, which can be either off_heap or on_heap. For more information, see the documentation of process_flag(message_queue_data, MQD).
  • {parent, Pid} โ€” Pid is the identifier of the parent process, the one that spawned current process. When the process does not have a parent undefined is returned. Only the initial process (init) on a node lacks a parent, though. ๐Ÿงš
  • {priority, Level} โ€” Level is the current priority level for the process. For more information on priorities, see process_flag(priority, Level).
  • {reductions, Number} โ€” Number is the number of reductions executed by the process.
  • {registered_name, Atom} โ€” Atom is the registered process name. If the process has no registered name, this tuple is not present in the list. (yes, that's the gotcha from the note above, iykyk ๐Ÿ˜ญ)
  • {sequential_trace_token, [] | SequentialTraceToken} โ€” SequentialTraceToken is the sequential trace token for the process. This InfoTuple can be changed or removed without prior notice.
  • {stack_size, Size} โ€” Size is the stack size, in words, of the process.
  • {status, Status} โ€” Status is the status of the process and is one of the following:
    • exiting
    • garbage_collecting
    • waiting (for a message)
    • running
    • runnable (ready to run, but another process is running)
    • suspended (suspended on a "busy" port or by the BIF erlang:suspend_process/1,2)
  • {suspending, SuspendeeList} โ€” SuspendeeList is a list of {Suspendee, ActiveSuspendCount, OutstandingSuspendCount} tuples. Suspendee is the process identifier of a process that has been, or is to be, suspended by the process identified by Pid through the BIF erlang:suspend_process/2 or erlang: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, Suspendee is currently in the suspended state.
    • If OutstandingSuspendCount =/= 0, option asynchronous of erlang:suspend_process/2 has been used and the suspendee has not yet been suspended by Pid.

Notice that ActiveSuspendCount and OutstandingSuspendCount are not the total suspend count on Suspendee, only the parts contributed by Pid. ๐Ÿ’…

  • {total_heap_size, Size} โ€” Size is 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} โ€” InternalTraceFlags is an integer representing the internal trace flag for this process. This InfoTuple can be changed or removed without prior notice.
  • {trap_exit, Boolean} โ€” Boolean is true if the process is trapping exits, otherwise false. ๐ŸŒˆ

Notice that not all implementations support all these Items. ๐Ÿซ 

Failures:

  • badarg โ€” if Pid is not a local process.
  • badarg โ€” if Item is an invalid item.

โœจ processes() -> [pid()] โœจ

Returns a list of process identifiers corresponding to all the processes currently existing on the local node. ๐Ÿ‘‘

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. (the way that's lowkey confusing but it's true ๐Ÿซถ)

Example:

> processes().
[<0.0.0>,<0.2.0>,<0.4.0>,<0.5.0>,<0.7.0>,<0.8.0>]

๐ŸŒธ purge_module(Module) -> true ๐ŸŒธ

Types:

Module = atom()

Removes old code for Module. Before this BIF is used, check_process_code/2 is to be called to check that no processes execute old code in the module. ๐Ÿงน

Warning: this BIF is intended for the code server (see code(3erl)) and is not to be used elsewhere. bestie i'm serious, leave it to the code server, it's giving main character energy that you should not steal ๐Ÿ’€
Note: As from ERTS 8.0 (Erlang/OTP 19), any lingering processes that still execute the old code is killed by this function. In earlier versions, such incorrect use could cause much more fatal failures, like emulator crash. ๐Ÿ˜ญ

Failure: badarg if there is no old code for Module.

๐Ÿซถ put(Key, Val) -> term()

Types:

Key = Val = term()

Adds a new Key to the process dictionary, associated with the value Val, and returns undefined. If Key exists, the old value is deleted and replaced by Val, and the function returns the old value. 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. Example:

> X = put(name, walrus), Y = put(name, carpenter),
Z = get(name),
{X, Y, Z}.
{undefined,walrus,carpenter}
Note: The values stored when put is evaluated within the scope of a catch are not retracted if a throw is evaluated, or if an error occurs.

๐ŸŒˆ erlang:raise(Class, Reason, Stacktrace) -> badarg

Types:

Class = error | exit | throw
Reason = term()
Stacktrace = raise_stacktrace() | stacktrace()
raise_stacktrace() =
    [{module(), atom(), arity() | [term()]} |
     {function(), arity() | [term()]}]

Raises an exception of the specified class, reason, and call stack backtrace (stacktrace). ๐Ÿ’ฅ

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.

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. ๐Ÿ™ˆ

See the reference manual about errors and error handling for more information about exception classes and how to catch exceptions.

๐ŸŽ€ erlang:read_timer(TimerRef) -> Result

Types:

TimerRef = reference()
Time = integer() >= 0
Result = Time | false

Reads the state of a timer. The same as calling erlang:read_timer(TimerRef, []).

๐Ÿฆ‹ erlang:read_timer(TimerRef, Options) -> Result | ok

Types:

TimerRef = reference()
Async = boolean()
Option = {async, Async}
Options = [Option]
Time = integer() >= 0
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.

Options:

  • {async, Async} โ€” Asynchronous request for state information. Async defaults to false, which causes the operation to be performed synchronously. In this case, the Result is returned by erlang:read_timer. When Async is true, erlang:read_timer sends an asynchronous request for the state information to the timer service that manages the timer, and then returns ok. A message on the format {read_timer, TimerRef, Result} is sent to the caller of erlang:read_timer when the operation has been processed.

More Options can be added in the future. โœจ

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. ๐Ÿ’€

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

Types:

Ref = reference()

Returns a string corresponding to the text representation of Ref.

Warning: This BIF is intended for debugging and is not to be used in application programs. ๐Ÿšจ

๐Ÿ‘‘ register(RegName, PidOrPort) -> true

Types:

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. Example:

> register(db, Pid).
true

The registered name is considered a Directly Visible Erlang Resource and is automatically unregistered when the process terminates.

Failures:

  • badarg โ€” If PidOrPort is not an existing local process or port.
  • badarg โ€” If RegName is already in use.
  • badarg โ€” If the process or port is already registered (already has a name).
  • badarg โ€” If RegName is the atom undefined.

๐ŸŒธ registered() -> [RegName]

Types:

RegName = atom()

Returns a list of names that have been registered using register/2, for example:

> registered().
[code_server, file_server, init, user, my_db]

๐Ÿ’… erlang:resume_process(Suspendee) -> true

Types:

Suspendee = pid()

Decreases the suspend count on the process identified by Suspendee. 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. ๐Ÿšจ

Failures:

  • badarg โ€” If Suspendee is not a process identifier.
  • badarg โ€” If the process calling erlang:resume_process/1 had not previously increased the suspend count on the process identified by Suspendee.
  • badarg โ€” If the process identified by Suspendee is not alive.

โญ round(Number) -> integer()

Types:

Number = number()

Returns an integer by rounding Number, for example:

round(42.1).
42

round(5.5).
6

round(-5.5).
-6

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.

Allowed in guard tests.

๐Ÿฆ‹ self() -> pid()

Returns the process identifier of the calling process, for example:

> self().
<0.26.0>

Allowed in guard tests.

๐Ÿ”ฅ erlang:send(Dest, Msg) -> Msg

Types:

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.

The function fails with a badarg run-time error if Dest is an atom name, but this name is not registered. This is the only case when send fails for an unreachable destination Dest (of correct type).

๐Ÿ’œ erlang:send(Dest, Msg, Options) -> Res

Types:

Dest = send_destination()
Msg = term()
Options = [nosuspend | noconnect]
Res = ok | nosuspend | noconnect

Either sends a message and returns ok, or does not send the message but returns something else (see below). Otherwise the same as erlang:send/2. For more detailed explanation and warnings, see erlang:send_nosuspend/2,3.

Options:

  • nosuspend โ€” If the sender would have to be suspended to do the send, nosuspend is returned instead.
  • noconnect โ€” If the destination node would have to be auto-connected to do the send, noconnect is returned instead.
Warning: As with erlang:send_nosuspend/2,3: use with extreme care. โš ๏ธ

erlang:send_after(Time, Dest, Msg) -> TimerRef

bestie it's timer time โฐ this one starts a timer, and it's literally the same as calling erlang:send_after(Time, Dest, Msg, []). that's the whole entire vibe of this clause, no cap.

Types, because we keep receipts ๐Ÿงพ:

Time = integer() >= 0
Dest = pid() | atom()
Msg = term()
TimerRef = reference()

erlang:send_after(Time, Dest, Msg, Options) -> TimerRef

Starts a timer ๐ŸŽ€ and when that timer expires, the message Msg gets sent to the process identified by Dest. And apart from the format of the time-out message, this function works exactly as erlang:start_timer/4. iykyk.

The types, slay:

Time = integer()
Dest = pid() | atom()
Msg = term()
Options = [Option]
Abs = boolean()
Option = {abs, Abs}
TimerRef = reference()
๐Ÿ‘€ note that Time here is integer() with no >= 0 attached, unlike the /3 version above. just saying.

erlang:send_nosuspend(Dest, Msg) -> boolean()

okay so this is the same as erlang:send(Dest, Msg, [nosuspend]), BUT it gives you a boolean back: true if the message was sent, and false if it wasn't, because the sender would have had to be suspended. ๐Ÿซ 

Types:

Dest = send_destination()
Msg = term()

This function is for send operations to an unreliable remote node, and the whole point is that it never blocks the sending (Erlang) process. ever. If the connection to that remote node is overloaded โ€” and heads up, that node is usually not a real Erlang node, it's more likely a node written in C or Java โ€” then this function just does not send the message and returns false.

Same thing happens if Dest refers to a local port that's busy. For all other destinations (the ones allowed for the ordinary send operator !), this function sends the message and returns true. ๐Ÿ‘

Now, the important part: 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 by net_kernel (because of tick time-outs). The normal reaction when this happens is some kind of premature shutdown of the other node. ๐Ÿ’€

Notice that ignoring the return value from this function would result in unreliable message passing, which is contradictory to the Erlang programming model. The message is not sent if this function returns false. so like, don't ignore it, bestie.

In many systems, transient states of overloaded queues are just normal. false does not mean the other node is guaranteed to be non-responsive โ€” it could just be a temporary overload. And a true only means the message can be sent on the (TCP) channel without blocking; it does not guarantee the message arrives at the remote node. For a disconnected non-responsive node, the return value is true (it mimics the behavior of operator !). The expected behavior and the actions to take when the function returns false are application- and hardware-specific. ๐ŸŒˆ

โš ๏ธ Warning: Use with extreme care.

erlang:send_nosuspend(Dest, Msg, Options) -> boolean()

Same as erlang:send(Dest, Msg, [nosuspend | Options]), but with a Boolean return value. ๐ŸŽ€

Types:

Dest = send_destination()
Msg = term()
Options = [noconnect]

This one behaves like erlang:send_nosuspend/2, but it takes a third parameter, a list of options. The only option is noconnect, which makes the function return false if the remote node isn't 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. Using option noconnect makes it possible to be sure you don't get the slightest delay when sending to a remote process โœจ โ€” 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. ๐Ÿ’…

โš ๏ธ Warning: Use with extreme care.

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 (see section Distributed Erlang in the Erlang Reference Manual in System Documentation).

Types:

Cookie = atom()

You can get this value using get_cookie/0.

Failure: function_clause if the local node is not alive. ๐Ÿ˜ญ


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 (see section Distributed Erlang in the Erlang Reference Manual in System Documentation).

Types:

Node = node()
Cookie = atom()

You can get this value using get_cookie/1.

Failure: function_clause if the local node is not alive. ๐Ÿ˜ญ


setelement(Index, Tuple1, Value) -> Tuple2

Returns a tuple that is a copy of argument Tuple1 with the element specified by integer argument Index (the first element is the element with index 1) replaced by argument Value. iconic behavior, honestly. ๐Ÿ’…

Types:

Index = integer() >= 1
  1..tuple_size(Tuple1)
Tuple1 = Tuple2 = tuple()
Value = term()

Example, because seeing it is believing:

> setelement(2, {10, green, bottles}, red).
{10,red,bottles}

size(Item) -> integer() >= 0

Returns the number of elements in a tuple, or the number of bytes in a binary or bitstring. ๐ŸŽ€

Types:

Item = tuple() | binary()

Examples:

> size({morni, mulle, bwange}).
3
> size(<<11, 22, 33>>).
3

For bitstrings, the number of whole bytes is returned. That is, if the number of bits in the bitstring isn't divisible by 8, the resulting number of bytes is rounded down. ๐Ÿซถ

Allowed in guard tests. โœ…

See also tuple_size/1, byte_size/1, and bit_size/1.


spawn(Fun) -> pid()

Returns the process identifier of a new process, started by the application of Fun to the empty list []. Otherwise it works like spawn/3. ๐Ÿฃ

Types:

Fun = function()

spawn(Node, Fun) -> pid()

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. Otherwise works like spawn/3. ๐Ÿ’€

Types:

Node = node()
Fun = function()

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

Returns the process identifier of a new process started by the application of Module:Function to Args. ๐ŸŒธ

Types:

Module = module()
Function = atom()
Args = [term()]

error_handler:undefined_function(Module, Function, Args) is evaluated by the new process if Module:Function/Arity doesn't 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(Node, Module, Function, Args) -> pid()

Returns the process identifier (pid) of a new process started by the application of Module:Function to Args on Node. If Node does not exist, a useless pid is returned. Otherwise works like spawn/3. ๐Ÿฆ‹

Types:

Node = node()
Module = module()
Function = atom()
Args = [term()]

Returns the process identifier of a new process started by the application of Fun to the empty list []. A link is created between the calling process and the new process, atomically. ๐Ÿ”— Otherwise works like spawn/3.

Types:

Fun = function()

Returns the process identifier (pid) of a new process started by the application of Fun to the empty list [] on Node. A link is created between the calling process and the new process, atomically. ๐Ÿ”—โœจ If Node does not exist, a useless pid is returned and an exit signal with reason noconnection is sent to the calling process. ๐Ÿ˜ญ Otherwise works like spawn/3.

Types:

Node = node()
Fun = function()

Returns the process identifier of a new process started by the application of Module:Function to Args. A link is created between the calling process and the new process, atomically. ๐Ÿ”—๐ŸŒธ Otherwise works like spawn/3.

Types:

Module = module()
Function = atom()
Args = [term()]

Returns the process identifier (pid) of a new process started by the application of Module:Function to Args on Node. A link is created between the calling process and the new process, atomically. ๐Ÿ”—๐Ÿ’œ If Node does not exist, a useless pid is returned and an exit signal with reason noconnection is sent to the calling process. Otherwise works like spawn/3.

Types:

Node = node()
Module = module()
Function = atom()
Args = [term()]

spawn_monitor(Fun) -> {pid(), reference()}

Returns the process identifier of a new process, started by the application of Fun to the empty list [], and a reference for a monitor created to the new process. ๐Ÿ‘€๐Ÿ” Otherwise works like spawn/3.

Types:

Fun = function()

spawn_monitor(Node, Fun) -> {pid(), reference()}

Returns the process identifier of a new process, started by the application of 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.

Types:

Node = node()
Fun = function()

If the node identified by Node doesn't support distributed spawn_monitor(), the call will fail with a notsup exception. So likeโ€ฆ vibe check your cluster first, bestie ๐Ÿซถ


spawn_monitor(Module, Function, Args) -> {pid(), reference()}

Types:

Module = module()
Function = atom()
Args = [term()]

A whole new process gets started by applying Module:Function to Args โ€” and it's monitored at the same time, iconic behavior honestly. You get back the process identifier and a reference for the monitor. Other than that, it works exactly like spawn/3. ๐Ÿ’…


spawn_monitor(Node, Module, Function, Args) -> {pid(), reference()}

Types:

Node = node()
Module = module()
Function = atom()
Args = [term()]

A new process gets started by applying Module:Function to Args on the node Node, and it's monitored at the same time. Returns the process identifier and a reference for the monitor. Otherwise works like spawn/3. โœจ

If the node identified by Node does not support distributed spawn_monitor(), the call will fail with a notsup exception. Yeah. That one again. Not all nodes are ready for that kind of commitment ๐Ÿ˜ญ


spawn_opt(Fun, Options) -> pid() | {pid(), reference()}

Types:

Fun = function()
Options = [spawn_opt_option()]
priority_level() = low | normal | high | max
max_heap_size() =
    integer() >= 0 |
    #{size => integer() >= 0,
      kill => boolean(),
      error_logger => boolean()}
message_queue_data() = off_heap | on_heap
spawn_opt_option() =
    link | monitor |
    {monitor, MonitorOpts :: [monitor_option()]} |
    {priority, Level :: priority_level()} |
    {fullsweep_after, Number :: integer() >= 0} |
    {min_heap_size, Size :: integer() >= 0} |
    {min_bin_vheap_size, VSize :: integer() >= 0} |
    {max_heap_size, Size :: max_heap_size()} |
    {message_queue_data, MQD :: message_queue_data()} |
    {async_dist, Enabled :: boolean()}

Returns the process identifier (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 both the pid and the reference for the monitor are returned โ€” a little two-for-one deal, we love to see it ๐Ÿ’–


spawn_opt(Node, Fun, Options) -> pid() | {pid(), reference()}

Types:

Node = node()
Fun = function()
Options =
    [monitor | {monitor, [monitor_option()]} | link |
OtherOption]
OtherOption = term()

Returns the process identifier (pid) of a new process started by applying Fun to the empty list [] on Node. If Node does not exist, a useless pid is returned. (Useless. Not even gonna sugarcoat it. ๐Ÿ’€) Otherwise works like spawn_opt/4.

Valid options depend on what options are supported by the node identified by Node. A description of valid Options for the local node of the current OTP version can be found in the documentation of spawn_opt/4. Basically: check what your node actually supports, don't just assume โœจ


spawn_opt(Module, Function, Args, Options) -> Pid | {Pid, MonitorRef}

Types:

Module = module()
Function = atom()
Args = [term()]
Options = [spawn_opt_option()]
Pid = pid()
MonitorRef = reference()
priority_level() = low | normal | high | max
max_heap_size() =
    integer() >= 0 |
    #{size => integer() >= 0,
      kill => boolean(),
      error_logger => boolean()}
message_queue_data() = off_heap | on_heap
spawn_opt_option() =
    link | monitor |
    {monitor, MonitorOpts :: [monitor_option()]} |
    {priority, Level :: priority_level()} |
    {fullsweep_after, Number :: integer() >= 0} |
    {min_heap_size, Size :: integer() >= 0} |
    {min_bin_vheap_size, VSize :: integer() >= 0} |
    {max_heap_size, Size :: max_heap_size()} |
    {message_queue_data, MQD :: message_queue_data()} |
    {async_dist, Enabled :: boolean()}

Works as spawn/3, except that an extra option list is specified when creating the process. Custom order, off the menu, main character energy ๐Ÿ‘‘

If the option monitor is specified, the newly created process is monitored, and both the pid and the reference for the monitor are returned. ๐ŸŽ€

Options:

  • link โ€” sets a link to the parent process (like spawn_link/3 does). Bound for life, no cap.
  • monitor โ€” monitors the new process (like monitor(process, Pid) does). A {Pid, MonitorRef} tuple will be returned instead of just a Pid. ๐Ÿ‘€
  • {monitor, MonitorOpts} โ€” monitors the new process with options (like monitor(process, Pid, MonitorOpts) does). A {Pid, MonitorRef} tuple will be returned instead of just a Pid. Fancy monitoring, we're obsessed.
  • {priority, Level} โ€” sets the priority of the new process. Equivalent to executing process_flag(priority, Level) in the start function of the new process, except that the priority is set before the process is selected for execution for the first time. For more info on priorities, see process_flag(priority, Level). Like giving your process a VIP lanyard before it even walks in ๐ŸŽŸ๏ธ
  • {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 matters. Fr fr, this is not a "just try it" situation ๐Ÿ™ˆ

The Erlang runtime system uses a generational garbage collection scheme, using 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 is room on the old heap. Setting the number to zero disables the general collection algorithm โ€” that is, all live data is copied at every garbage collection. ๐Ÿ˜ญ

A few cases when it can be useful to change fullsweep_after:

  • If binaries that are no longer used are to be thrown away as soon as possible. (Set Number to zero.) Bye bestie, don't let the door hit you ๐Ÿ’…
  • A process that mostly has short-lived data is fullsweeped seldom or never, that is, the old heap contains mostly garbage. To ensure a fullsweep occasionally, set Number to a suitable value, such as 10 or 20.
  • In embedded systems with a limited amount of RAM and no virtual memory, you might want to preserve memory by setting Number to zero. (The value can be set globally, see erlang: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 ensure that the option improves matters. Same disclaimer, same energy ๐Ÿ’€

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 a too high value can waste memory and slow down the system because of worse data locality. Therefore, use this option only for fine-tuning an application and to measure the execution time with various Size values. Science, not vibes ๐Ÿ”ฅ

  • {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 ensure that the option improves matters. (Yes, we're saying it a third time. It's that serious.)

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 a too high value can waste memory. Therefore, use this option only for fine-tuning an application and to measure the execution time with various VSize values. ๐Ÿงš

  • {max_heap_size, Size} โ€” sets the max_heap_size process flag. The default max_heap_size is determined by command-line argument +hmax in erl(1). For more information, see the documentation of process_flag(max_heap_size, Size). Boundaries, bestie ๐Ÿšง
  • {message_queue_data, MQD} โ€” sets the value of the message_queue_data process flag. MQD can be either off_heap or on_heap. The default value of the message_queue_data process flag is determined by the command-line argument +hmqd in erl(1). For more info, see the documentation of process_flag(message_queue_data, MQD). ๐Ÿ“
  • {async_dist, Enabled} โ€” Since: OTP 25.3

Set the async_dist process flag of the spawned process. This option will override the default value set by the command line argument +pad <boolean>. Override era, sorry to the command line โญ


spawn_opt(Node, Module, Function, Args, Options) -> pid() | {pid(), reference()}

Types:

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 applying Module:Function to Args on Node. If Node does not exist, a useless pid is returned. (Again. Useless. ๐Ÿ˜ญ) Otherwise works like spawn_opt/4.

Valid options depend on what options are supported by the node identified by Node. A description of valid Options for the local node of the current OTP version can be found in the documentation of spawn_opt/4. Read the room, and also read spawn_opt/4 ๐Ÿซถ


spawn_request(Fun) -> ReqId

Types:

Fun = function()
ReqId = reference()

The same as the call spawn_request(node(),Fun,[]). That is, a spawn request on the local node with no options. Minimalist. Clean. Lowkey elegant โœจ


spawn_request(Fun, Options) -> ReqId

Types:

Fun = function()
Option =
    {reply_tag, ReplyTag} | {reply, Reply} |
spawn_opt_option()
ReplyTag = term()
Reply = yes | no | error_only | success_only
Options = [Option]
ReqId = reference()

Lowkey the exact same as calling spawn_request(node(),Fun,Options) โ€” i.e. a spawn request that stays home, on the local node. ๐Ÿ โœจ

spawn_request(Node, Fun) -> ReqId

Types:

Node = node()
Fun = function()
ReqId = reference()

Same as spawn_request(Node,Fun,[]) โ€” spawn request, zero options, no notes. ๐ŸŽ€

spawn_request(Node, Fun, Options) -> ReqId

Types:

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

Same as spawn_request(Node,erlang,apply,[Fun,[]],Options) โ€” so it's a spawn request that uses the zero-arity fun Fun as the entry point. Basically "just run this fun over there please". ๐Ÿซถ

This function will fail with a badarg exception if:

  • Node is not an atom.
  • Fun is not a fun of arity zero.
  • Options is not a proper list of terms.

spawn_request(Module, Function, Args) -> ReqId

Types:

Module = module()
Function = atom()
Args = [term()]
ReqId = reference()

Same as calling spawn_request(node(),Module,Function,Args,[]) โ€” local node, no options, keep it simple. ๐Ÿ’…

spawn_request(Node, Module, Function, Args) -> ReqId

Types:

Node = node()
Module = module()
Function = atom()
Args = [term()]
ReqId = reference()

Same as spawn_request(Node,Module,Function,Args,[]) โ€” spawn request, no options, that's it. โœจ

spawn_request(Module, Function, Args, Options) -> ReqId

Types:

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

Same as calling spawn_request(node(),Module,Function,Args,Options) โ€” spawn request, but staying on the local node. ๐Ÿก

spawn_request(Node, Module, Function, Args, Options) -> ReqId

Types:

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

Okay bestie, this is the main character of the whole page โ€” asynchronously send a spawn request, and get back a request identifier ReqId. ๐Ÿ”ฅ

If the spawn operation succeeds, a new process gets created on the node identified by Node. When a spawn operation succeeds, the caller will by default be sent a message on the form {ReplyTag, ReqId, ok, Pid} where Pid is the process identifier of the newly created process. That message is what we call a success message for the rest of this text, mwah. ReplyTag is by default the atom spawn_reply unless you changed it with the {reply_tag, ReplyTag} option. The new process is started by the application of Module:Function to Args. ๐Ÿงš

The spawn operation fails either if creation of a new process failed, or if the spawn operation was 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 โ€” and that one is an error message, jsyk. Currently the following spawn error Reasons are defined, but no cap: other reasons can appear at any time without prior notice: ๐Ÿ’€

  • badopt โ€” an invalid Option was passed as argument. Note that different runtime systems may support different options.
  • notsup โ€” the node identified by Node does not support spawn operations issued by spawn_request().
  • noconnection โ€” failure to set up a connection to the node identified by Node, or the connection to that node was lost during the spawn operation. In the case the connection was lost, a process may or may not have been created. ๐Ÿ™ˆ
  • system_limit โ€” could not create a new process due to that some system limit was reached. Typically the process table was full.

Valid Options:

  • monitor โ€” in the absence of spawn operation failures, atomically sets up a monitor to the newly created process. That is, as if the calling process had called monitor(process, Pid) where Pid is the process identifier of the newly created process. The ReqId returned by spawn_request() is also used as monitor reference as if it was returned from monitor(process, Pid).

The monitor will not be activated for the calling process until the spawn operation has succeeded. The monitor can not be demonitored 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. 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, as if the calling process had called monitor(process, Pid, MonitorOpts) where Pid is the process identifier of the newly created process. See the monitor option 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, in the case that an alias is created using the monitor option, the alias will not be active until the monitor is activated.

  • link โ€” in absence of spawn operation failures, atomically sets up a link between the calling process and the newly created process. That is, as if the calling process had called link(Pid) where Pid is the process identifier of the newly created process.

The link will not be activated for the calling process until the spawn operation has succeeded. 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. If the spawn operation fails, no exit signal due to the link will be delivered to the caller of spawn_request().

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} โ€” valid Reply values:
    • yes โ€” a spawn reply message will be sent to the caller regardless of whether the operation succeeds or not. If the call to spawn_request() returns without raising an exception and the reply option is set to yes, the caller is guaranteed to be delivered either a success message or an error message. The reply option is by default set to yes. โœ…
    • 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 to ReplyTag in 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 atom spawn_reply. ๐Ÿท๏ธ
  • OtherOption โ€” other valid options depends on what options are supported by the node identified by Node. A description of other valid Options for the local node of current OTP version can be found in the documentation of spawn_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. Ordering slay. ๐Ÿ’…

This function will fail with a badarg exception if:

  • Node is not an atom.
  • Module is not an atom.
  • Function is not an atom.
  • Args is not a proper list of terms.
  • Options is not a proper list of terms.

okay so continuing where we left off, and this is the โœจfine-print eraโœจ of spawn_request, bestie, so pay attention:

not every individual Options gets checked at the moment the spawn request is sent. some of them can only be checked when the request is received. so an invalid option won't throw a badarg exception at you โ€” instead the spawn operation just fails with an error reason of badopt. lowkey rude but that's the deal. ๐Ÿ’…

and psst โ€” a spawn request can always be abandoned by calling spawn_request_abandon/1. keep that in your back pocket.

spawn_request_abandon(ReqId :: reference()) -> boolean()

Abandon a spawn request you already issued. ReqId is a request identifier that spawn_request() handed back to you earlier, in a call from the current process. translation: only the process that made the request can abandon it. no delegating, bestie. ๐Ÿ™…โ€โ™€๏ธ

You can only successfully abandon a request until the spawn request has completed. once it's successfully abandoned, you as the caller will not be affected by future direct effects of the spawn request itself โ€” like, for example, you will not get a spawn reply message. ๐ŸŽ€

but heads up: the request is not withdrawn, so a new process may or may not still get created because of it. if a new process does get created after you abandoned, then no monitors and no links get set up to the caller of spawn_request_abandon/1 because of that spawn request. and if the spawn request included the link option, the process created due to the request will be sent an exit signal from its parent with the exit reason abandoned when the system detects that the spawn operation has succeeded. ๐Ÿ˜ญ

Note: a process created due to a spawn request that's been abandoned may still communicate with its parent like any other process. the only thing abandoning cancels is the direct effects on the parent of the actual spawn request. that's it. don't expect radio silence. ๐Ÿซถ

Return values, let's go:

  • true โ€” the spawn request was successfully abandoned. slay. โœจ
  • false โ€” no spawn request was abandoned. the ReqId request identifier didn't correspond to an outstanding spawn request issued by the calling process. the reason is either:
    • ReqId corresponds to a spawn request previously made by the calling process, but 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.
    • ReqId doesn't correspond to a spawn request that's been made by the calling process at all. ๐Ÿ’€

This function fails with a badarg exception if ReqId is not a reference.


split_binary(Bin, Pos) -> {binary(), binary()}

Types:

Bin = binary()
Pos = integer() >= 0
  0..byte_size(Bin)

Returns a tuple with the two binaries you get from splitting Bin into two parts at position Pos. not destructive, okay? nobody's getting hurt here. after the operation there are three binaries altogether. iconic behaviour, honestly. ๐Ÿฆ‹

Example:

> B = list_to_binary("0123456789").
<<"0123456789">>
> byte_size(B).
10
> {B1, B2} = split_binary(B,3).
{<<"012">>,<<"3456789">>}
> byte_size(B1).
3
> byte_size(B2).
7

erlang:start_timer(Time, Dest, Msg) -> TimerRef

Types:

Time = integer() >= 0
Dest = pid() | atom()
Msg = term()
TimerRef = reference()

Starts a timer. literally the same as calling erlang:start_timer(Time, Dest, Msg, []). no cap. ๐Ÿงš

erlang:start_timer(Time, Dest, Msg, Options) -> TimerRef

Types:

Time = integer()
Dest = pid() | atom()
Msg = term()
Options = [Option]
Abs = boolean()
Option = {abs, Abs}
TimerRef = reference()

Starts a timer. when it expires, the message {timeout, TimerRef, Msg} gets sent to the process identified by Dest. ๐ŸŽ€

Options:

  • {abs, false} โ€” this is the default. it means the Time value is interpreted as a time in milliseconds relative to the current Erlang monotonic time.
  • {abs, true} โ€” absolute Time value. the Time value is interpreted as an absolute Erlang monotonic time in milliseconds.

More options can be added in the future, so don't get too comfy. ๐Ÿ™ˆ

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. periodt. ๐Ÿ’…

If Dest is a pid(), it must be a pid() of a process created on the current runtime system instance. that process may have terminated or not, either way. if Dest is an atom(), it's interpreted as the name of a locally registered process, and the process referred to by that name is looked up at the time of timer expiration. no error gets returned if the name doesn't refer to a process. so like, chill, it's fine. ๐Ÿ˜Œ

If Dest is a pid(), the timer is automatically canceled if the process referred to by the pid() isn't alive, or if the process exits. this feature was introduced in ERTS 5.4.11 โ€” vintage. โญ but notice!! timers are not automatically canceled when Dest is an atom().

See also erlang:send_after/4, erlang:cancel_timer/2, and erlang:read_timer/2.

Failure: badarg if the arguments don't satisfy the requirements specified here.


statistics(Item :: active_tasks) -> [ActiveTasks]

Types:

ActiveTasks = integer() >= 0

Returns the same as statistics(active_tasks_all) โ€” with one exception: no information about the dirty IO run queue and its associated schedulers is part of the result. so only tasks that are expected to be CPU bound show up. ๐Ÿ”ฅ

statistics(Item :: active_tasks_all) -> [ActiveTasks]

Types:

ActiveTasks = integer() >= 0

Returns a list where each element represents the number of active processes and ports on each run queue and its associated schedulers. like, the number of processes and ports that are ready to run, or are currently running. ๐Ÿ’œ

Values for normal run queues and their associated schedulers come first in the resulting list. the first element corresponds to scheduler number 1 and so on. if support for dirty schedulers exists, an element with the value for the dirty CPU run queue and its associated dirty CPU schedulers follows, and then as the last element comes the value for the dirty IO run queue and its associated dirty IO schedulers. ๐Ÿฆ‹

and ngl, the information is not gathered atomically. so the result isn't necessarily a consistent snapshot of the state โ€” it's just gathered quite efficiently. vibes over precision, i guess.

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 we've got multiple normal run queues, one dirty CPU run queue, and 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. this has to be taken into account when evaluating the result. iykyk. ๐Ÿง 

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

statistics(Item :: context_switches) -> {ContextSwitches, 0}

Types:

ContextSwitches = integer() >= 0

Returns the total number of context switches since the system started. the 0 is just there vibing, honestly. ๐Ÿ’€

statistics(Item :: exact_reductions) -> {Total_Exact_Reductions, Exact_Reductions_Since_Last_Call}

Types:

Total_Exact_Reductions = Exact_Reductions_Since_Last_Call =
integer() >= 0

Returns the number of exact reductions. โœจ

Note: statistics(exact_reductions) is a more expensive operation than statistics(reductions). your wallet (and your runtime) will feel it. ๐Ÿ˜ญ

statistics(Item :: garbage_collection) -> {Number_of_GCs, Words_Reclaimed, 0}

Types:

Number_of_GCs = Words_Reclaimed = integer() >= 0

Returns information about garbage collection, for example:

> statistics(garbage_collection).
{85,23961,0}

This information can be invalid for some implementations. so like, don't build your whole personality on it. ๐Ÿ™ˆ

statistics(Item :: io) -> {{input, Input}, {output, Output}}

Types:

Input = Output = integer() >= 0

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(Item :: microstate_accounting) -> [MSAcc_Thread] | undefined

Types:

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 = integer() >= 0
MSAcc_Counters = #{MSAcc_Thread_State => integer() >= 0}
MSAcc_Thread_State =
    alloc | aux | bif | busy_wait | check_io | emulator | ets |
    gc | gc_fullsweep | nif | other | port | send | sleep | timers

Microstate accounting can be used to measure 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 it's enabled. it's meant to be a profiling tool to help you find performance bottlenecks โ€” like a little detective for your perf problems. ๐Ÿ•ต๏ธโ€โ™€๏ธ

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 within ERTS. each map contains type and id fields that identify what thread it is, plus a counters field with data about how much time has been spent in the various states. ๐Ÿ‘‘

Example:

okay so when you actually run it, the output is giving:

> 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 as returned by os:perf_counter/0. 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. This is because of various optimisation done to keep the overhead as small as possible. Lowkey important, bestie. ๐Ÿ’…

The thread types (MSAcc_Thread_Types) are these:

  • scheduler โ€” The main execution threads that do most of the work. See erl +S for more details.
  • dirty_cpu_scheduler โ€” The threads for long running cpu intensive work. See erl +SDcpu for more details.
  • dirty_io_scheduler โ€” The threads for long running I/O work. See erl +SDio for more details.
  • async โ€” Async threads are used by various linked-in drivers (mainly the file drivers) to offload non-CPU intensive work. See erl +A for more details.
  • aux โ€” Takes care of any work that is not specifically assigned to a scheduler.
  • poll โ€” Does the IO polling for the emulator. See erl +IOt for more details.

The following MSAcc_Thread_States are available. All states are exclusive, meaning that a thread cannot be in two states at once. So, if you add the numbers of all counters in a thread, you get the total runtime for that thread. Math slay โœจ

  • 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.
  • port โ€” Time spent executing ports.
  • sleep โ€” Time spent sleeping.

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. fr fr, that tradeoff is real.

  • 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 the emulator state.
  • busy_wait โ€” Time spent busy waiting. This is also the state where a scheduler no longer reports that it is active when using statistics(scheduler_wall_time). So, if you add all other states but this and sleep, and then divide that by all time in the thread, you should get something very similar to the scheduler_wall_time fraction. Without extra states this time is part of the other state.
  • ets โ€” Time spent executing ETS BIFs. Without extra states this time is part of the emulator state.
  • gc_full โ€” Time spent doing fullsweep garbage collection. Without extra states this time is part of the gc state.
  • nif โ€” Time spent in NIFs. Without extra states this time is part of the emulator state.
  • send โ€” Time spent sending messages (processes only). Without extra states this time is part of the emulator state.
  • timers โ€” Time spent managing timers. Without extra states this time is part of the other state.

The utility module msacc(3erl) can be used to more easily analyse these statistics. iconic helper module behavior tbh ๐Ÿซถ

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.

Note: The threads and states are subject to change without any prior notice. So donโ€™t get too attached, bestie. ๐Ÿ˜ญ

statistics(Item :: reductions) -> {Total_Reductions, Reductions_Since_Last_Call}

Types:

  • Total_Reductions = Reductions_Since_Last_Call = integer() >= 0

Returns information about reductions, for example:

> statistics(reductions).
{2046,11}
Note: 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).

statistics(Item :: run_queue) -> integer() >= 0

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. expensive little snapshot, but itโ€™s honest. ๐Ÿ’ธ


statistics(Item :: run_queue_lengths) -> [RunQueueLength]

Types:

  • RunQueueLength = integer() >= 0

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.


statistics(Item :: run_queue_lengths_all) -> [RunQueueLength]

Types:

  • RunQueueLength = integer() >= 0

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.

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), statistics(total_active_tasks), and statistics(total_active_tasks_all).


statistics(Item :: runtime) -> {Total_Run_Time, Time_Since_Last_Call}

Types:

  • Total_Run_Time = Time_Since_Last_Call = integer() >= 0

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.

Warning: This value might wrap due to limitations in the underlying functionality provided by the operating system that is used. so yeah, wrap watch is a thing. ๐Ÿ’€

Example:

> statistics(runtime).
{1690,1620}

statistics(Item :: scheduler_wall_time) -> [{SchedulerId, ActiveTime, TotalTime}] | undefined

Types:

  • SchedulerId = integer() >= 1
  • ActiveTime = TotalTime = integer() >= 0

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.

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. main character scheduler energy, honestly. ๐Ÿ‘‘

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.

So if it's enabled, this function hands you a list of tuples shaped like {SchedulerId, ActiveTime, TotalTime} โ€” where SchedulerId is an integer ID of the scheduler, ActiveTime is how long that scheduler has been busy, and TotalTime is the total time duration since scheduler_wall_time got activated for that specific scheduler. Heads up tho: the time unit it returns is undefined and can literally change between releases, OSs, and system restarts ๐Ÿ˜ญ. That's why scheduler_wall_time is only to be used to calculate relative values for scheduler utilization. Also, ActiveTime can never exceed TotalTime, bestie โ€” that's the one guarantee. And the list of scheduler info is unsorted and can appear in a different order between calls (so don't you dare assume ordering ๐Ÿ’…).

When it's disabled, this function returns undefined.

The activation time can differ significantly between schedulers, ngl. Currently, dirty schedulers are activated at system start while normal schedulers are activated some time after the scheduler_wall_time functionality is enabled.

Only info about schedulers that are expected to handle CPU bound work is included in what this function returns. If you also want info 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).

Note: the different types of schedulers handle specific types of jobs. Every job is assigned to a specific scheduler type. Jobs can migrate between different schedulers of the same type, but never between schedulers of different types. This fact has to be taken under consideration when evaluating the result returned. Keep that in mind, okay? ๐Ÿ‘‘

You can use scheduler_wall_time to calculate scheduler utilization. First you take 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. Slay. โœจ

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 ๐Ÿ’€ (yes really, don't come for me, that's just how it is).

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_time is by default disabled. To enable it, use erlang:system_flag(scheduler_wall_time, true). Don't forget or you'll get undefined and be sad. ๐Ÿ˜ญ

๐Ÿ’– statistics(Item :: scheduler_wall_time_all) -> [{SchedulerId, ActiveTime, TotalTime}] | undefined

Types:

SchedulerId = integer() >= 1
ActiveTime = TotalTime = integer() >= 0

The same as statistics(scheduler_wall_time), except that it also includes info 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: work executing on dirty I/O schedulers is 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-read those numbers, bestie ๐Ÿซถ.

๐ŸŒธ statistics(Item :: total_active_tasks) -> ActiveTasks

Types:

ActiveTasks = integer() >= 0

The same as calling lists:sum(statistics(active_tasks)), but more efficient. Lowkey the glow-up version. โœจ


๐ŸŒธ statistics(Item :: total_active_tasks_all) -> ActiveTasks

Types:

ActiveTasks = integer() >= 0

The same as calling lists:sum(statistics(active_tasks_all)), but more efficient. Same vibe, all the dirty schedulers included. ๐Ÿ’…


๐Ÿฆ‹ statistics(Item :: total_run_queue_lengths) -> TotalRunQueueLengths

Types:

TotalRunQueueLengths = integer() >= 0

The same as calling lists:sum(statistics(run_queue_lengths)), but more efficient. Yes queen, skip the manual summing. ๐Ÿ‘‘


๐Ÿฆ‹ statistics(Item :: total_run_queue_lengths_all) -> TotalRunQueueLengths

Types:

TotalRunQueueLengths = integer() >= 0

The same as calling lists:sum(statistics(run_queue_lengths_all)), but more efficient. It's giving convenience, fr fr. ๐Ÿ’œ


โญ statistics(Item :: wall_clock) -> {Total_Wallclock_Time, Wallclock_Time_Since_Last_Call}

Types:

Total_Wallclock_Time = Wallclock_Time_Since_Last_Call = integer() >= 0

Returns info 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. Iconic distinction, don't mix them up ๐Ÿ˜Œ.


๐ŸŽ€ erlang:suspend_process(Suspendee) -> true

Types:

Suspendee = pid()

Suspends the process identified by Suspendee. The same as calling erlang:suspend_process(Suspendee, []).

Warning: this BIF is intended for debugging only. It's not a vibe you should build your app on, okay? ๐Ÿ’€

๐Ÿงš erlang:suspend_process(Suspendee, OptList) -> boolean()

Types:

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 isn't already in that state. A suspended process is not scheduled for execution until the process has been resumed. It's literally just paused. โธ๏ธ

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. Tracking this is a whole thing, but it's handled. ๐Ÿซถ

Options (Opts):

  • asynchronous โ€” a suspend request is sent to the process identified by Suspendee. Suspendee eventually suspends unless it is resumed before it could suspend. The caller of erlang:suspend_process/2 returns immediately, regardless of whether Suspendee has suspended yet or not. The point in time when Suspendee suspends cannot be deduced from other events in the system. It is only guaranteed that Suspendee eventually suspends (unless it is resumed). If no asynchronous options has been passed, the caller of erlang:suspend_process/2 is blocked until Suspendee has suspended.
  • {asynchronous, ReplyTag} โ€” a suspend request is sent to the process identified by Suspendee. 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} where State is either:
    • exited โ€” Suspendee has exited.
    • suspended โ€” Suspendee is now suspended.
    • not_suspended โ€” Suspendee is not suspended. This can only happen when the process that issued this request have called resume_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 by Suspendee is suspended unless the calling process already is suspending Suspendee. If unless_suspending is combined with option asynchronous, a suspend request is sent unless the calling process already is suspending Suspendee or if a suspend request already has been sent and is in transit. If the calling process already is suspending Suspendee, or if combined with option asynchronous and a send request already is in transit, false is returned and the suspend count on Suspendee remains unchanged.

If the suspend count on the process identified by Suspendee is increased, true is returned, otherwise false. Simple as that. ๐Ÿ’…

Warning: this BIF is intended for debugging only. Say it with me: 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?? This is the dangerous part, no cap. ๐Ÿ’€

Failures:

  • badarg โ€” if Suspendee is not a process identifier.

  • badarg: if the process identified by Suspendee is literally the same process as the one calling erlang:suspend_process/2. bestie you cannot suspend yourself, that's not the vibe ๐Ÿ’€
  • badarg: if the process identified by Suspendee is not alive.
  • badarg: if the process identified by Suspendee resides on another node. no long-distance suspending, sorry ๐Ÿซถ
  • badarg: if OptList is not a proper list of valid Opts.
  • system_limit: if the process identified by Suspendee has been suspended more times by the calling process than can be represented by the currently used internal data structures. the system limit is greater than 2,000,000,000 suspends and will never be lower. like, ever. ๐Ÿ˜ญ

erlang:system_flag(Flag :: backtrace_depth, Depth) -> OldDepth โœจ

Types:

Depth = OldDepth = integer() >= 0

Sets the maximum depth of call stack back-traces in the exit reason element of 'EXIT' tuples. this flag also limits the stacktrace depth returned by the process_info item current_stacktrace. ๐Ÿ”ฅ

Returns the old value of the flag.


erlang:system_flag(Flag :: cpu_topology, CpuTopology) -> OldCpuTopology ๐Ÿฆ‹

Types:

CpuTopology = OldCpuTopology = cpu_topology()
cpu_topology() = [LevelEntry :: level_entry()] | undefined
level_entry() =
    {LevelTag :: level_tag(), SubLevel :: sub_level()} |
    {LevelTag :: level_tag(),
     InfoList :: info_list(),
     SubLevel :: sub_level()}
level_tag() = core | node | processor | thread
sub_level() =
    [LevelEntry :: level_entry()] |
    (LogicalCpuId :: {logical, integer() >= 0})
info_list() = []
โš ๏ธ Warning: this argument is deprecated, bestie. instead of using this argument, use command-line argument +sct in erl(1). when this argument is removed, a final CPU topology to use is determined at emulator boot time.

Sets the user-defined CpuTopology. the user-defined CPU topology overrides any automatically detected CPU topology. by passing undefined as CpuTopology, the system reverts to the CPU topology automatically detected. the returned value equals the value returned from erlang:system_info(cpu_topology) before the change was made.

Returns the old value of the flag.

The CPU topology is used when binding schedulers to logical processors. if schedulers are already bound when the CPU topology is changed, the schedulers are sent a request to rebind according to the new CPU topology. ๐Ÿ’…

The user-defined CPU topology can also be set by passing command-line argument +sct to erl(1).

For info on the type CpuTopology and more, see erlang:system_info(cpu_topology) as well as command-line flags +sct and +sbt in erl(1).


erlang:system_flag(Flag :: dirty_cpu_schedulers_online, DirtyCPUSchedulersOnline) -> OldDirtyCPUSchedulersOnline ๐Ÿ”ฅ

Types:

DirtyCPUSchedulersOnline = OldDirtyCPUSchedulersOnline =
integer() >= 1

Sets the number of dirty CPU schedulers 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.

The number of dirty CPU schedulers online can change if the number of schedulers online changes. 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. math is mathing ๐Ÿ“

For more info, see erlang:system_info(dirty_cpu_schedulers) and erlang:system_info(dirty_cpu_schedulers_online).


erlang:system_flag(Flag :: erts_alloc, Value :: {Alloc, F, V}) -> ok | notsup ๐ŸŽ€

Types:

Alloc = F = atom()
V = integer()

Sets system flags for erts_alloc(3erl). Alloc is the allocator to affect, for example binary_alloc. F is the flag to change and V is the new value.

Only a subset of all erts_alloc flags can be changed at run time. this subset is currently only the flag sbct. ๐Ÿ‘‘

Returns ok if the flag was set or notsup if not supported by erts_alloc.


erlang:system_flag(Flag :: fullsweep_after, Number) -> OldNumber ๐ŸŒธ

Types:

Number = OldNumber = integer() >= 0

Sets system flag fullsweep_after. Number is a non-negative integer indicating how many times generational garbage collections can be done without forcing a fullsweep collection. the value applies to new processes, while processes already running are not affected.

Returns the old value of the flag.

In low-memory systems (especially without virtual memory), setting the value to 0 can help to conserve memory. ๐Ÿซถ

This value can also be set through (OS) environment variable ERL_FULLSWEEP_AFTER.


erlang:system_flag(Flag :: microstate_accounting, Action) -> OldState ๐Ÿงš

Types:

Action = true | false | reset
OldState = true | false

Turns on/off microstate accounting measurements. when passing reset, all counters are reset to 0. fresh start energy โœจ

For more info see statistics(microstate_accounting).


erlang:system_flag(Flag :: min_heap_size, MinHeapSize) -> OldMinHeapSize ๐Ÿ’œ

Types:

MinHeapSize = OldMinHeapSize = integer() >= 0

Sets the default minimum heap size for processes. the size is specified in words. the new min_heap_size effects only processes spawned after the change of min_heap_size has been made. min_heap_size can be set for individual processes by using spawn_opt/4 or process_flag/2.

Returns the old value of the flag.


erlang:system_flag(Flag :: min_bin_vheap_size, MinBinVHeapSize) -> OldMinBinVHeapSize ๐Ÿ“

Types:

MinBinVHeapSize = OldMinBinVHeapSize = integer() >= 0

Sets the default minimum binary virtual heap size for processes. the size is specified in words. the new min_bin_vhheap_size effects only processes spawned after the change of min_bin_vheap_size has been made. 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.


erlang:system_flag(Flag :: max_heap_size, MaxHeapSize) -> OldMaxHeapSize ๐ŸŒˆ

Types:

MaxHeapSize = OldMaxHeapSize = max_heap_size()
max_heap_size() =
    integer() >= 0 |
    #{size => integer() >= 0,
      kill => boolean(),
      error_logger => boolean()}

Sets the default maximum heap size settings for processes. the size is specified in words. the new max_heap_size effects only processes spawned efter the change has been made. 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. ๐Ÿ“š


erlang:system_flag(Flag :: multi_scheduling, BlockState) -> OldBlockState โญ

Types:

BlockState = block | unblock | block_normal | unblock_normal
OldBlockState = blocked | disabled | enabled

If multi-scheduling is enabled, more than one scheduler thread is used by the emulator. multi-scheduling can be blocked in two different ways. either all schedulers but one is blocked, or all normal schedulers but one is blocked. when only normal schedulers are blocked, dirty schedulers are free to continue to schedule processes. ๐Ÿ˜ค

If BlockState =:= block, multi-scheduling is blocked. that is, one and only one scheduler thread will execute. if BlockState =:= unblock and no one else blocks multi-scheduling, and this process has blocked only once, multi-scheduling is unblocked.

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. 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. 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. so like, it cleans up after itself ๐Ÿซถ

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. seriously bestie, think about it again. ๐Ÿ˜ญ

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


erlang:system_flag(Flag :: outstanding_system_requests_limit, NewLimit) -> OldLimit ๐Ÿ’ซ

Types:

NewLimit = OldLimit = 1..134217727

okay so this one sets a cap on the amount of outstanding requests a system process is allowed to have while it's out here orchestrating system-wide changes โ€” and rn there are literally two such processes, bestie:

  • The Code Purger โ€” this one orchestrates checking of references to old code before old code gets removed from the system. no cap, that's its whole job.
  • The Literal Area Collector โ€” this one orchestrates copying of references from old literal areas before those areas get removed from the system.

Each of these processes is allowed to have as many outstanding requests as the limit is set to. The default? Twice the amount of schedulers on the system. ๐Ÿ’… why? because that ensures schedulers will have enough work scheduled to perform these operations as quickly as possible while other work is interleaved in with it. iconic behavior. You can check the currently used limit 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.


erlang:system_flag(Flag :: scheduler_bind_type, How) -> OldBindType

Types:

How = scheduler_bind_type() | default_bind
OldBindType = 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
โš ๏ธ Warning: this argument is deprecated! Instead of using it, use the command-line argument +sbt in erl(1). And when this argument gets removed (it will, bestie), a final scheduler bind type to use is determined at emulator boot time. so like, plan accordingly ๐Ÿซถ

Controls if and how schedulers are bound to logical processors.

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, because it's not always possible to verify valid logical processor identifiers. If an error is reported, an error event is logged. To verify that the schedulers actually 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 info on how to define the CPU topology, see command-line flag +sct in erl(1).

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

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 u in erl(1).
  • no_spread โ€” same as command-line argument +sbt ns in erl(1).
  • thread_spread โ€” same as command-line argument +sbt ts in erl(1).
  • processor_spread โ€” same as command-line argument +sbt ps in erl(1).
  • spread โ€” same as command-line argument +sbt s in erl(1).
  • no_node_thread_spread โ€” same as command-line argument +sbt nnts in erl(1).
  • no_node_processor_spread โ€” same as command-line argument +sbt nnps in erl(1).
  • thread_no_node_processor_spread โ€” same as command-line argument +sbt tnnps in erl(1).
  • default_bind โ€” same as command-line argument +sbt db in erl(1).

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 command-line argument +sbt to erl(1).

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


erlang:system_flag(Flag :: scheduler_wall_time, Boolean) -> OldBoolean

Types:

Boolean = OldBoolean = boolean()

Try to enable or disable scheduler wall time measurements by passing Boolean as either true or false. slay.

For more info 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. So to ensure scheduler_wall_time is kept enabled, the process that enabled it must therefore be kept alive. ๐Ÿซถ lowkey important.

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


erlang:system_flag(Flag :: schedulers_online, SchedulersOnline) -> OldSchedulersOnline

Types:

SchedulersOnline = OldSchedulersOnline = integer() >= 1

Sets the number of schedulers online. Range is 1 <= 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. math is mathing ๐Ÿ”ฅ

For more information, see erlang:system_info(schedulers) and erlang:system_info(schedulers_online).


erlang:system_flag(Flag :: system_logger, Logger) -> PrevLogger

Types:

Logger = PrevLogger = logger | undefined | pid()

Sets the process that will receive the logging messages generated by ERTS. If set to undefined, 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() }

If the system_logger process dies, this flag will be reset 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. iykyk.

erlang:system_flag(Flag :: trace_control_word, TCW) -> OldTCW

Types:

TCW = OldTCW = integer() >= 0

Sets the value of the node trace control word to TCW, which is to be an unsigned integer. For more information, see function set_tcw in section "Match Specifications in Erlang" in the User's Guide.

Returns the old value of the flag. ๐ŸŽ€


erlang:system_flag(Flag :: time_offset, Value :: finalize) -> OldState

Types:

OldState = 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 preliminary is returned, finalization was performed and the time offset is now final.
  • If final is returned, the time offset was already in the final state. This either because another erlang:system_flag(time_offset, finalize) call or because no time warp mode is used.
  • If volatile is returned, the time offset cannot be finalized because multi-time warp mode is used.

erlang:system_info(Item :: update_cpu_info) -> changed | unchanged

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

okay so here are the rest of the system_info item groups, bestie โ€” sorted by vibe:

  • 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, compat_rel, debug_compiled, driver_version, dynamic_trace, dynamic_trace_probes, 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

and now we get into the allocator lore ๐Ÿ’…๐Ÿซถ

erlang:system_info(Item :: allocated_areas) -> [tuple()]

erlang:system_info(Item :: allocator) ->
                      {Allocator, Version, Features, Settings}

erlang:system_info(Item :: {allocator, Alloc}) -> [term()]

erlang:system_info(Item :: alloc_util_allocators) -> [Alloc]

erlang:system_info(Item :: {allocator_sizes, Alloc}) -> [term()]

Types:

Allocator = undefined | glibc
Version = [integer() >= 0]
Features = [atom()]
Settings =
    [{Subsystem :: atom(),
      [{Parameter :: atom(), Value :: term()}]}]
Alloc = atom()

Returns various information about the memory allocators of the current system (emulator), as specified by Item:

  • allocated_areas: Returns a list of tuples 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.

Notice that the sum of these values is not the total amount of memory allocated by the emulator. Some values are part of other values, and some memory areas are not part of the result. For information about the total amount of memory allocated by the emulator, see erlang:memory/0,1.

  • allocator: Returns {Allocator, Version, Features, Settings, where: โ€” yes, the manpage really leaves it hanging like that, we're keeping it exactly โ€” and here's what the pieces mean:
    • Allocator corresponds to the malloc() implementation used. If Allocator equals undefined, the malloc() implementation used cannot be identified. glibc can be identified.
    • Version is a list of integers (but not a string) representing the version of the malloc() implementation used.
    • Features is a list of atoms representing the allocation features used.
    • Settings is a list of subsystems, their configurable parameters, and used values. Settings can differ between different combinations of platforms, allocators, and allocation features. Memory sizes are given in bytes.

See also "System Flags Effecting erts_alloc" in erts_alloc(3erl).

  • {allocator, Alloc}: Returns information about the specified allocator. As from ERTS 5.6.1, the return value is a list of {instance, InstanceNo, InstanceInfo} tuples, where InstanceInfo contains information about a specific instance of the allocator. If Alloc is not a recognized allocator, undefined is returned. If Alloc is disabled, false is returned.

Notice that the information returned is highly implementation-dependent and can be changed or removed at any time without prior notice. It was initially intended as a tool when developing new allocators, but as it can be of interest for others it has been briefly documented.

The recognized allocators are listed in erts_alloc(3erl). Information about super carriers can be obtained from ERTS 8.0 with {allocator, erts_mmap} or from ERTS 5.10.4; the returned list when calling with {allocator, mseg_alloc} also includes an {erts_mmap, _} tuple as one element in the list.

After reading the erts_alloc(3erl) documentation, the returned information more or less speaks for itself, but it can be worth explaining some things. Call counts are presented by two values, the first value is giga calls, and the second value is calls. mbcs and sbcs denote multi-block carriers, and single-block carriers, respectively. Sizes are presented in bytes. When a size is not presented, it is the amount of something. Sizes and amounts are often presented by 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 is the current value. fix_alloc memory block types are presented by two values. The first value is the memory pool size and the second value 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 information, see section The alloc_util framework in erts_alloc(3erl).
  • {allocator_sizes, Alloc}: Returns various size information for the specified allocator. The information returned is a subset of the information returned by erlang:system_info({allocator, Alloc}).

next up: CPU topology, aka the family tree of your cores ๐Ÿงฌโœจ

erlang:system_info(Item :: cpu_topology) -> CpuTopology

erlang:system_info(Item ::
                       {cpu_topology, defined | detected | used}) ->
                      CpuTopology

erlang:system_info(Item ::
                       logical_processors |
                       logical_processors_available |
                       logical_processors_online) ->
                      unknown | integer() >= 1

erlang:system_info(Item :: trace_control_word) ->
                      integer() >= 0

Types:

cpu_topology() = [LevelEntry :: level_entry()] | undefined
   All LevelEntrys of a list must contain the same LevelTag,
  except on the top level where both node and
  processorLevelTags can coexist.
level_entry() =
    {LevelTag :: level_tag(), SubLevel :: sub_level()} |
    {LevelTag :: level_tag(),
     InfoList :: info_list(),
     SubLevel :: sub_level()}
  {LevelTag, SubLevel} == {LevelTag, [], SubLevel}
level_tag() = core | node | processor | thread
   More LevelTags can be introduced in a future release.
sub_level() =
    [LevelEntry :: level_entry()] |
    (LogicalCpuId :: {logical, integer() >= 0})
info_list() = []
   The info_list() can be extended in a future release.

Returns various information about the CPU topology of the current system (emulator), as specified by Item:

  • cpu_topology: Returns the CpuTopology currently used by the emulator. The CPU topology is used when binding schedulers to logical processors. The CPU topology used is the user-defined CPU topology, if such exists, otherwise the automatically detected CPU topology, if such exists. If no CPU topology exists, undefined is returned.

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.

  • {cpu_topology, defined}: Returns the user-defined CpuTopology. For more information, see command-line flag +sct in erl(1) and argument cpu_topology.
  • {cpu_topology, detected}: Returns the automatically detected CpuTopologyy. The emulator detects the CPU topology on some newer Linux, Solaris, FreeBSD, and Windows systems. On Windows system with more than 32 logical processors, the CPU topology is not detected.

For more information, see argument cpu_topology.

  • {cpu_topology, used}: Returns CpuTopology used by the emulator. For more information, see 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 cannot 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 cannot detect the available logical processors. The number of available logical processors is less than or equal to the number of logical processors online.

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 cannot 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 (between 1 and the number of logical processors), or the atom unknown if the emulator cannot detect a quota.

update_cpu_info

The runtime system rereads the CPU information available and updates its internally stored information about the detected CPU topology and the number of logical processors configured, online, available, and cpu quota.

If the CPU information has changed since the last time it was read, the atom changed is returned, otherwise the atom unchanged. If the CPU information has changed, you probably want to adjust the number of schedulers online. You typically want to have as many schedulers online as logical processors available. ๐Ÿ’…


Now we're moving into the process heap defaults zone, bestie. These signatures are exactly the ones listed:

erlang:system_info(Item :: fullsweep_after) ->
                      {fullsweep_after, integer() >= 0}

erlang:system_info(Item :: garbage_collection) ->
                      [{atom(), integer()}]

erlang:system_info(Item :: heap_sizes) -> [integer() >= 0]

erlang:system_info(Item :: heap_type) -> private

erlang:system_info(Item :: max_heap_size) ->
                      {max_heap_size,
                       MaxHeapSize :: max_heap_size()}

erlang:system_info(Item :: message_queue_data) ->
                      message_queue_data()

erlang:system_info(Item :: min_heap_size) ->
                      {min_heap_size,
                       MinHeapSize :: integer() >= 1}

erlang:system_info(Item :: min_bin_vheap_size) ->
                      {min_bin_vheap_size,
                       MinBinVHeapSize :: integer() >= 1}

erlang:system_info(Item :: process_limit) -> integer() >= 1

Types:

message_queue_data() = off_heap | on_heap
max_heap_size() =
    integer() >= 0 |
    #{size => integer() >= 0,
      kill => boolean(),
      error_logger => boolean()}

Returns information 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 information, see garbage_collection described below.

garbage_collection

Returns a list 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 by using erlang:system_flag/2. spawn_opt/2,3,4 can spawn a process that does not use the default settings.

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:

  • 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 and +hmaxel in erl(1). It can also be changed at runtime using erlang:system_flag(max_heap_size, MaxHeapSize). For more details about the max_heap_size process flag, see process_flag(max_heap_size, MaxHeapSize).

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 information, see the documentation of process_flag(message_queue_data, MQD).

min_heap_size

Returns {min_heap_size, MinHeapSize}, where MinHeapSize is the current system-wide minimum heap size for spawned processes.

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.

procs

Returns a binary containing a string of process and port information formatted as in Erlang crash dumps. For more information, see section How to interpret the Erlang crash dumps in the User's Guide.


Next up: system limits. The page lists these signatures right here:

erlang:system_info(Item :: atom_count) -> integer() >= 1

erlang:system_info(Item :: atom_limit) -> integer() >= 1

erlang:system_info(Item :: ets_count) -> integer() >= 1

erlang:system_info(Item :: ets_limit) -> integer() >= 1

erlang:system_info(Item :: port_parallelism) -> boolean()

erlang:system_info(Item :: port_count) -> integer() >= 0

erlang:system_info(Item :: port_limit) -> integer() >= 1

erlang:system_info(Item :: process_count) -> integer() >= 1

Returns information 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.

atom_limit

Returns the maximum number of atoms allowed. This limit can be increased at startup by passing command-line flag +t to erl(1).

ets_count

Returns the number of ETS tables currently existing at the local node.

ets_limit

Returns the limit for number of ETS tables. This limit is partially obsolete and number of tables are only limited by available memory.

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 returned by length(erlang:ports()), but more efficient.

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 command-line flag +Q in erl(1).

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 returned by length(processes()), 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 command-line flag +P in erl(1).


Time to talk time, literally. โฐ These time-ish signatures are listed:

erlang:system_info(Item :: end_time) -> integer() >= 0

erlang:system_info(Item :: os_monotonic_time_source) ->
                      [{atom(), term()}]

erlang:system_info(Item :: os_system_time_source) ->
                      [{atom(), term()}]

erlang:system_info(Item :: smp_support) -> boolean()

erlang:system_info(Item :: thread_pool_size) -> integer() >= 0

erlang:system_info(Item :: time_correction) -> true | false

erlang:system_info(Item :: time_offset) ->
                      preliminary | final | volatile

erlang:system_info(Item :: time_warp_mode) ->
                      no_time_warp | single_time_warp |
                      multi_time_warp

Returns information about the current system (emulator) time as specified by Item:

end_time

The last Erlang monotonic time in native time unit that can be represented internally in the current Erlang runtime system instance. The time between the start time and the end time is at least a quarter of a millennium.

os_monotonic_time_source

Returns a list containing information about the source of OS monotonic time that is used by the runtime system.

If [] is returned, no OS monotonic time is available. The list contains two-tuples with Keys as first element, and Values as second element. 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} โ€” Function is the name of the function used. This tuple always exists if OS monotonic time is available to the runtime system.
  • {clock_id, ClockId} โ€” This tuple only exists if Function can be used with different clocks. ClockId corresponds to the clock identifier used when calling Function.
  • {resolution, OsMonotonicTimeResolution} โ€” Highest possible resolution of current OS monotonic time source as parts per second. If no resolution information can be retrieved from the OS, OsMonotonicTimeResolution is set to the resolution of the time unit of Functions return value. That is, the actual resolution can be lower than OsMonotonicTimeResolution. Notice that the resolution does not say anything about the accuracy or whether the precision aligns with the resolution. You do, however, know that the precision is not better than OsMonotonicTimeResolution. โœจ
  • {extended, Extended} โ€” Extended equals yes if the range of time values has been extended; otherwise Extended equals no. The range must be extended if Function returns values that wrap fast. This typically is the case when the return value is a 32-bit value. ๐Ÿ’…
  • {parallel, Parallel} โ€” Parallel equals yes if Function is called in parallel from multiple threads. If it is not called in parallel, because calls must be serialized, Parallel equals no. no cap.
  • {time, OsMonotonicTime} โ€” OsMonotonicTime equals current OS monotonic time in native time unit. โฑ๏ธ
  • os_system_time_source โ€” Returns a list containing information about the source of OS system time that is used by the runtime system.

The list contains two-tuples with Keys as first element, and Values as second element. 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} โ€” Function is the name of the function used. ๐Ÿซถ
  • {clock_id, ClockId} โ€” Exists only if Function can be used with different clocks. ClockId corresponds to the clock identifier used when calling Function.
  • {resolution, OsSystemTimeResolution} โ€” Highest possible resolution of current OS system time source as parts per second. If no resolution information can be retrieved from the OS, OsSystemTimeResolution is set to the resolution of the time unit of Functions return value. That is, the actual resolution can be lower than OsSystemTimeResolution. Notice that the resolution does not say anything about the accuracy or whether the precision do align with the resolution. You do, however, know that the precision is not better than OsSystemTimeResolution. read that twice, bestie ๐Ÿ’›
  • {parallel, Parallel} โ€” Parallel equals yes if Function is called in parallel from multiple threads. If it is not called in parallel, because calls needs to be serialized, Parallel equals no.
  • {time, OsSystemTime} โ€” OsSystemTime equals current OS system time in native time unit.
  • start_time โ€” The Erlang monotonic time in native time unit at the time when current Erlang runtime system instance started. ๐ŸŽ€

See also erlang:system_info(end_time).

  • time_correction โ€” Returns a boolean value indicating whether time correction is enabled or not. simple, iconic โœจ
  • time_offset โ€” Returns the state of the time offset:
    • 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 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.
  • time_warp_mode โ€” Returns a value identifying the time warp mode that is used:
    • 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. time warp era ๐Ÿ’ซ
  • tolerant_timeofday โ€” Returns 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 is final, and time correction is enabled.

       erlang:system_info(Item :: dirty_cpu_schedulers) ->
                             integer() >= 0

       erlang:system_info(Item :: dirty_cpu_schedulers_online) ->
                             integer() >= 0

       erlang:system_info(Item :: dirty_io_schedulers) ->
                             integer() >= 0

       erlang:system_info(Item :: multi_scheduling) ->
                             disabled | blocked | blocked_normal |
                             enabled

       erlang:system_info(Item :: multi_scheduling_blockers) ->
                             [Pid :: pid()]

       erlang:system_info(Item :: normal_multi_scheduling_blockers) ->
                             [Pid :: pid()]

       erlang:system_info(Item :: procs) -> binary()

       erlang:system_info(Item :: scheduler_bind_type) ->
                             spread | processor_spread | thread_spread |
                             thread_no_node_processor_spread |
                             no_node_processor_spread |
                             no_node_thread_spread | no_spread | unbound

       erlang:system_info(Item :: scheduler_bindings) -> tuple()

       erlang:system_info(Item :: scheduler_id) ->
                             SchedulerId :: integer() >= 1

       erlang:system_info(Item :: schedulers | schedulers_online) ->
                             integer() >= 1

       erlang:system_info(Item :: system_version) -> string()

       erlang:system_info(Item :: threads) -> boolean()

Returns information about schedulers, scheduling and threads in the current system as specified by Item, bestie. ๐Ÿงš

  • dirty_cpu_schedulers โ€” Returns the number of dirty CPU scheduler threads used by the emulator. Dirty CPU schedulers execute CPU-bound native functions, such as 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, 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). boot-time behavior, periodt

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

  • dirty_cpu_schedulers_online โ€” Returns the number of dirty CPU schedulers online. The return value satisfies 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).

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

  • 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. I/O girlies rise ๐ŸŒŠ

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

  • 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. important distinction, don't skip ๐Ÿ‘€
    • 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 of Pids when multi-scheduling is blocked, otherwise the empty list is returned. The Pids in the list represent all the processes currently blocking multi-scheduling. A Pid occurs 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(normal_multi_scheduling_blockers), and erlang:system_info(schedulers).

  • normal_multi_scheduling_blockers โ€” Returns a list of Pids when normal multi-scheduling is blocked (that is, all normal schedulers but one is blocked), otherwise the empty list is returned. The Pids in the list represent all the processes currently blocking normal multi-scheduling. A Pid occurs 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).

  • scheduler_bind_type โ€” spills the tea on how the user asked for schedulers to be bound or not bound โ˜•

Lowkey important caveat, bestie: even if a user requested that schedulers be bound, they can silently have failed to bind ๐Ÿ’€. To actually inspect the scheduler bindings, call erlang:system_info(scheduler_bindings).

Want more deets? See command-line argument +sbt in erl(1) and erlang:system_info(scheduler_bindings).

  • scheduler_bindings โ€” tells you about the scheduler bindings currently in use โœจ

You get back a tuple whose size equals erlang:system_info(schedulers). The tuple elements are integers or the atom unbound. Logical processor identifiers are represented as integers. The Nth element of the tuple equals the current binding for the scheduler whose scheduler identifier equals N. Example era: if the schedulers are bound,

element(erlang:system_info(scheduler_id),
        erlang:system_info(scheduler_bindings))

returns the identifier of the logical processor that the calling process is executing on ๐ŸŽ€

Heads up though: only schedulers online can be bound to logical processors ๐Ÿ‘‘

For more, see command-line argument +sbt in erl(1) and erlang:system_info(schedulers_online).

  • scheduler_id โ€” returns the scheduler ID (SchedulerId) of the scheduler thread that the calling process is executing on ๐ŸŒธ

SchedulerId is a positive integer where 1 <= SchedulerId <= erlang:system_info(schedulers).

See also erlang:system_info(schedulers).

  • schedulers โ€” returns the number of scheduler threads used by the emulator ๐Ÿงš

Scheduler threads online schedules Erlang processes and Erlang ports, and execute Erlang code and Erlang linked-in driver code.

The number of scheduler threads is determined at emulator boot time and cannot be changed later ๐Ÿ˜ญ. However, the number of schedulers online can be changed at any time ๐Ÿ’…

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 โ€” returns 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 โ€” returns true ๐Ÿ’–
  • threads โ€” returns true ๐Ÿ’–
  • thread_pool_size โ€” returns 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.


erlang:system_info(Item :: async_dist) -> boolean()

erlang:system_info(Item :: creation) -> integer()

erlang:system_info(Item :: delayed_node_table_gc) ->
                      infinity | integer() >= 0

erlang:system_info(Item :: dist) -> binary()

erlang:system_info(Item :: dist_buf_busy_limit) ->
                      integer() >= 0

erlang:system_info(Item :: dist_ctrl) ->
                      [{Node :: node(),
                        ControllingEntity :: port() | pid()}]

Returns information about Erlang Distribution in the current system as specified by Item:

  • async_dist โ€” Since: OTP 25.3 ๐ŸŒˆ

Returns the value of the command line argument +pad <boolean> which the runtime system use. This value determines the default async_dist value for newly spawned processes.

  • creation โ€” returns the creation of the local node as an integer ๐Ÿ”ฅ

The creation is changed when a node is restarted. The creation of a node is stored in process identifiers, port identifiers, and references. This makes it (to some extent) possible to distinguish between identifiers from different incarnations of a node. The valid creations are integers in the range 1..3, but this will probably change in a future release. If the node is not alive, 0 is returned.

  • delayed_node_table_gc โ€” returns the amount of time in seconds 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 the command-line flag.

  • dist โ€” returns 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 โ€” returns 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).

  • dist_ctrl โ€” returns a list of tuples {Node, ControllingEntity}, one entry for each 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 the specific node.


erlang:system_info(Item :: c_compiler_used) -> {atom(), term()}

erlang:system_info(Item :: check_io) -> [term()]

erlang:system_info(Item :: compat_rel) -> integer()

erlang:system_info(Item :: debug_compiled) -> boolean()

erlang:system_info(Item :: driver_version) -> string()

erlang:system_info(Item :: dynamic_trace) ->
                      none | dtrace | systemtap

erlang:system_info(Item :: dynamic_trace_probes) -> boolean()

erlang:system_info(Item :: emu_flavor) -> emu | jit

erlang:system_info(Item :: emu_type) ->
                      opt | debug | gcov | valgrind | gprof |
                      lcnt | frmptr

erlang:system_info(Item :: info) -> binary()

erlang:system_info(Item :: kernel_poll) -> boolean()

erlang:system_info(Item :: loaded) -> binary()

erlang:system_info(Item :: machine) -> string()

erlang:system_info(Item :: modified_timing_level) ->
                      integer() | undefined

erlang:system_info(Item :: nif_version) -> string()

erlang:system_info(Item :: otp_release) -> string()

erlang:system_info(Item :: outstanding_system_requests_limit) ->
                      1..134217727

erlang:system_info(Item :: port_parallelism) -> boolean()

erlang:system_info(Item :: system_architecture) -> string()

erlang:system_info(Item :: system_logger) ->
                      logger | undefined | pid()

erlang:system_info(Item :: system_version) -> string()

erlang:system_info(Item :: trace_control_word) ->
                      integer() >= 0

erlang:system_info(Item :: version) -> string()

erlang:system_info(Item ::
                       wordsize |
                       {wordsize, internal} |
                       {wordsize, external}) ->
                      4 | 8

Returns various information about the current system (emulator) as specified by Item:

  • build_type โ€” Deprecated, use emu_type instead ๐Ÿ™ˆ
  • c_compiler_used โ€” returns 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 โ€” returns 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 โ€” no promises on the vibe check beyond that ๐Ÿ’€

  • compat_rel โ€” returns the compatibility mode of the local node as an integer ๐Ÿ•ฐ๏ธ

The integer returned represents the Erlang/OTP release that the current emulator has been set to be backward compatible with. The compatibility mode can be configured at startup by using command-line flag +R in erl(1).

  • debug_compiled โ€” returns true if the emulator has been debug-compiled, otherwise false ๐Ÿ›
  • driver_version โ€” returns a string containing the Erlang driver version used by the runtime system ๐Ÿš—

It has the form "<major ver>.<minor ver>".

  • dynamic_trace โ€” returns 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 dyntrace(3erl) manual page and the README.dtrace/README.systemtap files in the Erlang source code top directory.

  • dynamic_trace_probes โ€” returns a boolean() indicating if dynamic trace probes (dtrace or systemtap) 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).

  • emu_flavor โ€” returns 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 ๐Ÿ‘€

  • emu_type โ€” gives you an atom telling you what kind of build the runtime system is. Normally it's opt (that's "optimized", bestie, she's built different โœจ). Other possible answers are debug, gcov, valgrind, gprof, and lcnt. Ngl, the possible return values can be added or removed at any time without prior notice, so don't go hardcoding them like it's your whole personality ๐Ÿ’…
  • info โ€” returns a binary holding a string of miscellaneous system info, formatted like it would be in Erlang crash dumps. Want the lore? See section How to interpret the Erlang crash dumps in the User's Guide ๐ŸŽ€
  • kernel_poll โ€” true if the emulator uses some kind of kernel-poll implementation, otherwise false. Simple queen behavior ๐Ÿ’–
  • loaded โ€” returns a binary with a string of loaded module information, formatted as in Erlang crash dumps. Yeah, same deal โ€” see How to interpret the Erlang crash dumps in the User's Guide for the full story ๐Ÿฆ‹
  • machine โ€” returns a string with the Erlang machine name. That's her government name ๐Ÿซถ
  • modified_timing_level โ€” returns the modified timing-level (that's an integer, bestie) if modified timing is enabled, otherwise undefined. Want the tea on modified timing? See command-line flag +T in erl(1) โญ
  • nif_version โ€” returns a string with the version of the Erlang NIF interface that the runtime system is using. It comes in the form "<major ver>.<minor ver>". Slay, versioned ๐ŸŒธ
  • otp_release โ€” returns a string with the OTP release number of the OTP release that the currently executing ERTS application is part of.

So as from Erlang/OTP 17, the OTP release number corresponds to the major OTP version number, okay? And no erlang:system_info() argument gives you the exact OTP version โ€” not a single one, bestie ๐Ÿ˜ญ That's because the exact OTP version is, in the general case, difficult to determine. For more info, see the description of versions in System principles in System Documentation ๐Ÿ“š

  • outstanding_system_requests_limit โ€” returns the limit on the amount of outstanding requests made by a system process orchestrating system wide changes. Want more? See erlang:system_flag(outstanding_system_requests_limit, Limit) ๐Ÿ’…
  • port_parallelism โ€” returns the default port parallelism scheduling hint used. More deets? See command-line argument +spp in erl(1) ๐ŸŒˆ
  • system_architecture โ€” returns a string with the processor and OS architecture that the emulator is built for. She knows her roots ๐Ÿ‘‘
  • system_logger โ€” returns the current system_logger as set by erlang:system_flag(system_logger, _). Iconic, configurable ๐Ÿ”ฅ
  • system_version โ€” returns a string with the version number plus some important properties, like the number of schedulers. Main character stats, honestly ๐Ÿ’œ
  • trace_control_word โ€” returns the value of the node trace control word. Need the details? See function get_tcw in section Match Specifications in Erlang in the User's Guide ๐Ÿงš
  • version โ€” returns a string with the version number of the emulator. Her era, documented โญ
  • wordsize โ€” same as {wordsize, internal}. Literally the same thing, no cap ๐Ÿ™ˆ
  • {wordsize, internal} โ€” returns the size of Erlang term words in bytes as an integer. That means 4 on a 32-bit architecture, and 8 on a 64-bit architecture. Math is math ๐Ÿ’…
  • {wordsize, external} โ€” returns the true word size of the emulator, meaning the size of a pointer. The value comes as an integer in bytes. On a pure 32-bit architecture you get 4. On a 64-bit architecture you get 8. Periodt ๐Ÿ’–

๐Ÿซถ erlang:system_monitor() -> MonSettings

Types:

MonSettings = undefined | {MonitorPid, Options}
MonitorPid = pid()
Options = [system_monitor_option()]
system_monitor_option() =
    busy_port | busy_dist_port |
    {long_gc, integer() >= 0} |
    {long_schedule, integer() >= 0} |
    {large_heap, integer() >= 0}

Returns the current system monitoring settings that were set by erlang:system_monitor/2, as {MonitorPid, Options} โ€” or undefined if there are no settings at all. Heads up though: the order of the options can be different from the one that was set, so don't come for her about ordering ๐Ÿ˜Œ

๐Ÿฆ‹ erlang:system_monitor(Arg) -> MonSettings

Types:

Arg = MonSettings = undefined | {MonitorPid, Options}
MonitorPid = pid()
Options = [system_monitor_option()]
system_monitor_option() =
    busy_port | busy_dist_port |
    {long_gc, integer() >= 0} |
    {long_schedule, integer() >= 0} |
    {large_heap, integer() >= 0}

When you call this with the argument undefined, all system performance monitoring settings get cleared. Bye bestie ๐Ÿ‘‹

And calling the function with {MonitorPid, Options} as the argument is the same as calling erlang:system_monitor(MonitorPid, Options). Same vibe, different font โœจ

It returns the previous system monitor settings just like erlang:system_monitor/0 does.

๐Ÿ’… erlang:system_monitor(MonitorPid, Options) -> MonSettings

Types:

MonitorPid = pid()
Options = [system_monitor_option()]
MonSettings = undefined | {OldMonitorPid, OldOptions}
OldMonitorPid = pid()
OldOptions = [system_monitor_option()]
system_monitor_option() =
    busy_port | busy_dist_port |
    {long_gc, integer() >= 0} |
    {long_schedule, integer() >= 0} |
    {large_heap, integer() >= 0}

Okay so this one sets the system performance monitoring options. MonitorPid is a local process identifier (pid) that receives the system monitor messages. The second argument is a list of monitoring options, and here's the whole menu ๐ŸŽ€

  • {long_gc, Time} โ€” if a garbage collection in the system takes at least Time wall clock milliseconds, a message {monitor, GcPid, long_gc, Info} gets sent to MonitorPid. Here GcPid is the pid that was garbage collected, and Info is a list of two-element tuples describing the result of the garbage collection.

One of those tuples is {timeout, GcTime}, where GcTime is the time for the garbage collection in milliseconds. The other tuples are tagged with heap_size, heap_block_size, stack_size, mbuf_size, old_heap_size, and old_heap_block_size. These tuples get explained in the description of trace message gc_minor_start (see erlang:trace/3). New tuples can be added, and the order of the tuples in the Info list can be changed, at any time without prior notice. So don't get attached to the layout ๐Ÿ’€

  • {long_schedule, Time} โ€” if a process or port in the system runs uninterrupted for at least Time wall clock milliseconds, a message {monitor, PidOrPort, long_schedule, Info} gets sent to MonitorPid. PidOrPort is the process or port that was running. Info is a list of two-element tuples describing the event.

If it's a pid(), the tuples {timeout, Millis}, {in, Location}, and {out, Location} are present, where Location is either an MFA ({Module, Function, Arity}) describing the function where the process was scheduled in/out, or the atom undefined.

If it's a port(), the tuples {timeout, Millis} and {port_op,Op} are present. Op is one of proc_sig, timeout, input, output, event, or dist_cmd, depending on which driver callback was executing.

So proc_sig is an internal operation and is never to appear, while the others represent the corresponding driver callbacks timeout, ready_input, ready_output, event, and outputv (that last one is when the port is used by distribution). The value Millis in the tuple timeout tells you about the uninterrupted execution time of the process or port, which is always equal to or higher than the Time value you supplied when starting the trace. New tuples can be added to the Info list in a future release, and the order of the tuples in the list can be changed at any time without prior notice. Again โ€” build your code to not care, bestie ๐Ÿ™

Lowkey this one is a whole diagnostic tool: it can be used to detect problems with NIFs or drivers that take too long to execute. 1 ms is considered a good maximum time for a driver callback or a NIF. But a time-sharing system is usually to consider everything < 100 ms as "possible" and fairly "normal". Longer schedule times can indicate swapping or a misbehaving NIF/driver though, and misbehaving NIFs and drivers can cause bad resource utilization and bad overall system performance. So like... watch her ๐Ÿ‘€๐Ÿ”ฅ

  • {large_heap, Size} โ€” if a garbage collection in the system results in the allocated size of a heap being at least Size words, a message {monitor, GcPid, large_heap, Info} gets sent to MonitorPid. GcPid and Info are the same as for long_gc earlier, except that the tuple tagged with timeout is not present.

The monitor message is sent if the sum of the sizes of all memory blocks allocated for all heap generations after a garbage collection is equal to or higher than Size.

Important: when a process is killed by max_heap_size, it is killed before the garbage collection is complete and thus no large heap message is sent. So don't sit there waiting for one, she's not coming ๐Ÿ˜ญ
  • busy_port โ€” if a process in the system gets suspended because it sends to a busy port, a message {monitor, SusPid, busy_port, Port} gets sent to MonitorPid. SusPid is the pid that got suspended when sending to Port. Caught in 4K ๐Ÿ“ธ
  • busy_dist_port โ€” if a process in the system gets suspended because it sends to a process on a remote node whose inter-node communication was handled by a busy port, a message {monitor, SusPid, busy_dist_port, Port} gets sent to MonitorPid. SusPid is the pid that got suspended when sending through the inter-node communication port Port. Distributed queen problems ๐Ÿ’…

Returns the previous system monitor settings just like erlang:system_monitor/0 does.

Okay so real talk about system_monitor/2 for a sec โ€” the arguments you pass in specify how all system monitoring on the node should be done, not how it should be changed, if that makes sense. Which means only one process at a time (MonitorPid) can be the receiver of system monitor messages. And the way you clear a specific monitor option? You just... don't include it in the Options list. That's it. However, all system monitoring will be cleared if the process identified by MonitorPid terminates. ๐Ÿ’…

There are no special option values (like zero) to clear an option, jsyk. 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}. Ngl that's just how it is.

Note: If a monitoring process gets so large that it itself starts to cause system monitor messages when garbage collecting, those 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.

Failures (the "it's giving error" era):

  • badarg โ€” if MonitorPid does not exist.
  • badarg โ€” if MonitorPid is not a local process.

๐Ÿซถ erlang:system_profile() -> ProfilerSettings

Types:

ProfilerSettings = undefined | {ProfilerPid, Options}
ProfilerPid = pid() | port()
Options = [system_profile_option()]
system_profile_option() =
    exclusive | runnable_ports | runnable_procs | scheduler |
    timestamp | monotonic_timestamp | strict_monotonic_timestamp

Returns the current system profiling settings that were set by erlang:system_profile/2, as {ProfilerPid, Options} โ€” or undefined if there are no settings at all. Heads up: the order of the options can be different from the one that was originally set. Slay, but don't trust the order. โœจ

๐ŸŒธ erlang:system_profile(ProfilerPid, Options) -> ProfilerSettings

Types:

ProfilerPid = pid() | port() | undefined
Options = [system_profile_option()]
ProfilerSettings =
    undefined | {pid() | port(), [system_profile_option()]}
system_profile_option() =
    exclusive | runnable_ports | runnable_procs | scheduler |
    timestamp | monotonic_timestamp | strict_monotonic_timestamp

Sets system profiler options. ProfilerPid is a local process identifier (pid) or port receiving the profiling messages, and the receiver is excluded from all profiling (main character privilege, honestly). 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 by erlang: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 to ProfilerPid. 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 to ProfilerPid.
  • scheduler โ€” if a scheduler is put to sleep or awoken, a message, {profile, scheduler, Id, State, NoScheds, Ts}, is sent to ProfilerPid.
  • 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 by erlang:now(). This is also the default if no time stamp flag is specified. If cpu_timestamp has been enabled through erlang:trace/3, this also effects the time stamp produced in profiling messages when flag timestamp is enabled.
Note: erlang:system_profile behavior can change in a future release. Not saying it will, just saying it can. ๐Ÿ‘€

โญ erlang:system_time() -> integer()

Returns 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 really said "I'm fluid bestie". ๐Ÿ˜ญ

๐ŸŽ€ erlang:system_time(Unit) -> integer()

Types:

Unit = time_unit()

Returns current Erlang system time converted into the Unit passed as 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.

๐Ÿฆ‹ term_to_binary(Term) -> ext_binary()

Types:

Term = term()

Returns a binary data object that is the result of encoding Term according to the Erlang external term format.

This can be used for various purposes โ€” for example, writing a term to a file in an efficient way, or sending an Erlang term to some type of communications channel not supported by distributed Erlang. So versatile, we love to see it. ๐Ÿ’–

> Bin = term_to_binary(hello).
<<131,100,0,5,104,101,108,108,111>>
> hello = binary_to_term(Bin).
hello

See also binary_to_term/1.

Note: There is no guarantee that this function will return the same encoded representation for the same term. No cap.

๐ŸŒˆ term_to_binary(Term, Options) -> ext_binary()

Types:

Term = term()
Options =
    [compressed |
     {compressed, Level :: 0..9} |
     deterministic |
     {minor_version, Version :: 0..2}]

Returns a binary data object that is the result of encoding Term according to the Erlang external term format.

If option compressed is provided, the external term format is compressed. The compressed format is automatically recognized by binary_to_term/1 as from Erlang/OTP R7B.

A compression level can be specified by giving option {compressed, Level}. Level is an integer with range 0..9, where:

  • 0 โ€” No compression is done (it is the same as giving no compressed option).
  • 1 โ€” Takes least time but may not compress as well as the higher levels.
  • 6 โ€” Default level when option compressed is provided.
  • 9 โ€” Takes most time and tries to produce a smaller result. Notice "tries" in the preceding sentence; depending on the input term, level 9 compression either does or does not produce a smaller result than level 1 compression. The audacity honestly. ๐Ÿ˜ญ

Option {minor_version, Version} can be used to control some encoding details. This option was introduced in Erlang/OTP R11B-4. The valid values for Version are:

  • 0 โ€” Floats are encoded using a textual representation. This option is useful to ensure that releases before Erlang/OTP R11B-4 can decode the resulting binary.

This version encode atoms that can be represented by a latin1 string using latin1 encoding while only atoms that cannot be represented by latin1 are encoded using utf8.

  • 1 โ€” This is as of Erlang/OTP 17.0 the default. It forces any floats in the term to be 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/1 can decode this representation.

This version encode atoms that can be represented by a latin1 string using latin1 encoding while only atoms that cannot be represented by latin1 are encoded using utf8.

  • 2 โ€” Drops usage of the latin1 atom encoding and unconditionally use utf8 encoding for all atoms. Erlang/OTP systems as of R16B can decode this representation.
Note: In Erlang/OTP 26, the default minor_version is planned to change from 1 to 2. See Upcoming Potential Incompatibilities.

Option deterministic (introduced in OTP 24.1) can be used to ensure that within the same major release of Erlang/OTP, the same encoded representation is returned for the same term. There is still no guarantee that the encoded representation remains the same between major releases of Erlang/OTP. So consistent ish. Periodt.

See also binary_to_term/1.


๐Ÿงš term_to_iovec(Term) -> ext_iovec()

Types:

Term = term()

Returns the encoding of Term according to the Erlang external term format as ext_iovec().

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

term_to_iovec() is a pure optimization of the functionality term_to_binary() provide. term_to_iovec() can for example refer directly to off heap binaries instead of copying the binary data into the result. Efficiency queen behavior, honestly. ๐Ÿ‘‘

See also term_to_binary/1.

๐Ÿ’œ term_to_iovec(Term, Options) -> ext_iovec()

Types:

Term = term()
Options =
    [compressed |
     {compressed, Level :: 0..9} |
     deterministic |
     {minor_version, Version :: 0..2}]

Returns the encoding of Term according to the Erlang external term format as ext_iovec().

โœจ term_to_iovec/2 (the glow-up of term_to_binary)

Okay so this one gives you the same encoding as term_to_binary/2, bestie, just with a different return type. Like, same vibes, different wrapper. The call

iolist_to_binary(term_to_iovec(Term, Opts))

will produce exactly the same result as term_to_binary(Term, Opts). No cap. ๐ŸŽ€

Right now the recognised options are all the options recognised by term_to_binary/2.

Think of term_to_iovec() as a pure optimization of what term_to_binary() already does โ€” it's the same girl but faster. term_to_iovec() can, for example, refer directly to off heap binaries instead of copying the binary data into the result. Efficiency queen. ๐Ÿ’…

See also term_to_binary/2.


โœจ throw(Any) -> no_return()

Types:

Any = term()

Raises an exception of class throw. It's literally made for doing non-local returns from functions โ€” like a little exit sign that says "we're done here bestie". ๐Ÿšช

If it's evaluated within a catch expression, the catch expression returns the value Any. Example:

> catch throw({hello, there}).
        {hello,there}

If it's evaluated within a try-block of a try expression, the value Any can be caught within the catch block. Example:

try
    throw({my_exception, "Something happened"})
catch
    throw:{my_exception, Desc} ->
        io:format(standard_error, "Error: ~s~n", [Desc])
end

Failure: nocatch if not caught by an exception handler. ๐Ÿ’€ Like throwing a party and nobody shows up.

See the guide about errors and error handling for additional information.


๐ŸŒธ time() -> Time

Types:

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. Example:

> time().
{9,42,44}

๐Ÿฆ‹ erlang: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. Math girlies rise ๐Ÿ™Œ

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. Give it a minute, she's busy. โณ


๐Ÿ’œ erlang:time_offset(Unit) -> integer()

Types:

Unit = time_unit()

Returns the current time offset between Erlang monotonic time and Erlang system time converted into the Unit passed as argument.

Same as calling erlang:convert_time_unit(erlang:time_offset(), native, Unit) however optimized for commonly used Units. Glow-up included for free โœจ


๐ŸŽ€ erlang:timestamp() -> Timestamp

Types:

Timestamp = timestamp()
timestamp() =
    {MegaSecs :: integer() >= 0,
     Secs :: integer() >= 0,
     MicroSecs :: integer() >= 0}

Returns current Erlang system time on the format {MegaSecs, Secs, MicroSecs}. This format is the same as os:timestamp/0 and the deprecated erlang:now/0 use. The reason for the existence of erlang:timestamp() is purely to simplify use for existing code that assumes this time stamp format. Current Erlang system time can more efficiently be retrieved in the time unit of your choice using erlang:system_time/1. It's giving legacy support, and we respect the elders. ๐Ÿ‘‘

The erlang:timestamp() BIF is equivalent to:

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

It, however, uses a native implementation that does not build garbage on the heap and with slightly better performance. No garbage, only gains ๐Ÿ’…

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. Do not trust her with your monotonicity, she did not sign up for that.

๐Ÿงš tl(List) -> term()

Types:

List = nonempty_maybe_improper_list()

Returns the tail of List, that is, the list minus the first element โ€” like when you skip the intro of a song. For example:

> tl([geesties, guilies, beasties]).
[guilies, beasties]

> tl([geesties]).
[]

> tl([geesties, guilies, beasties | improper_end]).
[guilies, beasties | improper_end]

> tl([geesties | improper_end]).
improper_end

Allowed in guard tests. โœ…

Failure: badarg if List is the empty list []. She cannot remove the first element of nothing, bestie. ๐Ÿ˜ญ


๐Ÿ”ฅ erlang:trace(PidPortSpec, How, FlagList) -> integer()

Types:

PidPortSpec =
    pid() |
    port() |
    all | processes | ports | existing | existing_processes |
    existing_ports | new | new_processes | new_ports
How = boolean()
FlagList = [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()}

Turns on (if How == true) or off (if How == false) the trace flags in FlagList for the process or processes represented by PidPortSpec. It's the on/off switch of who's being watched, main character surveillance edition ๐Ÿ”

PidPortSpec is either a process identifier (pid) for a local process, a port identifier, or one of the following atoms:

  • all: โ€” All currently existing processes and ports and all that will be created in the future. Literally everyone. Periodt.
  • processes: โ€” All currently existing processes and all that will be created in the future.
  • ports: โ€” All currently existing ports and all that will be created in the future.
  • existing: โ€” All currently existing processes and ports.
  • existing_processes: โ€” All currently existing processes.
  • existing_ports: โ€” All currently existing ports.
  • new: โ€” All processes and ports that will be created in the future.
  • new_processes: โ€” All processes that will be created in the future.
  • new_ports: โ€” All ports that will be created in the future.

FlagList can contain any number of the following flags (the "message tags" refers to the list of trace messages):

  • all: โ€” Sets all trace flags except tracer and cpu_timestamp, which are in their nature different than the others. The exception girlies ๐Ÿซถ
  • send: โ€” Traces sending of messages.

Message tags: send and send_to_non_existing_process.

  • 'receive': โ€” Traces receiving of messages.

Message tags: 'receive'.

  • call: โ€” Traces certain function calls. Specify which function calls to trace by calling erlang:trace_pattern/3.

Message tags: call and return_from.

  • silent: โ€” Used with the call trace flag. The call, return_from, and return_to trace messages are inhibited if this flag is set, but they are executed as normal if there are match specifications.

Silent mode is inhibited by executing erlang:trace(_, false, [silent|_]), or by a match specification executing the function {silent, false}.

The silent trace flag facilitates setting up a trace on many or even all processes in the system. The trace can then be activated and deactivated using the match specification function {silent,Bool}, giving a high degree of control of which functions with which arguments that trigger the trace.

Message tags: call, return_from, and return_to. Or rather, the absence of. ๐Ÿคซ

  • return_to: โ€” Used with the call trace flag. Traces the return from a traced function back to its caller. Only works for functions traced with option local to erlang:trace_pattern/3.

The semantics is that a trace message is sent when a call traced function returns, that is, when a chain of tail recursive calls ends. Only one trace message is sent per chain of tail recursive calls, so the properties of tail recursiveness for function calls are kept while tracing with this flag. Using call and return_to trace together makes it possible to know exactly in which function a process executes at any time. Tracking your fave's every move โœจ

To get trace messages containing return values from functions, use the {return_trace} match specification action instead.

Message tags: return_to.

  • procs: โ€” Traces process-related events.

Message tags: spawn, spawned, exit, register, unregister, link, unlink, getting_linked, and getting_unlinked.

  • ports: โ€” Traces port-related events.

Message tags: open, closed, register, unregister, getting_linked, and getting_unlinked.

  • running: โ€” Traces scheduling of processes.

Message tags: in and out.

  • exiting: โ€” Traces scheduling of exiting processes.

Message tags: in_exiting, out_exiting, and out_exited.

  • running_procs: โ€” Traces scheduling of processes just like running. However, this option also includes schedule events when the process executes within the context of a port without being scheduled out itself.

Message tags: in and out.

  • running_ports: โ€” Traces scheduling of ports.

Message tags: in and out.

  • garbage_collection โ€” traces garbage collections of processes, bestie. message tags: gc_minor_start, gc_max_heap_size, and gc_minor_end. ๐Ÿ—‘๏ธโœจ
  • timestamp โ€” includes a time stamp in all trace messages. the time stamp (Ts) has the same form as returned by erlang:now(). โฐ
  • cpu_timestamp โ€” a global trace flag for the Erlang node that makes all trace time stamps using flag timestamp be in CPU time, not wall clock time. so basically cpu_timestamp is not to be used if monotonic_timestamp or strict_monotonic_timestamp is enabled. only allowed with PidPortSpec==all. if the host machine OS does not support high-resolution CPU time measurements, trace/3 exits with badarg. > heads up: most OS do not synchronize this value across cores, so be prepared that time can seem to go backwards when using this option ๐Ÿ˜ญ๐Ÿ’€
  • monotonic_timestamp โ€” includes an Erlang monotonic time time stamp in all trace messages. the time stamp (Ts) has the same format and value as produced by erlang:monotonic_time(nanosecond). this flag overrides flag cpu_timestamp. ๐Ÿ“ˆ
  • strict_monotonic_timestamp โ€” includes a time stamp consisting of Erlang monotonic time and a monotonically increasing integer in all trace messages. the time stamp (Ts) has the same format and value as produced by { erlang:monotonic_time(nanosecond), erlang:unique_integer([monotonic])}. this flag overrides flag cpu_timestamp. ๐Ÿ”ฅ
  • arity โ€” used with the call trace flag. {M, F, Arity} is specified instead of {M, F, Args} in call trace messages. ๐Ÿ”ข
  • set_on_spawn โ€” makes any process created by a traced process inherit its trace flags, including flag set_on_spawn. ๐Ÿฃ
  • set_on_first_spawn โ€” makes the first process created by a traced process inherit its trace flags, excluding flag set_on_first_spawn. ๐Ÿฅ‡
  • set_on_link โ€” makes any process linked by a traced process inherit its trace flags, including flag set_on_link. ๐Ÿ”—
  • set_on_first_link โ€” makes the first process linked to by a traced process inherit its trace flags, excluding flag set_on_first_link. ๐ŸŽ€
  • {tracer, Tracer} โ€” specifies where to send the trace messages. Tracer must be the process identifier of a local process or the port identifier of a local port. ๐Ÿ“ฎ
  • {tracer, TracerModule, TracerState} โ€” specifies that a tracer module is to be called instead of sending a trace message. the tracer module can then ignore or change the trace message. for more details on how to write a tracer module, see erl_tracer(3erl). ๐Ÿงš

if no tracer is specified, the calling process receives all the trace messages. you're the main character now, bestie ๐Ÿ’…

the effect of combining set_on_first_link with set_on_link is the same as set_on_first_link alone. likewise for set_on_spawn and set_on_first_spawn. no cap. ๐Ÿซถ

the tracing process receives the trace messages described in the following list. Pid is the process identifier of the traced process in which the traced event has occurred. the third tuple element is the message tag. ๐Ÿ‘‘

if flag timestamp, strict_monotonic_timestamp, or monotonic_timestamp is specified, the first tuple element is trace_ts instead, and the time stamp is added as an extra element last in the message tuple. if multiple time stamp flags are passed, timestamp has precedence over strict_monotonic_timestamp, which in turn has precedence over monotonic_timestamp. all time stamp flags are remembered, so if two are passed and the one with highest precedence later is disabled, the other one becomes active. the way this priority stack just works ๐Ÿ˜ญโœจ

if a match specification (applicable only for call, send and 'receive' tracing) contains a {message} action function with a non-boolean value, that value is added as an extra element to the message tuple either in the last position or before the timestamp (if it is present). ๐Ÿ“จ


๐Ÿ’Œ Trace messages

  • {trace, PidPort, send, Msg, To} โ€” when PidPort sends message Msg to process To.
  • {trace, PidPort, send_to_non_existing_process, Msg, To} โ€” when PidPort sends message Msg to the non-existing process To. ๐Ÿ’€
  • {trace, PidPort, 'receive', Msg} โ€” when PidPort receives message Msg. if Msg is set to time-out, a receive statement can have timed out, or the process received a message with the payload timeout. โณ
  • {trace, Pid, call, {M, F, Args}} โ€” when Pid calls a traced function. the return values of calls are never supplied, only the call and its arguments.

trace flag arity can be used to change the contents of this message, so that Arity is specified instead of Args.

  • {trace, Pid, return_to, {M, F, Arity}} โ€” when Pid returns to the specified function. this trace message is sent if both the flags call and return_to are set, and the function is set to be traced on local function calls. the message is only sent when returning from a chain of tail recursive function calls, where at least one call generated a call trace message (that is, the functions match specification matched, and {message, false} was not an action). ๐Ÿ”
  • {trace, Pid, return_from, {M, F, Arity}, ReturnValue} โ€” when Pid returns from the specified function. this trace message is sent if flag call is set, and the function has a match specification with a return_trace or exception_trace action. ๐Ÿ
  • {trace, Pid, exception_from, {M, F, Arity}, {Class, Value}} โ€” when Pid exits from the specified function because of an exception. this trace message is sent if flag call is set, and the function has a match specification with an exception_trace action. ๐Ÿ˜ญ
  • {trace, Pid, spawn, Pid2, {M, F, Args}} โ€” when Pid spawns a new process Pid2 with the specified function call as entry point.

Args is supposed to be the argument list, but can be any term if the spawn is erroneous. ๐Ÿฃ

  • {trace, Pid, spawned, Pid2, {M, F, Args}} โ€” when Pid is spawned by process Pid2 with the specified function call as entry point.

Args is supposed to be the argument list, but can be any term if the spawn is erroneous. ๐ŸŒฑ

  • {trace, Pid, exit, Reason} โ€” when Pid exits with reason Reason. ๐Ÿšช
  • {trace, PidPort, register, RegName} โ€” when PidPort gets the name RegName registered.
  • {trace, PidPort, unregister, RegName} โ€” when PidPort gets the name RegName unregistered. this is done automatically when a registered process or port exits.
  • {trace, Pid, link, Pid2} โ€” when Pid links to a process Pid2. ๐Ÿ”—
  • {trace, Pid, unlink, Pid2} โ€” when Pid removes the link from a process Pid2.
  • {trace, PidPort, getting_linked, Pid2} โ€” when PidPort gets linked to a process Pid2.
  • {trace, PidPort, getting_unlinked, Pid2} โ€” when PidPort gets unlinked from a process Pid2.
  • {trace, Port, open, Pid, Driver} โ€” when Pid opens a new port Port with the running Driver.

Driver is the name of the driver as an atom. ๐Ÿš€

  • {trace, Port, closed, Reason} โ€” when Port closes with Reason.
  • {trace, Pid, in | in_exiting, {M, F, Arity} | 0} โ€” when Pid is scheduled to run. the process runs in function {M, F, Arity}. on some rare occasions, the current function cannot be determined, then the last element is 0. ๐Ÿƒโ€โ™€๏ธ
  • {trace, Pid, out | out_exiting | out_exited, {M, F, Arity} | 0} โ€” when Pid is scheduled out. the process was running in function {M, F, Arity}. on some rare occasions, the current function cannot be determined, then the last element is 0. ๐Ÿ˜ด
  • {trace, Port, in, Command | 0} โ€” when Port is scheduled to run. Command is the first thing the port will execute, it can however run several commands before being scheduled out. on some rare occasions, the current function cannot be determined, then the last element is 0.

the possible commands are call, close, command, connect, control, flush, info, link, open, and unlink. ๐Ÿ“‹

  • {trace, Port, out, Command | 0} โ€” when Port is scheduled out. the last command run was Command. on some rare occasions, the current function cannot be determined, then the last element is 0. Command can contain the same commands as in
  • {trace, Pid, gc_minor_start, Info} โ€”

sent when a young garbage collection is about to be started. Info is a list of two-element tuples, where the first element is a key, and the second is the value. do not depend on any order of the tuples. the following keys are defined: ๐Ÿ—‘๏ธ๐Ÿ’–

  • heap_size โ€” the size of the used part of the heap.
  • heap_block_size โ€” the size of the memory block used for storing the heap and the stack.
  • old_heap_size โ€” the size of the used part of the old heap.
  • old_heap_block_size โ€” the size of the memory block used for storing the old heap.
  • stack_size โ€” the size of the stack.
  • recent_size โ€” the size of the data that survived the previous garbage collection.
  • mbuf_size โ€” the combined size of message buffers associated with the process.
  • bin_vheap_size โ€” the total size of unique off-heap binaries referenced from the process heap.
  • bin_vheap_block_size โ€” the total size of binaries allowed in the virtual heap in the process before doing a garbage collection.
  • bin_old_vheap_size โ€” the total size of unique off-heap binaries referenced from the process old heap.
  • bin_old_vheap_block_size โ€” the total size of binaries allowed in the virtual old heap in the process before it does a garbage collection. ๐Ÿ’…
  • wordsize โ€” for the gc_minor_start event, this is the size of the need that triggered the GC. For the matching gc_minor_end event, it's the size of reclaimed memory = start heap_size - end heap_size. Math, but make it fashion. โœจ

All sizes are in words, bestie. Words. Not bytes. Don't come for me. ๐Ÿ“

  • {trace, Pid, gc_max_heap_size, Info} โ€” sent when max_heap_size is reached during garbage collection. Info contains the same kind of list as in message gc_start, but the sizes reflect the sizes that triggered max_heap_size to be reached. She hit the ceiling, and she's telling you about it. ๐Ÿ˜ญ
  • {trace, Pid, gc_minor_end, Info} โ€” sent when young garbage collection is finished. Info contains the same kind of list as in message gc_minor_start, but the sizes reflect the new sizes after garbage collection. Cleanup complete, glow up achieved. ๐Ÿงš
  • {trace, Pid, gc_major_start, Info} โ€” sent when fullsweep garbage collection is about to be started. Info contains the same kind of list as in message gc_minor_start. Big sweep incoming, brace yourself. ๐ŸŒช๏ธ
  • {trace, Pid, gc_major_end, Info} โ€” sent when fullsweep garbage collection is finished. Info contains the same kind of list as in message gc_minor_start, but the sizes reflect the new sizes after a fullsweep garbage collection. Full sweep, fully slayed. โœจ

If the tracing process/port dies, or the tracer module returns remove, the flags are silently removed. No drama, no error, just quietly gone. ๐Ÿ’€

Each process can only be traced by one tracer. So yeah โ€” attempts to trace an already-traced process fail. Monogamy, but for tracing. ๐Ÿซถ

Returns a number indicating the number of processes that matched PidPortSpec. If PidPortSpec is a process identifier, the return value is 1. If PidPortSpec is all or existing, the return value is the number of processes running. If PidPortSpec is new, the return value is 0.

Failure: badarg if the specified arguments are not supported. For example, cpu_timestamp is not supported on all platforms. Not every stage has the same lighting, okay? ๐Ÿ™ˆ


๐Ÿฆ‹ erlang:trace_delivered(Tracee) -> Ref ๐Ÿฆ‹

Types:

Tracee = pid() | all
Ref = reference()

Okay so here's the situation: the delivery of trace messages (generated by erlang:trace/3, seq_trace(3erl), or erlang:system_profile/2) is dislocated on the time-line compared to other events in the system. Like, the vibes arrive out of order. If you know that Tracee has passed some specific point in its execution, and you want to know when at least all trace messages corresponding to events up to this point have reached the tracer โ€” that's literally what erlang:trace_delivered(Tracee) is for. ๐ŸŽฏ

When it's guaranteed that all trace messages are delivered to the tracer up to the point that Tracee reached at the time of the call to erlang:trace_delivered(Tracee), then a {trace_delivered, Tracee, Ref} message is sent to the caller of erlang:trace_delivered(Tracee). Iconic closure behaviour. ๐Ÿ’–

Heads up bestie โ€” message trace_delivered does not imply that trace messages have been delivered. Instead it implies that all trace messages that are to be delivered have been delivered. Read that again, it's giving subtle but important. ๐Ÿ‘‘

It is not an error if Tracee is not, and has not been traced by someone โ€” but if that's the case, no trace messages have been delivered when the trace_delivered message arrives. Empty inbox, zero notes, no crumbs. ๐Ÿ‚

Also: Tracee must refer to a process currently or previously existing on the same node as the caller of erlang:trace_delivered(Tracee) resides on. The special Tracee atom all denotes all processes that currently are traced in the node. No long-distance relationships. ๐ŸŒˆ

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. Delivered-delivered. โœจ

Example: process A is Tracee, port B is tracer, and process C is the port owner of B. C wants to close B when A exits. To ensure that the trace is not truncated, C can call erlang:trace_delivered(A) when A exits, and wait for message {trace_delivered, A, Ref} before closing B. See? Clean shutdown, no lost lore. ๐Ÿ’…

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.


๐Ÿ’œ erlang:trace_info(PidPortFuncEvent, Item) -> Res ๐Ÿ’œ

Types:

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 | all
Res = trace_info_return()
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}
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, integer() >= 0 | boolean() | undefined} |
    {call_time,
     [{pid(),
       integer() >= 0,
       integer() >= 0,
       integer() >= 0}] |
     boolean() |
     undefined}
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
trace_match_spec() =
    [{[term()] | '_' | match_variable(), [term()], [term()]}]
match_variable() = atom()
   Approximation of '$1' | '$2' | '$3' | ...

Returns trace information about a port, process, function, or event. The vibe-check function, essentially. ๐Ÿ”

To get info about a port or process, PidPortFuncEvent is to be a process identifier (pid), port identifier, or one of the atoms new, new_processes, or new_ports. The atom new or new_processes means that the default trace state for processes to be created is returned. The atom new_ports means that the default trace state for ports to be created is returned. Future babies, pre-inspected. ๐Ÿผ

Valid Items for ports and processes:

  • flags โ€” returns a list of atoms indicating what kind of traces is enabled for the process. The list is empty if no traces are enabled, and one or more of the following atoms if traces are enabled: send, 'receive', set_on_spawn, call, return_to, procs, ports, set_on_first_spawn, set_on_link, running, running_procs, running_ports, silent, exiting, monotonic_timestamp, strict_monotonic_timestamp, garbage_collection, timestamp, and arity. The order is arbitrary โ€” don't read into it, she's just like that. ๐Ÿ’…
  • tracer โ€” returns the identifier for process, port, or a tuple containing the tracer module and tracer state tracing this process. If this process is not traced, the return value is []. Nobody's watching, and honestly? Peace. ๐Ÿ•Š๏ธ

To get information about a function, PidPortFuncEvent is to be the three-element tuple {Module, Function, Arity} or the atom on_load. No wildcards are allowed. Returns undefined if the function does not exist, or false if the function is not traced. If PidPortFuncEvent is on_load, the information returned refers to the default value for code that will be loaded. โœจ

Valid Items for functions:

  • traced โ€” returns global if this function is traced on global function calls, local if this function is traced on local function calls (that is, local and global function calls), and false if local or global function calls are not traced. Global vs local, the eternal discourse. ๐ŸŒ
  • match_spec โ€” returns the match specification for this function, if it has one. If the function is locally or globally traced but has no match specification defined, the returned value is []. Empty list, not a problem, just a bare face. ๐ŸŽ€
  • meta โ€” returns the meta-trace tracer process, port, or trace module for this function, if it has one. If the function is not meta-traced, the returned value is false. If the function is meta-traced but has once detected that the tracer process is invalid, the returned value is []. She noticed the tracer was fake and moved on. ๐Ÿ’€
  • meta_match_spec โ€” returns the meta-trace match specification for this function, if it has one. If the function is meta-traced but has no match specification defined, the returned value is []. Same energy, different layer. ๐Ÿงš
  • call_count โ€” returns the call count value for this function or true for the pseudo function on_load if call count tracing is active. Otherwise false is returned.

See also erlang:trace_pattern/3. ๐Ÿ“–

  • call_time โ€” returns the call time values for this function or true for the pseudo function on_load if call time tracing is active. Otherwise false is returned. The call time values returned, [{Pid, Count, S, Us}], is a list of each process that executed the function and its specific counters. Per-process receipts! ๐Ÿงพ

See also erlang:trace_pattern/3. ๐Ÿ“–

  • all โ€” returns a list containing the {Item, Value} tuples for all other items, or returns false if no tracing is active for this function. The full haul, or nothing at all. ๐Ÿ›๏ธ

To get information about an event, PidPortFuncEvent is to be one of the atoms send or 'receive'.

One valid Item for events exists:

  • match_spec โ€” returns the match specification for this event, if it has one, or true if no match specification has been set. ๐ŸŽฏ

The return value is {Item, Value}, where Value is the requested information as described earlier. If a pid for a dead process was specified, or the name of a non-existing function, Value is undefined. Ghosted by the runtime, respectfully. ๐Ÿ‘ป

  • erlang:trace_pattern(MFA, MatchSpec) -> integer() >= 0

Types:

MFA = trace_pattern_mfa() | send | 'receive'
MatchSpec =
    (MatchSpecList :: trace_match_spec()) |
    boolean() |
    restart | pause
trace_pattern_mfa() = {atom(), atom(), arity() | '_'} | on_load
trace_match_spec() =
    [{[term()] | '_' | match_variable(), [term()], [term()]}]
match_variable() = atom()
   Approximation of '$1' | '$2' | '$3' | ...

Literally the exact same thing as erlang:trace_pattern(Event, MatchSpec, []) โ€” it's just been left here for backward compatibility, bestie. Old code still slays, we just don't ship it new. ๐Ÿ’…

  • erlang:trace_pattern(MFA :: send, MatchSpec, FlagList :: []) -> integer() >= 0

Types:

MatchSpec = (MatchSpecList :: trace_match_spec()) | boolean()
trace_match_spec() =
    [{[term()] | '_' | match_variable(), [term()], [term()]}]
match_variable() = atom()
   Approximation of '$1' | '$2' | '$3' | ...

Okay so this one sets the trace pattern for message sending. โœจ You must pair it with erlang:trace/3 to actually set the send trace flag on one or more processes, or it's giving nothing. By default, every single message sent from send-traced processes gets traced. If you want to be picky and only trace send events based on message content, the sender and/or the receiver, that's where erlang:trace_pattern/3 comes in. ๐ŸŽฏ

Argument MatchSpec can take these forms:

  • MatchSpecList: a list of match specifications, duh. The matching happens on the list [Receiver, Msg]. Receiver is the process or port identity of the receiver, and Msg is the message term. The pid of the sending process is right there via the guard function self/0. An empty list is the same as true. For more info, see section Match Specifications in Erlang in the User's Guide. ๐Ÿ“š
  • true: enables tracing for all sent messages (from send traced processes). Any match specification is removed. This is the default, iykyk.
  • false: disables tracing for all sent messages. Any match specification is removed.

Argument FlagList must be [] for send tracing. No exceptions, no notes. ๐Ÿ™…โ€โ™€๏ธ

The return value is always 1.

Examples:

Only trace messages to a specific process Pid:

> erlang:trace_pattern(send, [{[Pid, '_'],[],[]}], []).
1

Only trace messages matching {reply, _}:

> erlang:trace_pattern(send, [{['_', {reply,'_'}],[],[]}], []).
1

Only trace messages sent to the sender itself:

> erlang:trace_pattern(send, [{['$1', '_'],[{'=:=','$1',{self}}],[]}], []).
1

Only trace messages sent to other nodes:

> erlang:trace_pattern(send, [{['$1', '_'],[{'=/=',{node,'$1'},{node}}],[]}], []).
1
Note: a match specification for send trace can use all guard and body functions except caller. Not that one, bestie. ๐Ÿ™ˆ

It fails by raising an error exception with an error reason of:

  • badarg: if an argument is invalid.
  • system_limit: if a match specification passed as argument has excessive nesting which causes scheduler stack exhaustion for the scheduler that the calling process is executing on. Scheduler stack size can be configured when starting the runtime system. ๐Ÿ˜ญ Nesting goes hard, apparently.
  • erlang:trace_pattern(MFA :: 'receive', MatchSpec, FlagList :: []) -> integer() >= 0

Types:

MatchSpec = (MatchSpecList :: trace_match_spec()) | boolean()
trace_match_spec() =
    [{[term()] | '_' | match_variable(), [term()], [term()]}]
match_variable() = atom()
   Approximation of '$1' | '$2' | '$3' | ...

Same vibe, different direction โ€” this one sets the trace pattern for message receiving. ๐Ÿฆ‹ Must be combined with erlang:trace/3 to set the 'receive' trace flag for one or more processes. By default, all messages received by 'receive' traced processes are traced. To limit traced receive events based on message content, the sender and/or the receiver, you use erlang:trace_pattern/3. ๐Ÿ’–

Argument MatchSpec can take these forms:

  • MatchSpecList: a list of match specifications. The matching is done on the list [Node, Sender, Msg]. Node is the node name of the sender. Sender is the process or port identity of the sender, or the atom undefined if the sender is not known (which can totally happen with remote senders โ€” no cap). Msg is the message term. The pid of the receiving process is accessible with the guard function self/0. An empty list is the same as true. For more info, see section Match Specifications in Erlang in the User's Guide. ๐Ÿ“–
  • true: enables tracing for all received messages (to 'receive' traced processes). Any match specification is removed. This is the default.
  • false: disables tracing for all received messages. Any match specification is removed.

Argument FlagList must be [] for receive tracing. Same rule, different flag. ๐Ÿšซ

The return value is always 1.

Examples:

Only trace messages from a specific process Pid:

> erlang:trace_pattern('receive', [{['_',Pid, '_'],[],[]}], []).
1

Only trace messages matching {reply, _}:

> erlang:trace_pattern('receive', [{['_','_', {reply,'_'}],[],[]}], []).
1

Only trace messages from other nodes:

> erlang:trace_pattern('receive', [{['$1', '_', '_'],[{'=/=','$1',{node}}],[]}], []).
1
Note: a match specification for 'receive' trace can use all guard and body functions except caller, is_seq_trace, get_seq_token, set_seq_token, enable_trace, disable_trace, trace, silent, and process_dump. That's a whole blocklist, bestie, respect it. ๐Ÿ’€

It fails by raising an error exception with an error reason of:

  • badarg: if an argument is invalid.
  • system_limit: if a match specification passed as argument has excessive nesting which causes scheduler stack exhaustion for the scheduler that the calling process is executing on. Scheduler stack size can be configured when starting the runtime system.

  • erlang:trace_pattern(MFA, MatchSpec, FlagList) -> integer() >= 0

Types:

MFA = trace_pattern_mfa()
MatchSpec =
    (MatchSpecList :: trace_match_spec()) |
    boolean() |
    restart | pause
FlagList = [trace_pattern_flag()]
trace_pattern_mfa() = {atom(), atom(), arity() | '_'} | on_load
trace_match_spec() =
    [{[term()] | '_' | match_variable(), [term()], [term()]}]
trace_pattern_flag() =
    global | local | meta |
    {meta, Pid :: pid()} |
    {meta, TracerModule :: module(), TracerState :: term()} |
    call_count | call_time
match_variable() = atom()
   Approximation of '$1' | '$2' | '$3' | ...

Now we're at the main character of the trio: this enables or disables call tracing for one or more functions. ๐Ÿ‘‘ And yes โ€” it must be combined with erlang:trace/3 to set the call trace flag for one or more processes. They're a package deal, fr fr.

Conceptually, call tracing works like this: inside the Erlang virtual machine, there's a set of processes and a set of functions to be traced. If a traced process calls a traced function, the trace action is taken. Otherwise, nothing happens. Literally nothing. Silence. ๐Ÿฆ—

To add or remove one or more processes from the set of traced processes, use erlang:trace/3.

To add or remove functions from the set of traced functions, use erlang:trace_pattern/3.

The BIF erlang:trace_pattern/3 can also add match specifications to a function. A match specification is made of a pattern that the function arguments must match, a guard expression that must evaluate to true, and an action to be performed. The default action is to send a trace message. If the pattern doesn't match or the guard fails, the action is not executed. Simple as that. โœจ

Argument MFA has to be a tuple, like {Module, Function, Arity}, or the atom on_load (explained below). It can be the module, function, and arity for a function (or a BIF in any module โ€” yes, any). The atom '_' works as a wildcard in any of these ways:

  • {Module,Function,'_'}: all functions of any arity named Function in module Module.
  • {Module,'_','_'}: all functions in module Module.
  • {'_','_','_'}: all functions in all loaded modules. Yes, all of them. ๐Ÿ˜ณ

Other combinations, such as {Module,'_',Arity}, are not allowed. Don't try it. Local functions match wildcards only if option local is in FlagList.

If argument MFA is the atom on_load, the match specification and flag list are used on all modules that are newly loaded. Fresh modules get the whole treatment. ๐ŸŽ€

Argument MatchSpec can take these forms:

  • false: disables tracing for the matching functions. Any match specification is removed.
  • true: enables tracing for the matching functions. Any match specification is removed.
  • MatchSpecList: a list of match specifications. An empty list is equivalent to true. For a description of match specifications, see section Match Specifications in Erlang in the User's Guide. ๐Ÿ“š
  • restart: for the FlagList options call_count and call_time โ€” restarts the existing counters. The behavior is undefined for other FlagList options. โš ๏ธ Undefined means don't, bestie.
  • pause: for the FlagList options call_count and call_time โ€” pauses the existing counters. The behavior is undefined for other FlagList options. Same warning, same drama. ๐Ÿ’€

Parameter FlagList is a list of options. Here's the valid ones:

  • global: turns on or off call tracing for global function calls (that is, calls specifying the module explicitly). Only exported functions match and only global calls generate trace messages. This is the default. ๐ŸŒ

local

Turns on (or off) call tracing for all the types of function calls. Trace messages get yeeted whenever any of the specified functions are called โ€” no matter how they're called, bestie. And if the return_to flag is set for the process, a return_to message also gets sent when this function returns to its caller. ๐Ÿซถ

meta | {meta, Pid} | {meta, TracerModule, TracerState}

Turns meta-tracing on or off for all types of function calls. Trace messages go to the tracer whenever any of the specified functions are called. If you don't specify a tracer, self() is used as the default tracer process. ๐Ÿ’…

Meta-tracing traces all processes and literally does not care about the process trace flags set by erlang:trace/3 โ€” the trace flags are instead fixed to [call, timestamp]. Iconic behaviour, no notes.

The match specification function {return_trace} works with meta-trace and sends its trace message to the same tracer. โœจ

call_count

Starts (MatchSpec == true) or stops (MatchSpec == false) call count tracing for all types of function calls. For every function, a counter gets incremented when the function is called, in any process. No process trace flags need to be activated โ€” it's giving low maintenance ๐Ÿ‘‘

If call count tracing is started while it's already running, the count restarts from zero. To pause running counters, use MatchSpec == pause. Paused and running counters can be restarted from zero with MatchSpec == restart.

To read the counter value, use erlang:trace_info/2.

call_time

Starts (MatchSpec == true) or stops (MatchSpec == false) call time tracing for all types of function calls. For every function, a counter gets incremented when the function is called. Time spent in the function accumulates in two other counters: seconds and microseconds. The counters are stored for each call traced process. โฑ๏ธ

If call time tracing is started while already running, the count and time restart from zero. To pause running counters, use MatchSpec == pause. Paused and running counters can be restarted from zero with MatchSpec == restart.

To read the counter value, use erlang:trace_info/2.


The options global and local are mutually exclusive, and global is the default (when no options are specified). The options call_count and meta perform a kind of local tracing and cannot be combined with global. A function can be globally or locally traced โ€” pick a lane, babe. If global tracing is specified for a set of functions, then local, meta, call time, and call count tracing for the matching set of local functions is disabled, and conversely. ๐Ÿ”„

When disabling trace, the option must match the type of trace set on the function. That is, local tracing must be disabled with option local and global tracing with option global (or no option), and so on.

Part of a match specification list cannot be changed directly. If a function has a match specification, it can be replaced with a new one. To change an existing match specification, use the BIF erlang:trace_info/2 to retrieve the existing match specification.

Returns the number of functions matching argument MFA. This is zero if none matched. ๐Ÿ˜ญ

Fails by raising an error exception with an error reason of:

  • badarg โ€” if an argument is invalid.
  • system_limit โ€” if a match specification passed as argument has excessive nesting which causes scheduler stack exhaustion for the scheduler that the calling process is executing on. Scheduler stack size can be configured when starting the runtime system.

trunc(Number) -> integer()

Types:

Number = number()

Truncates the decimals of Number, for example:

> trunc(5.7).
5

> trunc(-5.7).
-5

> trunc(5).
5

> trunc(36028797018963969.0).
36028797018963968

In the last example, trunc(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 are lowkey shady like that ๐Ÿ’€

Allowed in guard tests.

tuple_size(Tuple) -> integer() >= 0

Types:

Tuple = tuple()

Returns an integer that is the number of elements in Tuple, for example:

> tuple_size({morni, mulle, bwange}).
3

Allowed in guard tests.

tuple_to_list(Tuple) -> [term()]

Types:

Tuple = tuple()

Returns a list corresponding to Tuple. Tuple can contain any Erlang terms. Example:

> tuple_to_list({share, {'Ericsson_B', 163}}).
[share,{'Ericsson_B',163}]

unalias(Alias) -> boolean()

Types:

Alias = reference()

Deactivates the alias Alias previously created by the calling process. An alias can for example be created via alias/0, or monitor/3. unalias/1 will always deactivate the alias regardless of options used when creating the alias. No take-backsies, it's done ๐Ÿ’…

Returns true if Alias was a currently active alias for current processes; otherwise, false.

For more information on process aliases see the Process Aliases section of the Erlang Reference Manual.

erlang:unique_integer() -> integer()

Generates and returns an integer unique on the current runtime system instance. The same as calling erlang:unique_integer([]).

erlang:unique_integer(ModifierList) -> integer()

Types:

ModifierList = [Modifier]
Modifier = positive | monotonic

Generates and returns an integer unique on the current runtime system instance. The integer is 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. ๐ŸŽ€

By default, when [] is passed as ModifierList, both negative and positive integers can be returned. This is to use the range of integers that don't need heap memory allocation as much as possible. 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.

Modifiers:

  • positive โ€” returns only positive integers.

Notice that 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.

All valid Modifiers can be combined. Repeated (valid) Modifiers in the ModifierList are ignored.

Note: The set of integers returned by erlang:unique_integer/1 using different sets of Modifiers will overlap. For example, by calling unique_integer([monotonic]), and unique_integer([positive, monotonic]) repeatedly, you will eventually see some integers that are returned by both calls.

Failures:

  • badarg โ€” if ModifierList is not a proper list.
  • badarg โ€” if Modifier is not a valid modifier.

erlang:universaltime() -> DateTime

Types:

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. Example: ๐ŸŒ

> erlang:universaltime().
{{1996,11,6},{14,18,43}}

erlang:universaltime_to_localtime(Universaltime) -> Localtime

Types:

Localtime = 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. 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.

Types:

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. ๐Ÿซถ

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

okay so once unlink(Id) has returned, it is guaranteed that the link between the caller and the unlikee 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 unlikee sending the caller an exit signal by calling the exit/2 BIF. So yeah, 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. ๐Ÿฆ‹

Failure: badarg if Id does not identify a process or a node local port.


unregister(RegName) -> true ๐ŸŽ€

Types:

RegName = atom()

Removes the registered name RegName associated with a process identifier or a port identifier from the name registry. 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. iykyk ๐Ÿ‘€

Users are advised not to unregister system processes.

Failure: badarg if RegName is not a registered name.


whereis(RegName) -> pid() | port() | undefined ๐Ÿ”Ž

Types:

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. Example:

> whereis(db).
<0.43.0>

erlang: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.

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.

shoutout to Ericsson AB, erts 13.2.2.5, and erlang(3erl) for this page โ€” mwah, bestie ๐Ÿ’–๐ŸŽ€

๐Ÿ“ฆ where this page comes from