A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://www.erlang.org/doc/apps/erts/erlang below:

erlang — erts v16.0.1

The Erlang BIFs and predefined types.

By convention, most Built-In Functions (BIFs) and all predefined types are included in this module. Some of the BIFs and all of the predefined types are viewed more or less as part of the Erlang programming language and are auto-imported. Thus, it is not necessary to specify the module name. For example, the calls atom_to_list(erlang) and erlang:atom_to_list(erlang) are identical.

Auto-imported BIFs are annotated with auto-imported and predefined types are annotated with predefined.

Some auto-imported BIFs are also allowed in guard expression. Such BIFs are annoted with both auto-imported and guard-bif.

BIFs can fail for various reasons. All BIFs fail with reason badarg if they are called with arguments of an incorrect type. The other reasons are described in the description of each individual BIF.

Summary Predefined datatypes

All possible Erlang terms. Synonym for term/0.

The arity of a function or type.

An Erlang binary, that is, a bitstring with a size divisible by 8.

A byte of data represented by an integer.

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

The dynamic type, which represents a statically unknown type

A binary or list containing bytes and/or iodata.

A list containing bytes and/or iodata.

An Erlang list containing terms of any type.

An Erlang list containing terms of the type ContentType.

An Erlang map containing any number of key and value associations.

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

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

A three-tuple representing a Module:Function/Arity function signature.

An Erlang module represented by an atom.

The type used to show that a function will never return a value, that is it will always throw an exception.

An Erlang node represented by an atom.

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

This type is used to show that a function will never return a value; that is it will always throw an exception.

A list/0 that contains some items.

A string/0 that contains some characters.

An integer greater than zero.

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

All possible Erlang terms. Synonym for any/0.

Types

The current cpu topology.

The time_unit/0 type also consist of the following deprecated symbolic time units

An opaque handle identifying a distribution channel.

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

A term of type iovec/0, structured according to the Erlang external term format.

A list with the system wide garbage collection defaults.

The requested scheduler bind type.

The destination for a send operation.

The time unit used by erlang time APIs.

Checksum

Computes and returns the adler32 checksum for Data.

Continues computing the adler32 checksum by combining the previous checksum, OldAdler, with the checksum of Data.

Combines two previously computed adler32 checksums.

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

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

Combines two previously computed crc32 checksums.

Computes an MD5 message digest from Data, where the length of the digest is 128 bits (16 bytes). Data is a binary or a list of small integers and binaries.

Finishes the update of an MD5 Context and returns the computed MD5 message digest.

Creates an MD5 context, to be used in the following calls to md5_update/2.

Update an MD5 Context with Data and returns a NewContext.

Code

Returns true if Module has old code, otherwise false.

Checks if the node local process identified by Pid executes old code for 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.

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.

This BIF is useful for builders of cross-reference tools.

Loads Module described by the object code contained within Binary.

Loads and links a dynamic library containing native implemented functions (NIFs) for a module.

Returns a list of all loaded Erlang modules (current and old code), including preloaded modules.

Returns true if the module Module is loaded as current code; otherwise, false. It does not attempt to load the module.

Returns a list of Erlang modules that are preloaded in the run-time system.

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.

Distributed Erlang

Forces the disconnection of a node.

Get distribution channel data from the local node that is to be passed to the remote node.

Returns the value of the get_size option on the distribution channel identified by DHandle. For more information see the documentation of the get_size option for the erlang:dist_ctrl_set_opt/3 function.

Register an alternate input handler process for the distribution channel identified by DHandle.

Deliver distribution channel data from a remote node to the local node.

Sets the value of the get_size option on the distribution channel identified by DHandle.

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.

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.

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 is started with

Monitor the status of the node Node. If Flag is true, monitoring is turned on. If Flag is false, monitoring is turned off.

Behaves as monitor_node/2 except that it allows an extra option to be specified, namely allow_passive_connect.

Returns the name of the local node.

Returns a list of all nodes connected to this node through normal connections (that is, hidden nodes are not listed). Same as nodes(visible).

Returns a list of nodes according to the argument specified. The returned result, when the argument is a list, is the list of nodes satisfying the disjunction(s) of the list elements.

Returns a list of NodeInfo tuples.

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.

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.

Erlang Terms

Returns an integer or float representing the absolute value of Float or Int.

Returns a new tuple that has one element more than Tuple1, and contains the elements in Tuple1 followed by Term as the last element.

Returns a binary corresponding to the text representation of Atom.

Returns a list of unicode code points corresponding to the text representation of Atom.

Extracts the part of the binary described by Start and Length.

Returns the atom whose text representation is Binary, creating a new atom if necessary.

Returns the atom whose text representation is Binary provided that such atom already exists.

Returns the float whose text representation is Binary.

Returns an integer whose text representation is Binary.

Returns an integer whose text representation in base Base is Binary.

Returns a list of integers corresponding to the bytes of Binary.

As binary_to_list/1, but returns a list of integers corresponding to the bytes from position Start to position Stop in Binary.

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

Returns an integer that is the size in bits of Bitstring.

Returns a list of integers corresponding to the bytes of Bitstring.

Returns an integer that is the number of bytes needed to contain Bitstring.

Returns the smallest integer not less than Number.

Decodes the binary Bin according to the packet protocol specified by Type, similar to the packet handling done by sockets with the {packet,Type} option.

Returns a new tuple with element at Index removed from tuple Tuple1.

Prints a text representation of Term on the standard output.

Returns the Nth element (numbering from 1) of Tuple.

Calculates, without doing the encoding, the maximum byte size for a term encoded in the Erlang external term format.

Calculates, without doing the encoding, the maximum byte size for a term encoded in the Erlang external term format.

Returns a float by converting Number to a float.

Returns a binary corresponding to the text representation of Float using fixed decimal point formatting.

Returns a string corresponding to the text representation of Float using fixed decimal point formatting.

Returns the largest integer not greater than Number.

Returns a list with information about the fun Fun.

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

Returns String that represents the code that created Fun.

Returns the first element of List.

Returns a new tuple with element Term inserted at position Index in tuple Tuple1.

Returns a binary corresponding to the text representation of Integer.

Returns a binary corresponding to the text representation of Integer in base Base.

Returns a string corresponding to the text representation of Integer.

Returns a string corresponding to the text representation of Integer in base Base.

Returns a binary constructed from the integers and binaries in IoListOrBinary.

Returns an iovec that is made from the integers and binaries in IoListOrBinary.

Returns true if Term is an atom; otherwise, returns false.

Returns true if Term is a binary; otherwise, returns false.

Returns true if Term is a bitstring (including a binary); otherwise, returns false.

Returns true if Term is the atom true or false; otherwise, returns false.

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

Returns true if Term is a fun; otherwise, returns false.

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

Returns true if Term is an integer; otherwise, returns false.

Returns true if Term is a list with zero or more elements; otherwise, returns false.

Returns true if Term is a map; otherwise, returns false.

Returns true if map Map contains Key and returns false if it does not contain the Key.

Returns true if Term is an integer or a floating point number; otherwise, returns false.

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

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

Returns true if Term is a tuple and its first element is RecordTag; otherwise, returns false.

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

Returns true if Term is a reference; otherwise, returns false.

Returns true if Term is a tuple; otherwise, returns false.

Returns the length of List.

Returns the atom whose text representation is String, creating a new atom if necessary.

Returns a binary made from the integers and binaries in IoList.

Returns a bitstring made from the integers and bitstrings in BitstringList.

Returns the atom whose text representation is String, but only if there already exists such atom.

Returns the float whose text representation is String.

Returns an integer whose text representation is String.

Returns an integer whose text representation in base Base is String.

Returns a process identifier whose text representation is a String.

Returns a port identifier whose text representation is a String.

Returns a reference whose text representation is a String.

Returns a tuple whose elements are the elements of List.

Creates a new tuple of the specified Arity, where all elements are InitialValue.

Creates a tuple of size Arity, where each element has value DefaultValue, and then fills in values from InitList.

Returns value Value associated with Key if Map contains Key.

Returns the number of key-value pairs in Map.

Returns the largest of Term1 and Term2.

Returns the smallest of Term1 and Term2.

Returns the node where Arg originates.

Returns a hash value for Term.

Returns a string corresponding to the text representation of Pid.

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

Returns a string corresponding to the text representation of Ref.

Returns an integer by rounding Number to the nearest integer.

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.

Returns the number of elements in a tuple or the number of bytes in a binary or bitstring.

Returns a tuple containing the binaries that are the result of splitting Bin into two parts at position Pos.

Returns a binary data object that is the result of encoding Term according to the Erlang external term format.

Returns the encoding of Term according to the Erlang external term format as ext_iovec/0.

Returns the encoding of Term according to the Erlang external term format as ext_iovec/0.

Returns the tail of List, which is the list without its first element.

Truncates the decimals of Number.

Returns the number of elements in Tuple.

Returns a list corresponding to Tuple.

Processes and Ports

Create an alias which can be used when sending messages to the process that created the alias. When the alias has been deactivated, messages sent using the alias will be dropped. An alias can be deactivated using unalias/1.

Calls a fun, passing the elements in Args as arguments.

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.

This implementation-dependent function increments the reduction counter for the calling process.

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.

The returned value is true unless info is part of OptionList.

Returns the process dictionary and deletes it.

Returns the value Val associated with Key and deletes it from the process dictionary. Returns undefined if no value is associated with Key.

Raises an exception of class error with the reason Reason.

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.

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.

Raises an exception of class exit with exit reason Reason.

Sends an exit signal with exit reason Reason to the process or port identified by Dest. If Dest is a reference, the exit signal will only affect the identified process if the reference is an active process alias of a process executing on an OTP 28.0 node or newer.

Provides an option list for modification of the functionality provided by the exit/2 BIF. The Dest and Reason arguments has the same meaning as when passed to the exit/2 BIF.

Forces an immediate garbage collection of the executing process.

Garbage collects the node local process identified by Pid.

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

Returns the value Val associated with Key in the process dictionary, or undefined if Key does not exist.

Returns a list of all keys present in the process dictionary. The items in the returned list can be in any order.

Returns a list of keys that are associated with the value Val in the process dictionary. The items in the returned list can be in any order.

Returns the process identifier of the group leader for the process evaluating the function.

Sets the group leader of Pid to GroupLeader. Typically, this is used when a process started from a certain shell is to have another group leader than init.

Puts the calling process into a wait state where its memory allocation has been reduced as much as possible. This is useful if the process does not expect to receive any messages soon.

Puts the calling process into a wait state where its memory allocation has been reduced as much as possible. This is useful if the process does not expect to receive any messages soon.

Pid must refer to a process at the local node.

Sets up and activates a link between the calling process and another process or a port identified by PidOrPort.

Provides an option list for modification of the link functionality provided by link/1. The PidOrPort argument has the same meaning as when passed to link/1.

Sends a monitor request of type Type to the entity identified by Item.

Provides an option list for modification of monitoring functionality provided by monitor/2. The Type and Item arguments have the same meaning as when passed to monitor/2.

Works exactly like error/1, but Dialyzer thinks that this BIF will return an arbitrary term. When used in a stub function for a NIF to generate an exception when the NIF library is not loaded, Dialyzer does not generate false warnings.

Works exactly like error/2, but Dialyzer thinks that this BIF will return an arbitrary term. When used in a stub function for a NIF to generate an exception when the NIF library is not loaded, Dialyzer does not generate false warnings.

Returns a port identifier as the result of opening a new Erlang port. A port can be seen as an external Erlang process.

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.

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

Sends data to a port. Same as Port ! {PortOwner, {command, Data}} except for the error behavior and being synchronous (see below).

Sets the port owner (the connected port) to Pid. Roughly the same as Port ! {Owner, {connect, Pid}} except for the following

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.

Returns a list containing tuples with information about Port, or undefined if the port is not open.

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

Sets the process flag indicated to the specified value. Returns the previous value of the flag.

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.

Returns a list containing InfoTuples with miscellaneous information about the process identified by Pid, or undefined if the process is not alive.

Returns information about the process identified by Pid, as specified by Item or ItemList. Returns undefined if the process is not alive.

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

Returns a 2-tuple, consisting of one process identifier and a new processes iterator. If the process iterator has run out of processes in the process table, none will be returned.

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.

Raises an exception of the specified class, reason, and call stack backtrace (stacktrace).

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 identifies as an argument.

Returns a list of names that have been registered using register/2.

Decreases the suspend count on the process identified by Suspendee.

Returns the process identifier of the calling process.

Sends a message and returns Msg. This is the same as using the send operator: Dest ! Msg.

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.

Send a message without suspending the caller.

Returns the process identifier of a new process started by the application of Fun to the empty list []. Otherwise works like spawn/3.

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.

Returns the process identifier of a new process started by the application of Module:Function to Args.

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.

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.

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.

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.

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.

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.

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.

A new process is started by the application of Module:Function to Args. The process is monitored at the same time. Returns the process identifier and a reference for the monitor. Otherwise works like spawn/3.

A new process is started by the application of Module:Function to Args on the node Node. The process is monitored at the same time. Returns the process identifier and a reference for the monitor. Otherwise works like spawn/3.

Returns the process identifier (pid) of a new process started by the application of Fun to the empty list []. Otherwise works like spawn_opt/4.

Returns the process identifier (pid) 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_opt/4.

Works as spawn/3, except that an extra option list is specified when creating the process.

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_opt/4.

Asynchronously send a spawn request. Returns a request identifier ReqId.

Abandon a previously issued spawn request. ReqId corresponds to a request identifier previously returned by spawn_request() in a call from current process. That is, only the process that has made the request can abandon the request.

Increases the suspend count on the process identified by Suspendee and puts it in the suspended state if it is not already in that state. A suspended process is not scheduled for execution until the process has been resumed. If the suspended process currently is waiting in a receive ... after expression, the timer for the timeout will, as of OTP 28.0, also be suspended until the process is resumed.

Raises an exception of class throw. Intended to be used to do non-local returns from functions.

Deactivate the alias Alias previously created by the calling process.

Removes a link between the calling process and another process or a port identified by Id.

Returns the process identifier or port identifier with the registered name RegName from the name registry. Returns undefined if the name is not registered.

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.

System

Returns a list with information about memory dynamically allocated by the Erlang emulator.

Returns the memory size in bytes allocated for memory of type Type. The argument can also be specified as a list of memory_type/0 atoms, in which case a corresponding list of {memory_type(), Size :: integer >= 0} tuples is returned.

Returns statistics about the current system.

Sets a system flag to the given value.

Returns the current system monitoring settings set by erlang:system_monitor/2 as {MonitorPid, Options}, or undefined if no settings exist.

When called with argument undefined, all system performance monitoring settings are cleared.

Sets the system event monitoring options. MonitorPid is a local process identifier (pid) receiving system monitor messages.

Returns the current system profiling settings set by erlang:system_profile/2 as {ProfilerPid, Options}, or undefined if there are no settings. The order of the options can be different from the one that was set.

Sets system profiler options. ProfilerPid is a local process identifier (pid) or port receiving profiling messages. The receiver is excluded from all profiling. The second argument is a list of profiling options

Time and timers

Equivalent to erlang:cancel_timer(TimerRef, []).

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

Returns the current date as {Year, Month, Day}.

Returns the current local date and time, {{Year, Month, Day}, {Hour, Minute, Second}}.

Converts local date and time to Universal Time Coordinated (UTC), if supported by the underlying OS. Otherwise no conversion is done and Localtime is returned.

Equivalent to erlang:read_timer(TimerRef, []).

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.

Equivalent to erlang:send_after(Time, Dest, Msg, []).

Starts a timer. When the timer expires, the message Msg is sent to the process identified by Dest. Apart from the format of the time-out message, this function works exactly as erlang:start_timer/4.

Equivalent to erlang:start_timer(Time, Dest, Msg, []).

Starts a timer. When the timer expires, the message {timeout, TimerRef, Msg} is sent to the process identified by Dest.

Returns the current time as {Hour, Minute, Second}.

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.

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.

Tracing

Turn on or off trace flags on processes or ports for the static legacy trace session.

Calling this function makes sure all trace messages have been delivered.

Returns trace information about a port, process, function, or event for the static legacy trace session.

Set trace pattern for call, send and receive tracing on the static legacy trace session.

Predefined datatypes

The empty list/0.

All possible Erlang terms. Synonym for term/0.

-type arity() :: arity().

The arity of a function or type.

An Erlang atom.

-type binary() :: <<_:_*8>>.

An Erlang binary, that is, a bitstring with a size divisible by 8.

-type bitstring() :: <<_:_*1>>.

An Erlang bitstring.

-type boolean() :: true | false.

A boolean value.

A byte of data represented by an integer.

-type char() :: 0..1114111.

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

The dynamic type, which represents a statically unknown type

-type float() :: float().

An Erlang float.

-type function() :: fun().

An Erlang fun.

An unique identifier for some entity, for example a process, port or monitor.

An Erlang integer.

A binary or list containing bytes and/or iodata.

This datatype is used to represent data that is meant to be output using any I/O module. For example: file:write/2 or gen_tcp:send/2.

To convert an iodata/0 term to binary/0 you can use iolist_to_binary/2. To transcode a string/0 or unicode:chardata/0 to iodata/0 you can use unicode:characters_to_binary/1.

A list containing bytes and/or iodata.

This datatype is used to represent data that is meant to be output using any I/O module. For example: file:write/2 or gen_tcp:send/2.

In most use cases you want to use iodata/0 instead of this type.

An Erlang list containing terms of any type.

-type list(ContentType) :: [ContentType].

An Erlang list containing terms of the type ContentType.

-type map() :: #{any() => any()}.

An Erlang map containing any number of key and value associations.

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

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

A three-tuple representing a Module:Function/Arity function signature.

-type module() :: atom().

An Erlang module represented by an atom.

A negative integer.

-type no_return() :: none().

The type used to show that a function will never return a value, that is it will always throw an exception.

An Erlang node represented by an atom.

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

This type is used to show that a function will never return a value; that is it will always throw an exception.

In a spec, use no_return/0 for the sake of clarity.

-type nonempty_binary() :: <<_:8, _:_*8>>.

A binary/0 that contains some data.

-type nonempty_bitstring() :: <<_:1, _:_*1>>.

A bitstring/0 that contains some data.

-type nonempty_improper_list(ContentType, TerminationType) ::
          nonempty_improper_list(ContentType, TerminationType).

A maybe_improper_list/2 that contains some items.

-type nonempty_list() :: [any(), ...].

A list/0 that contains some items.

-type nonempty_list(ContentType) :: [ContentType, ...].

A list(ContentType) that contains some items.

A maybe_improper_list/0 that contains some items.

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

-type nonempty_string() :: [char(), ...].

A string/0 that contains some characters.

An Erlang number.

An Erlang process identifier.

An Erlang port identifier.

An integer greater than zero.

An Erlang reference.

-type string() :: [char()].

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

All possible Erlang terms. Synonym for any/0.

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

-type tuple() :: tuple().

An Erlang tuple.

Types
-type cpu_topology() :: [LevelEntry :: level_entry()] | undefined.

The current cpu topology.

node refers to Non-Uniform Memory Access (NUMA) nodes. thread refers to hardware threads (for example, Intel hyper-threads).

A level in term CpuTopology can be omitted if only one entry exists and InfoList is empty.

thread can only be a sublevel to core. core can be a sublevel to processor or node. processor can be on the top level or a sublevel to node. node can be on the top level or a sublevel to processor. That is, NUMA nodes can be processor internal or processor external. A CPU topology can consist of a mix of processor internal and external NUMA nodes, as long as each logical CPU belongs to one NUMA node. Cache hierarchy is not part of the CpuTopology type, but will be in a future release. Other things can also make it into the CPU topology in a future release. So, expect the CpuTopology type to change.

-type deprecated_time_unit() :: seconds | milli_seconds | micro_seconds | nano_seconds.

The time_unit/0 type also consist of the following deprecated symbolic time units:

An opaque handle identifying a distribution channel.

-type ext_binary() :: binary().

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

-type ext_iovec() :: iovec().

A term of type iovec/0, structured according to the Erlang external term format.

-type fun_info_item() :: arity | env | index | name | module | new_index | new_uniq | pid | type | uniq.

A list with the system wide garbage collection defaults.

-type halt_options() :: [{flush, boolean()} | {flush_timeout, Timeout :: 0..2147483647 | infinity}].

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

-type level_tag() :: core | node | processor | thread.
-type link_option() :: priority.

See link/2.

Since OTP 28.0"

-type match_variable() :: atom().

Process max heap size configuration. For more info see process_flag(max_heap_size, MaxHeapSize)

-type memory_type() ::
          total | processes | processes_used | system | atom | atom_used | binary | code | ets.
-type message_queue_data() :: off_heap | on_heap.

See process_flag(message_queue_data, MQD).

Process message queue data configuration. For more information, see process_flag(message_queue_data, MQD)

-type monitor_option() ::
          {alias, explicit_unalias | demonitor | reply_demonitor} | {tag, term()} | priority.

See monitor/3.

An opaque handle identifying a NIF resource object .

-type priority_level() :: low | normal | high | max.

Process priority level. For more info see process_flag(priority, Level)

-type process_info_item() ::
          async_dist | backtrace | binary | catchlevel | current_function | current_location |
          current_stacktrace | dictionary |
          {dictionary, Key :: term()} |
          error_handler | garbage_collection | garbage_collection_info | group_leader | heap_size |
          initial_call | links | label | last_calls | memory | message_queue_len | messages |
          min_heap_size | min_bin_vheap_size | monitored_by | monitors | message_queue_data | parent |
          priority | priority_messages | reductions | registered_name | sequential_trace_token |
          stack_size | status | suspending | total_heap_size | trace | trap_exit.
-type process_info_result_item() ::
          {async_dist, Enabled :: boolean()} |
          {backtrace, Bin :: binary()} |
          {binary, BinInfo :: [{non_neg_integer(), non_neg_integer(), non_neg_integer()}]} |
          {catchlevel, CatchLevel :: non_neg_integer()} |
          {current_function, {Module :: module(), Function :: atom(), Arity :: arity()} | undefined} |
          {current_location,
           {Module :: module(),
            Function :: atom(),
            Arity :: arity(),
            Location :: [{file, Filename :: string()} | {line, Line :: pos_integer()}]}} |
          {current_stacktrace, Stack :: [stack_item()]} |
          {dictionary, Dictionary :: [{Key :: term(), Value :: term()}]} |
          {{dictionary, Key :: term()}, Value :: term()} |
          {error_handler, Module :: module()} |
          {garbage_collection, GCInfo :: [{atom(), non_neg_integer()}]} |
          {garbage_collection_info, GCInfo :: [{atom(), non_neg_integer()}]} |
          {group_leader, GroupLeader :: pid()} |
          {heap_size, Size :: non_neg_integer()} |
          {initial_call, mfa()} |
          {links, PidsAndPorts :: [pid() | port()]} |
          {label, term()} |
          {last_calls, false | (Calls :: [mfa()])} |
          {memory, Size :: non_neg_integer()} |
          {message_queue_len, MessageQueueLen :: non_neg_integer()} |
          {messages, MessageQueue :: [term()]} |
          {min_heap_size, MinHeapSize :: non_neg_integer()} |
          {min_bin_vheap_size, MinBinVHeapSize :: non_neg_integer()} |
          {max_heap_size, MaxHeapSize :: max_heap_size()} |
          {monitored_by, MonitoredBy :: [pid() | port() | nif_resource()]} |
          {monitors,
           Monitors :: [{process | port, Pid :: pid() | port() | {RegName :: atom(), Node :: node()}}]} |
          {message_queue_data, MQD :: message_queue_data()} |
          {parent, pid() | undefined} |
          {priority, Level :: priority_level()} |
          {priority_messages, Enabled :: boolean()} |
          {reductions, Number :: non_neg_integer()} |
          {registered_name, [] | (Atom :: atom())} |
          {sequential_trace_token, [] | (SequentialTraceToken :: term())} |
          {stack_size, Size :: non_neg_integer()} |
          {status, Status :: exiting | garbage_collecting | waiting | running | runnable | suspended} |
          {suspending,
           SuspendeeList ::
               [{Suspendee :: pid(),
                 ActiveSuspendCount :: non_neg_integer(),
                 OutstandingSuspendCount :: non_neg_integer()}]} |
          {total_heap_size, Size :: non_neg_integer()} |
          {trace, InternalTraceFlags :: non_neg_integer()} |
          {trap_exit, Boolean :: boolean()}.
-opaque processes_iter_ref()

A extended stacktrace/0 that can be passed to raise/3.

-type registered_name() :: atom().
-type scheduler_bind_type() ::
          no_node_processor_spread | no_node_thread_spread | no_spread | processor_spread | spread |
          thread_spread | thread_no_node_processor_spread | unbound.

The requested scheduler bind type.

The destination for a send operation.

This can 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.

Options for spawn_opt().

An Erlang stacktrace as described by Errors and Error Handling section in the Erlang Reference Manual.

-type system_profile_option() ::
          exclusive | runnable_ports | runnable_procs | scheduler | timestamp | monotonic_timestamp |
          strict_monotonic_timestamp.

The time unit used by erlang time APIs.

Supported time unit representations:

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

See erlang:timestamp/0.

-type 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()}.
-type 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.
-type trace_info_item_result() ::
          {traced, global | local | false | undefined} |
          {match_spec, trace_match_spec() | false | undefined} |
          {meta, pid() | port() | false | undefined | []} |
          {meta, module(), term()} |
          {meta_match_spec, trace_match_spec() | false | undefined} |
          {call_count, non_neg_integer() | boolean() | undefined} |
          {call_time | call_memory,
           [{pid(), non_neg_integer(), non_neg_integer(), non_neg_integer()}] | boolean() | undefined}.
-type trace_pattern_flag() ::
          global | local | meta |
          {meta, Pid :: pid()} |
          {meta, TracerModule :: module(), TracerState :: term()} |
          call_count | call_time | call_memory.
-type trace_pattern_mfa() :: {atom(), atom(), arity() | '_'} | on_load.
Checksum

Computes and returns the adler32 checksum for Data.

Continues computing the adler32 checksum by combining the previous checksum, OldAdler, with the checksum of Data.

The following code:

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

assigns the same value to Y as this:

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

Combines two previously computed adler32 checksums.

This computation requires the size of the data object for the second checksum to be known.

The following code:

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

assigns the same value to Z as this:

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

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

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

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)).
-spec md5(Data) -> Digest when Data :: iodata(), Digest :: binary().

Computes an MD5 message digest from Data, where the length of the digest is 128 bits (16 bytes). Data is a binary or a list of small integers and binaries.

For more information about MD5, see RFC 1321 - The MD5 Message-Digest Algorithm.

Warning

The MD5 Message-Digest Algorithm is not considered safe for code-signing or software-integrity purposes.

-spec md5_final(Context) -> Digest when Context :: binary(), Digest :: binary().

Finishes the update of an MD5 Context and returns the computed MD5 message digest.

-spec md5_init() -> Context when Context :: binary().

Creates an MD5 context, to be used in the following calls to md5_update/2.

-spec md5_update(Context, Data) -> NewContext
                    when Context :: binary(), Data :: iodata(), NewContext :: binary().

Update an MD5 Context with Data and returns a NewContext.

Code
-spec check_old_code(Module) -> boolean() when Module :: module().

Returns true if Module has old code, otherwise false.

See also code.

-spec check_process_code(Pid, Module) -> CheckResult
                            when Pid :: pid(), Module :: module(), CheckResult :: boolean().

Equivalent to check_process_code(Pid, Module, []).

-spec check_process_code(Pid, Module, OptionList) -> CheckResult | async
                            when
                                Pid :: pid(),
                                Module :: module(),
                                RequestId :: term(),
                                Option :: {async, RequestId} | {allow_gc, boolean()},
                                OptionList :: [Option],
                                CheckResult :: boolean() | aborted.

Checks if the node local process identified by Pid executes old code for Module.

Options:

If Pid equals self/0, 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:

Change

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.

Failures:

-spec delete_module(Module) -> true | undefined when 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) and is not to be used elsewhere.

Failure: badarg if there already is an old version of Module.

-spec function_exported(Module, Function, Arity) -> boolean()
                           when Module :: module(), Function :: atom(), Arity :: arity().

Returns true if the module Module is current and contains an exported function Function/Arity, or if there is a BIF (a built-in function implemented in C) with the specified name, otherwise returns false.

-spec is_builtin(Module, Function, Arity) -> boolean()
                    when Module :: module(), Function :: atom(), Arity :: arity().

This BIF is useful for builders of cross-reference tools.

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

-spec load_module(Module, Binary) -> {module, Module} | {error, Reason}
                     when
                         Module :: module(),
                         Binary :: binary(),
                         Reason :: badfile | not_purged | on_load | {features_not_allowed, [atom()]}.

Loads Module described by the object code contained within Binary.

If the code for module Module already exists, all export references are replaced so they point to the newly loaded code. The previously loaded code is kept in the system as old code, as there can still be processes executing that code.

Returns either {module, Module}, or {error, Reason} if loading fails. Reason is one of the following:

Warning

This BIF is intended for the code server (see code) and is not to be used elsewhere.

-spec load_nif(Path, LoadInfo) -> ok | Error
                  when
                      Path :: string(),
                      LoadInfo :: term(),
                      Error :: {error, {Reason, Text :: string()}},
                      Reason :: load_failed | bad_lib | load | reload | upgrade | old_code.

Loads and links a dynamic library containing native implemented functions (NIFs) for a module.

Path is a file path to the shareable object/dynamic library file minus the OS-dependent file extension (.so for Unix and .dll for Windows). Notice that on most OSs the library has to have a different name on disc when an upgrade of the nif is done. If the name is the same, but the contents differ, the old library may be loaded instead. For information on how to implement a NIF library, see erl_nif(3).

LoadInfo can be any term. It is passed on to the library as part of the initialization. A good practice is to include a module version number to support future code upgrade scenarios.

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 the following atoms while Text is a human readable string that can give more information about the failure:

If the -nifs() attribute is used (which is recommended), all NIFs in the dynamic library must be declared as such for load_nif/2 to succeed. On the other hand, all functions declared with the -nifs() attribute do not have to be implemented by the dynamic library. This allows a target independent Erlang file to contain fallback implementations for functions that may lack NIF support depending on target OS/hardware platform.

-spec loaded() -> [Module] when Module :: module().

Returns a list of all loaded Erlang modules (current and old code), including preloaded modules.

See also code.

-spec module_loaded(Module) -> boolean() when Module :: module().

Returns true if the module Module is loaded as current code; otherwise, false. It does not attempt to load the module.

-spec pre_loaded() -> [module()].

Returns a list of Erlang modules that are preloaded in the run-time 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.

-spec purge_module(Module) -> true when 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) and is not to be used elsewhere.

Change

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.

Distributed Erlang
-spec disconnect_node(Node) -> boolean() | ignored when Node :: node().

Forces the disconnection of a node.

Doing this makes it appears to the node Node as if the local node has crashed. This BIF is mainly used in the Erlang network authentication protocols.

Returns true if disconnection succeeds, otherwise false. If the local node is not alive, ignored is returned.

Note

This function may return before nodedown messages have been delivered.

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.

-spec dist_ctrl_get_data_notification(DHandle) -> ok when DHandle :: dist_handle().

Request notification when more data is available to fetch using erlang:dist_ctrl_get_data(DHandle) for the distribution channel identified by DHandle.

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.

-spec dist_ctrl_get_opt(DHandle, get_size) -> Value when DHandle :: dist_handle(), Value :: boolean().

Returns the value of the get_size option on the distribution channel identified by DHandle. For more information see the documentation of the get_size option for the erlang:dist_ctrl_set_opt/3 function.

Note

Only the process registered as distribution controller for the distribution channel identified by DHandle is allowed to call this function.

This function is used when implementing an alternative distribution carrier using processes as distribution controllers. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module.

-spec dist_ctrl_input_handler(DHandle, InputHandler) -> ok
                                 when DHandle :: dist_handle(), InputHandler :: pid().

Register an alternate input handler process for the distribution channel identified by DHandle.

Once this function has been called, InputHandler is the only process allowed to call erlang:dist_ctrl_put_data(DHandle, Data) with the DHandle identifying this distribution channel.

Note

When the distribution controller for the distribution channel identified by DHandle is a process, it is the only process allowed to call this function. This function is also allowed to be called when the distribution controller for the distribution channel identified by DHandle is a port. The data received by the port should in this case be delivered to the process identified by InputHandler which in turn should call erlang:dist_ctrl_put_data/2.

This function is used when implementing an alternative distribution carrier. DHandle is retrieved via the callback f_handshake_complete. More information can be found in the documentation of ERTS User's Guide ➜ How to implement an Alternative Carrier for the Erlang Distribution ➜ Distribution Module.

-spec dist_ctrl_put_data(DHandle, Data) -> ok when DHandle :: dist_handle(), Data :: iodata().

Deliver distribution channel data from a remote node to the local node.

Note

Only the process registered as distribution controller for the distribution channel identified 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. 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.

-spec dist_ctrl_set_opt(DHandle, get_size, Value) -> OldValue
                           when DHandle :: dist_handle(), Value :: boolean(), OldValue :: boolean().

Sets the value of the get_size option on the distribution channel identified by DHandle.

This option controls the return value of calls to erlang:dist_ctrl_get_data(DHandle) where DHandle equals DHandle used when setting this option. When the get_size option is:

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.

-spec get_cookie() -> Cookie | nocookie when Cookie :: atom().

Returns the magic cookie of the local node if the node is alive, otherwise the atom nocookie. This value is set by set_cookie/1.

-spec get_cookie(Node) -> Cookie | nocookie when Node :: node(), Cookie :: atom().

Returns the magic cookie for node Node if the local node is alive, otherwise the atom nocookie. This value is set by set_cookie/2.

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 is started with:

  1. "erl -name LONGNAME" or,
  2. "erl -sname SHORTNAME".

A node can also be alive if it has got a name from a call to net_kernel:start/2 and has not been stopped by a call to net_kernel:stop/0.

-spec monitor_node(Node, Flag) -> true when Node :: node(), Flag :: boolean().

Monitor the status of the node Node. If Flag is true, monitoring is turned on. If Flag is false, monitoring is turned off.

Making several calls to monitor_node(Node, true) for the same Node is not an error; it results in as many independent monitoring instances.

If Node fails or does not exist, the message {nodedown, Node} is delivered to the process. If a process has made two calls to monitor_node(Node, true) and Node terminates, two nodedown messages are delivered to the process. If there is no connection to Node, an attempt is made to create one. If this fails, a nodedown message is delivered.

The delivery of the nodedown signal is not ordered with respect to other link or monitor signals from the node that goes down. If you need a guarantee that all signals from the remote node has been delivered before the nodedown signal is sent, you should use net_kernel:monitor_nodes/1.

Nodes connected through hidden connections can be monitored as any other nodes.

Failure: notalive if the local node is not alive.

-spec monitor_node(Node, Flag, Options) -> true
                      when
                          Node :: node(),
                          Flag :: boolean(),
                          Options :: [Option],
                          Option :: allow_passive_connect.

Behaves as monitor_node/2 except that it allows an extra option to be specified, namely allow_passive_connect.

This option allows the BIF to wait the normal network connection time-out for the monitored node to connect itself, even if it cannot be actively connected from this node (that is, it is blocked). The state where this can be useful can only be achieved by using the Kernel option dist_auto_connect once. If that option is not used, option allow_passive_connect has no effect.

Note

Option allow_passive_connect is used internally and is seldom needed in applications where the network topology and the Kernel options in effect are known in advance.

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

-spec node() -> Node when Node :: node().

Returns the name of the local node.

If the node is not alive, nonode@nohost is returned.

Examples
> node().
nonode@nohost
-spec nodes() -> Nodes when Nodes :: [node()].

Returns a list of all nodes connected to this node through normal connections (that is, hidden nodes are not listed). Same as nodes(visible).

-spec nodes(Arg) -> Nodes
               when
                   Arg :: NodeType | [NodeType],
                   NodeType :: visible | hidden | connected | this | known,
                   Nodes :: [node()].

Returns a list of nodes according to the argument specified. The returned result, when the argument is a list, is the list of nodes satisfying the disjunction(s) of the list elements.

NodeTypes:

Some equalities: [node()] = nodes(this), nodes(connected) = nodes([visible, hidden]), and nodes() = nodes(visible).

-spec nodes(Arg, InfoOpts) -> [NodeInfo]
               when
                   NodeType :: visible | hidden | connected | this | known,
                   Arg :: NodeType | [NodeType],
                   InfoOpts :: #{connection_id => boolean(), node_type => boolean()},
                   NodeTypeInfo :: visible | hidden | this | known,
                   ConnectionId :: undefined | integer(),
                   Info :: #{connection_id => ConnectionId, node_type => NodeTypeInfo},
                   NodeInfo :: {node(), Info}.

Returns a list of NodeInfo tuples.

The first element is the node name. Nodes to be included in the list are determined by the first argument Arg in the same way as for nodes(Arg). The second element of NodeInfo tuples is a map containing further information about the node identified by the first element. The information present in this map is determined by the InfoOpts map passed as the second argument. Currently the following associations are allowed in the InfoOpts map:

Example:

(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>
-spec set_cookie(Cookie) -> true when Cookie :: atom().

Sets the magic cookie of the local node to the atom Cookie, which is also the cookie for all nodes that have no explicit cookie set with set_cookie/2 Cookie.

See section Distributed Erlang in the Erlang Reference Manual in System Documentation for more information.

You can get this value using get_cookie/0.

Failure: function_clause if the local node is not alive.

-spec set_cookie(Node, Cookie) -> true when Node :: node(), Cookie :: atom().

Sets the magic cookie for Node to the atom Cookie. If Node is the local node, the function sets the cookie of all other nodes (that have no explicit cookie set with this function) to Cookie.

See section Distributed Erlang in the Erlang Reference Manual in System Documentation for more information.

You can get this value using get_cookie/1.

Failure: function_clause if the local node is not alive.

Erlang Terms

Returns an integer or float representing the absolute value of Float or Int.

Examples
1> abs(-3.33).
3.33
2> abs(-3).
3
3> abs(5).
5
-spec append_element(Tuple1, Term) -> Tuple2 when Tuple1 :: tuple(), Tuple2 :: tuple(), Term :: term().

Returns a new tuple that has one element more than Tuple1, and contains the elements in Tuple1 followed by Term as the last element.

Semantically equivalent to list_to_tuple(tuple_to_list(Tuple1) ++ [Term]), but faster.

Examples
1> erlang:append_element({one, two}, three).
{one,two,three}
-spec atom_to_binary(Atom) -> binary() when Atom :: atom().

Equivalent to atom_to_binary(Atom, utf8).

-spec atom_to_binary(Atom, Encoding) -> binary()
                        when Atom :: atom(), Encoding :: latin1 | unicode | utf8.

Returns a binary corresponding to the text representation of Atom.

If Encoding is latin1, each character in the text representation is stored as a single byte. If Encoding is utf8 or unicode, the characters are encoded using UTF-8, where some characters may require multiple bytes.

Change

As from Erlang/OTP 20, atoms can contain any Unicode character and atom_to_binary(Atom, latin1) may fail if the text representation for Atom contains a Unicode character > 255.

Examples
1> atom_to_binary('Erlang', latin1).
<<"Erlang">>
2> atom_to_binary('π', unicode).
<<207,128>>
3> atom_to_binary('π', latin1).
** exception error: bad argument
     in function  atom_to_binary/2
        called as atom_to_binary('π',latin1)
        *** argument 1: contains a character not expressible in latin1
-spec atom_to_list(Atom) -> string() when Atom :: atom().

Returns a list of unicode code points corresponding to the text representation of Atom.

See the unicode module for instructions on converting the resulting list into different formats.

Examples
1> atom_to_list('Erlang').
"Erlang"
2> atom_to_list('π').
[960]
3> atom_to_list('你好').
[20320,22909]

Equivalent to binary_part(Subject, Start, Length).

Extracts the part of the binary described by Start and Length.

A negative length can be used to extract bytes at the end of a binary.

Start is zero-based.

Failure: badarg if Start and Length in any way reference outside the binary.

For details about the semantics of Start and Length, see binary:part/3.

Examples
1> Bin = <<1,2,3,4,5,6,7,8,9,10>>.
2> binary_part(Bin, 0, 2).
<<1,2>>
3> binary_part(Bin, 2, 3).
<<3,4,5>>
4> binary_part(Bin, byte_size(Bin), -5).
<<6,7,8,9,10>>
-spec binary_to_atom(Binary) -> atom() when Binary :: binary().

Equivalent to binary_to_atom(Binary, utf8).

-spec binary_to_atom(Binary, Encoding) -> atom()
                        when Binary :: binary(), Encoding :: latin1 | unicode | utf8.

Returns the atom whose text representation is Binary, creating a new atom if necessary.

If Encoding is utf8 or unicode, the binary must contain valid UTF-8 sequences.

Note

Note that once an atom is created, it cannot be deleted. The Erlang system has a configurable limit on the number of atoms that can exist. To avoid reaching this limit, consider whether binary_to_existing_atom/2 is a better choice than binary_to_atom/2.

The number of characters that are permitted in an atom name is limited.

Change

As from Erlang/OTP 20, binary_to_atom(Binary, utf8) is capable of decoding any Unicode character. Earlier versions would fail if the binary contained Unicode characters > 255.

Examples
1> binary_to_atom(<<"Erlang">>, latin1).
'Erlang'
2> binary_to_atom(<<960/utf8>>, utf8).
'π'
-spec binary_to_existing_atom(Binary) -> atom() when Binary :: binary().

Equivalent to binary_to_existing_atom(Binary, utf8).

-spec binary_to_existing_atom(Binary, Encoding) -> atom()
                                 when Binary :: binary(), Encoding :: latin1 | unicode | utf8.

Returns the atom whose text representation is Binary provided that such atom already exists.

The Erlang system has a configurable limit for the total number of atoms that can exist. Once an atom is created, it cannot be deleted. Therefore, it is not safe to create many atoms from binaries that come from an untrusted source (for example, a file fetched from the Internet), for example, using binary_to_atom/2. This function is thus the appropriate option when the input binary comes from an untrusted source.

An atom exists in an Erlang system when included in a loaded Erlang module or when created programmatically (for example, by binary_to_atom/2). See the next note for an example of when an atom exists in the source code for an Erlang module but not in the compiled version of the same module.

Failure: badarg if the atom does not exist.

Note

Note that the compiler may optimize away atoms. For example, the compiler 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.

Note

The number of characters that are permitted in an atom name is limited. The default limits can be found in the Efficiency Guide (section System Limits).

Examples
1> binary_to_existing_atom(~"definitely_not_existing_at_all", utf8).
** exception error: bad argument
     in function  binary_to_existing_atom/2
        called as binary_to_existing_atom(<<"definitely_not_existing_at_all">>,utf8)
        *** argument 1: not an already existing atom
2> hello.
hello
3> binary_to_existing_atom(~"hello", utf8).
hello
-spec binary_to_float(Binary) -> float() when Binary :: binary().

Returns the float whose text representation is Binary.

The float string format is the same as the format for Erlang float literals, except that underscores are not permitted.

Failure: badarg if Binary contains an invalid representation of a float.

Examples
1> binary_to_float(~"10.5").
10.5
2> binary_to_float(~"17.0").
17.0
3> binary_to_float(<<"2.2017764e+1">>).
22.017764
-spec binary_to_integer(Binary) -> integer() when Binary :: binary().

Returns an integer whose text representation is Binary.

binary_to_integer/1 accepts the same string formats as list_to_integer/1.

Failure: badarg if Binary contains an invalid representation of an integer.

Examples
1> binary_to_integer(<<"123">>).
123
2> binary_to_integer(<<"-99">>).
-99
3> binary_to_integer(<<"+33">>).
33
-spec binary_to_integer(Binary, Base) -> integer() when Binary :: binary(), Base :: 2..36.

Returns an integer whose text representation in base Base is Binary.

Example
1> binary_to_integer(<<"3FF">>, 16).
1023
2> binary_to_integer(<<"101">>, 2).
5

binary_to_integer/2 accepts the same string formats as list_to_integer/2.

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

-spec binary_to_list(Binary) -> [byte()] when Binary :: binary().

Returns a list of integers corresponding to the bytes of Binary.

Examples
1> binary_to_list(<<1,2,3>>).
[1,2,3]

As binary_to_list/1, but returns a list of integers corresponding to the bytes from position Start to position Stop in Binary.

The positions in the binary are numbered starting from 1.

Note

The one-based indexing for binaries used by this function is deprecated. New code should use binary:bin_to_list/3. All functions in module binary consistently use zero-based indexing.

Examples
1> binary_to_list(~"abcdef", 2, 3).
"bc"

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

Warning

When decoding binaries from untrusted sources, the untrusted source may submit data in a way to create resources, such as atoms and remote references, that cannot be garbage collected and lead to a Denial of Service (DoS) attack. In such cases, use binary_to_term/2 with the safe option.

Examples
1> Bin = term_to_binary(hello).
<<131,119,5,104,101,108,108,111>>
2> hello = binary_to_term(Bin).
hello

See also term_to_binary/1 and binary_to_term/2.

-spec binary_to_term(Binary, Opts) -> term() | {term(), Used}
                        when
                            Binary :: ext_binary(),
                            Opt :: safe | used,
                            Opts :: [Opt],
                            Used :: pos_integer().

Equivalent to binary_to_term(Binary), but can be configured to fit special purposes.

The allowed options are:

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.

Returns an integer that is the size in bits of Bitstring.

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

Returns a list of integers corresponding to the bytes of Bitstring.

If the number of bits in the binary is not a multiple of 8, the last element of the list is a bitstring containing the remaining 1 to 7 bits.

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

Returns an integer that is the number of bytes needed to contain Bitstring.

If the number of bits in Bitstring is not a multiple of 8, the result is rounded up.

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

Returns the smallest integer not less than Number.

See also trunc/1.

Examples
1> ceil(5.5).
6
2> ceil(-2.3).
-2
3> ceil(10.0).
10
-spec decode_packet(Type, Bin, Options) -> {ok, Packet, Rest} | {more, Length} | {error, Reason}
                       when
                           Type ::
                               raw | 0 | 1 | 2 | 4 | asn1 | cdr | sunrm | fcgi | tpkt | line | http |
                               http_bin | httph | httph_bin,
                           Bin :: binary(),
                           Options :: [Opt],
                           Opt :: {packet_size, non_neg_integer()} | {line_length, non_neg_integer()},
                           Packet :: binary() | HttpPacket,
                           Rest :: binary(),
                           Length :: non_neg_integer() | undefined,
                           Reason :: term(),
                           HttpPacket :: HttpRequest | HttpResponse | HttpHeader | http_eoh | HttpError,
                           HttpRequest :: {http_request, HttpMethod, HttpUri, HttpVersion},
                           HttpResponse :: {http_response, HttpVersion, integer(), HttpString},
                           HttpHeader ::
                               {http_header,
                                integer(),
                                HttpField,
                                UnmodifiedField :: HttpString,
                                Value :: HttpString},
                           HttpError :: {http_error, HttpString},
                           HttpMethod ::
                               'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' |
                               HttpString,
                           HttpUri ::
                               '*' |
                               {absoluteURI,
                                http | https,
                                Host :: HttpString,
                                Port :: inet:port_number() | undefined,
                                Path :: HttpString} |
                               {scheme, Scheme :: HttpString, HttpString} |
                               {abs_path, HttpString} |
                               HttpString,
                           HttpVersion :: {Major :: non_neg_integer(), Minor :: non_neg_integer()},
                           HttpField ::
                               'Cache-Control' | 'Connection' | 'Date' | 'Pragma' |
                               'Transfer-Encoding' | 'Upgrade' | 'Via' | 'Accept' | 'Accept-Charset' |
                               'Accept-Encoding' | 'Accept-Language' | 'Authorization' | 'From' |
                               'Host' | 'If-Modified-Since' | 'If-Match' | 'If-None-Match' |
                               'If-Range' | 'If-Unmodified-Since' | 'Max-Forwards' |
                               'Proxy-Authorization' | 'Range' | 'Referer' | 'User-Agent' | 'Age' |
                               'Location' | 'Proxy-Authenticate' | 'Public' | 'Retry-After' | 'Server' |
                               'Vary' | 'Warning' | 'Www-Authenticate' | 'Allow' | 'Content-Base' |
                               'Content-Encoding' | 'Content-Language' | 'Content-Length' |
                               'Content-Location' | 'Content-Md5' | 'Content-Range' | 'Content-Type' |
                               'Etag' | 'Expires' | 'Last-Modified' | 'Accept-Ranges' | 'Set-Cookie' |
                               'Set-Cookie2' | 'X-Forwarded-For' | 'Cookie' | 'Keep-Alive' |
                               'Proxy-Connection' | HttpString,
                           HttpString :: string() | binary().

Decodes the binary Bin according to the packet protocol specified by Type, similar to the packet handling done by sockets with the {packet,Type} option.

If Bin contains an entire packet, it is returned along with the remainder of the binary as {ok,Packet,Rest}.

If Bin does not contain the entire packet, {more,Length} is returned. Length is either the expected total size of the packet or undefined if the expected packet size is unknown. decode_packet can then be called again with additional data.

If the packet does not conform to the protocol format, {error,Reason} is returned.

Types:

Options:

Examples
1> erlang:decode_packet(1, <<3,"abcd">>, []).
{ok,<<"abc">>,<<"d">>}
2> erlang:decode_packet(1, <<5,"abcd">>, []).
{more,6}
-spec delete_element(Index, Tuple1) -> Tuple2
                        when Index :: pos_integer(), Tuple1 :: tuple(), Tuple2 :: tuple().

Returns a new tuple with element at Index removed from tuple Tuple1.

Examples
1> erlang:delete_element(2, {one, two, three}).
{one,three}
-spec display(Term) -> true when Term :: term().

Prints a text representation of Term on the standard output.

Warning

This BIF is intended for debugging only. The printed representation may contain internal details that do not match the high-level representation of the term in Erlang.

Returns the Nth element (numbering from 1) of Tuple.

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

Calculates, without doing the encoding, the maximum byte size for a term encoded in the Erlang external term format.

The following condition applies always:

> Size1 = byte_size(term_to_binary(Term)),
> Size2 = erlang:external_size(Term),
> true = Size1 =< Size2.
true
Examples
1> Term = {ok,"abc"}.
2> erlang:external_size(Term).
13
3> byte_size(term_to_binary(Term)).
13
-spec external_size(Term, Options) -> non_neg_integer()
                       when
                           Term :: term(),
                           Options ::
                               [compressed |
                                {compressed, Level :: 0..9} |
                                deterministic |
                                {minor_version, Version :: 0..2} |
                                local].

Calculates, without doing the encoding, the maximum byte size for a term encoded in the Erlang external term format.

The following condition applies always:

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

See term_to_binary/2 for a description of the options.

Examples
1> Term = {ok,lists:duplicate(50, $A)}.
{ok,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
2> erlang:external_size(Term, [compressed]).
60
3> byte_size(term_to_binary(Term, [compressed])).
26
-spec float(Number) -> float() when Number :: number().

Returns a float by converting Number to a float.

Examples
1> float(55).
55.0
Note

If used on the top level in a guard, it tests whether the argument is a floating point number; for clarity, use is_float/1 instead.

When float/1 is used in an expression in a guard, such as 'float(A) == 4.0', it converts a number as described earlier.

-spec float_to_binary(Float) -> binary() when Float :: float().

Equivalent to float_to_binary(Float, [{scientific, 20}]).

-spec float_to_binary(Float, Options) -> binary()
                         when
                             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 in the same way as float_to_list/2.

Examples
1> float_to_binary(7.12, [{decimals, 4}]).
<<"7.1200">>
2> float_to_binary(7.12, [{decimals, 4}, compact]).
<<"7.12">>
3> float_to_binary(7.12, [{scientific, 3}]).
<<"7.120e+00">>
4> float_to_binary(7.12, [short]).
<<"7.12">>
5> float_to_binary(0.1+0.2, [short]).
<<"0.30000000000000004">>
6> float_to_binary(0.1+0.2)
<<"3.00000000000000044409e-01">>
-spec float_to_list(Float) -> string() when Float :: float().

Equivalent to float_to_list(Float, [{scientific, 20}]).

-spec float_to_list(Float, Options) -> string()
                       when
                           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:

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

In the last example, float_to_list(0.1+0.2) evaluates to "3.00000000000000044409e-01". The reason for this is explained in Representation of Floating Point Numbers.

Returns the largest integer not greater than Number.

See also trunc/1.

Examples
1> floor(-10.5).
-11
2> floor(5.5).
5
3> floor(10.0).
10
-spec fun_info(Fun) -> [{Item, Info}]
                  when
                      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. The order of the tuples is undefined, and more tuples can be added in a future release.

Warning

This BIF is intended for debugging. Library functions that need to check some property of a fun should use fun_info/2.

Two types of funs have slightly different semantics:

The following elements are always present in the list for both local and external funs:

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

See also fun_info/2 and is_function/2.

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 for a description of the items.

Examples
1> erlang:fun_info(fun() -> ok end, type).
{type,local}
2> erlang:fun_info(fun lists:sum/1, type).
{type,external}

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

Note

Generally, one can not use fun_to_list/1 to check if two funs are equal as 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.

Change

The output of fun_to_list/1 can differ between Erlang implementations and may change in future versions.

Examples
-module(test).
-export([add/1, add2/0, fun_tuple/0]).
add(A) -> fun(B) -> A + B end.
add2() -> fun add/1.
fun_tuple() -> {fun() -> 1 end, fun() -> 1 end}.
> {fun test:add/1, test:add2()}.
{fun test:add/1,#Fun<test.1.107738983>}

Explanation: fun test:add/1 is upgradable but test:add2() is not upgradable.

> {test:add(1), test:add(42)}.
{#Fun<test.0.107738983>,#Fun<test.0.107738983>}

Explanation: test:add(1) and test:add(42) has the same string representation as the environment is not taken into account.

> test:fun_tuple().
{#Fun<test.2.107738983>,#Fun<test.3.107738983>}

Explanation: The string representations differ because the funs come from different fun expressions.

> {fun() -> 1 end, fun() -> 1 end}. >
{#Fun<erl_eval.45.97283095>,#Fun<erl_eval.45.97283095>}

Explanation: All funs created from fun expressions of this form in uncompiled code with the same arity are mapped to the same list by fun_to_list/1.

Returns the first element of List.

It works with improper lists.

Failure: badarg if List is the empty list [].

Examples
1> hd([1,2,3,4,5]).
1
2> hd([first, second, third, so_on | improper_end]).
first
3> hd([]).
** exception error: bad argument
     in function  hd/1
        called as hd([])
        *** argument 1: not a nonempty list
-spec insert_element(Index, Tuple1, Term) -> Tuple2
                        when
                            Index :: pos_integer(), Tuple1 :: tuple(), Tuple2 :: tuple(), Term :: term().

Returns a new tuple with element Term inserted at position Index in tuple Tuple1.

All elements from position Index and upwards are pushed one step higher in the new tuple Tuple2.

Examples
1> erlang:insert_element(2, {one, two, three}, new).
{one,new,two,three}
-spec integer_to_binary(Integer) -> binary() when Integer :: integer().

Returns a binary corresponding to the text representation of Integer.

Examples
1> integer_to_binary(77).
<<"77">>
-spec integer_to_binary(Integer, Base) -> binary() when Integer :: integer(), Base :: 2..36.

Returns a binary corresponding to the text representation of Integer in base Base.

Examples
1> integer_to_binary(1023, 16).
<<"3FF">>
-spec integer_to_list(Integer) -> string() when Integer :: integer().

Returns a string corresponding to the text representation of Integer.

Examples
1> integer_to_list(77).
"77"
-spec integer_to_list(Integer, Base) -> string() when Integer :: integer(), Base :: 2..36.

Returns a string corresponding to the text representation of Integer in base Base.

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

Returns the size in bytes of the binary that would result from iolist_to_binary(Item).

Examples
1> iolist_size([1,2|<<3,4>>]).
4
-spec iolist_to_binary(IoListOrBinary) -> binary() when IoListOrBinary :: iolist() | binary().

Returns a binary constructed from the integers and binaries in IoListOrBinary.

Examples
1> Bin1 = <<1,2,3>>.
<<1,2,3>>
2> Bin2 = <<4,5>>.
<<4,5>>
3> Bin3 = <<6>>.
<<6>>
4> iolist_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6>>
-spec iolist_to_iovec(IoListOrBinary) -> iovec() when IoListOrBinary :: iolist() | binary().

Returns an iovec that is made from the integers and binaries in IoListOrBinary.

This function is useful when you need to flatten an iolist but do not require a single binary. It can be beneficial for passing data to NIF functions such as enif_inspect_iovec or for more efficient message passing. The advantage of using this function over iolist_to_binary/1 is that it does not need to copy off-heap binaries.

Examples

If you pass small binaries and integers, it works like iolist_to_binary/1.

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

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,...>>]

Returns true if Term is an atom; otherwise, returns false.

Examples
1> is_atom(42).
false
2> is_atom(ok).
true
-spec is_binary(Term) -> boolean() when Term :: term().

Returns true if Term is a binary; otherwise, returns false.

A binary always contains a complete number of bytes.

Examples
1> is_binary(42).
false
2> is_binary(<<1,2,3>>).
true
3> is_binary(<<7:12>>).
false
-spec is_bitstring(Term) -> boolean() when Term :: term().

Returns true if Term is a bitstring (including a binary); otherwise, returns false.

Examples
1> is_bitstring(42).
false
2> is_bitstring(<<1,2,3>>).
true
3> is_bitstring(<<7:12>>).
true
-spec is_boolean(Term) -> boolean() when Term :: term().

Returns true if Term is the atom true or false; otherwise, returns false.

Examples
1> is_boolean(true).
true
2> is_boolean(false).
true
3> is_boolean(ok).
false
4> is_boolean(42).
false

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

Examples
1> is_float(42).
false
2> is_float(42.0).
true
3> is_float(zero).
false
-spec is_function(Term) -> boolean() when Term :: term().

Returns true if Term is a fun; otherwise, returns false.

Examples
1> is_function(fun() -> ok end).
true
2> is_function(fun lists:sum/1).
true
3> is_function({lists,sum}).
false
-spec is_function(Term, Arity) -> boolean() when Term :: term(), Arity :: arity().

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

Examples
1> is_function(fun() -> ok end, 0).
true
2> is_function(fun lists:sum/1, 1).
true
3> is_function({lists,sum}, 1).
false
4> is_function(fun lists:sum/1, -1).
** exception error: bad argument
     in function  is_function/2
        called as is_function(fun lists:sum/1,-1)
        *** argument 2: out of range
5> is_function(fun lists:sum/1, bad_arity).
** exception error: bad argument
     in function  is_function/2
        called as is_function(fun lists:sum/1,bad_arity)
        *** argument 2: not an integer
-spec is_integer(Term) -> boolean() when Term :: term().

Returns true if Term is an integer; otherwise, returns false.

Examples
1> is_integer(1).
true
2> is_integer(-1234567890123456789012345678901234567890).
true
3> is_integer(1.0).
false
4> is_integer(zero).
false

Returns true if Term is a list with zero or more elements; otherwise, returns false.

Examples
1> is_list({a,b,c}).
false
2> is_list([]).
true
3> is_list([1]).
true
4> is_list([1,2]).
true
5> is_list([1,2|3]).
true

Returns true if Term is a map; otherwise, returns false.

Examples
1> is_map(#{}).
true
2> is_map(#{key => value}).
true
3> is_map([]).
false
-spec is_map_key(Key, Map) -> boolean() when Key :: term(), Map :: map().

Returns true if map Map contains Key and returns false if it does not contain the Key.

Failure: A {badmap,Map} exception is raised if Map is not a map.

Examples
> Map = #{"42" => value}.
#{"42" => value}
1> is_map_key("42", Map).
true
2> is_map_key(value, Map).
false
3> is_map_key(value, no_map).
** exception error: bad map: no_map
     in function  is_map_key/2
        called as is_map_key(value,no_map)
        *** argument 2: not a map
-spec is_number(Term) -> boolean() when Term :: term().

Returns true if Term is an integer or a floating point number; otherwise, returns false.

Examples
1> is_number(10.0).
true
2> is_number(7).
true
3> is_number(zero).
false

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

Examples
1> is_pid(self()).
true
2> is_pid(ok).
false

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

Examples
1> APort = hd(erlang:ports()).
2> is_port(APort).
true
3> is_port(self()).
false
-spec is_record(Term, RecordTag) -> boolean() when 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 specially. It emits code to verify that Term is a tuple, its first element is RecordTag, and its 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.

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.

-spec is_reference(Term) -> boolean() when Term :: term().

Returns true if Term is a reference; otherwise, returns false.

Examples
1> is_reference(make_ref()).
true
2> is_reference(self()).
false

Returns true if Term is a tuple; otherwise, returns false.

Examples
1> is_tuple({a, b, c}).
true
2> is_tuple([a, b, c]).
false

Returns the length of List.

Examples
1> length([1,2,3,4,5,6,7,8,9]).
9
2> length([a,b|c]).
** exception error: bad argument
     in function  length/1
        called as length([a,b|c])
        *** argument 1: not a list
-spec list_to_atom(String) -> atom() when String :: string().

Returns the atom whose text representation is String, creating a new atom if necessary.

As from Erlang/OTP 20, String may contain any Unicode character. Earlier versions allowed only ISO-latin-1 characters as the implementation did not allow Unicode characters above 255.

Note

Note that once an atom is created, it cannot be deleted. The Erlang system has a configurable limit on the number of atoms that can exist. To avoid reaching this limit, consider whether list_to_existing_atom/1 is a better choice than list_to_atom/1.

The number of characters that are permitted in an atom name is limited.

Examples
1> list_to_atom("Erlang").
'Erlang'
2> list_to_atom([960]).
'π'
-spec list_to_binary(IoList) -> binary() when IoList :: iolist().

Returns a binary made from the integers and binaries in IoList.

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

Returns a bitstring made from the integers and bitstrings in BitstringList.

The last tail in BitstringList is allowed to be a bitstring.

Examples
1> Bin1 = <<1,2,3>>.
<<1,2,3>>
2> Bin2 = <<4,5>>.
<<4,5>>
3> Bin3 = <<6,7:4>>.
<<6,7:4>>
4> list_to_bitstring([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6,7:4>>
-spec list_to_existing_atom(String) -> atom() when String :: string().

Returns the atom whose text representation is String, but only if there already exists such atom.

An atom exists if it has been created by the run-time system by either loading code or creating a term that the atom is a part of.

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

Note

Note that the compiler may optimize away atoms. For example, the compiler will 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 list_to_existing_atom("some_atom") will fail.

Examples
1> list_to_existing_atom("a_blatal_DOS_attack").
** exception error: bad argument
     in function  list_to_existing_atom/1
        called as list_to_existing_atom("a_blatal_DOS_attack")
        *** argument 1: not an already existing atom
2> hello.
hello
3> list_to_existing_atom("hello").
hello
-spec list_to_float(String) -> float() when String :: string().

Returns the float whose text representation is String.

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

The float string format is the same as the format for Erlang float literals except for that underscores are not permitted.

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

-spec list_to_integer(String) -> integer() when String :: string().

Returns an integer whose text representation is String.

String must contain at least one digit character and can have an optional prefix consisting of a single "+" or "-" character (that is, String must match the regular expression "^[+-]?[0-9]+$").

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

Examples
1> list_to_integer("123").
123
2> list_to_integer("-123").
-123
3> list_to_integer("+123234982304982309482093833234234").
123234982304982309482093833234234
-spec list_to_integer(String, Base) -> integer() when String :: string(), Base :: 2..36.

Returns an integer whose text representation in base Base is String.

String must contain at least one digit character and can have an optional prefix consisting of a single "+" or "-" character.

Failure: badarg if String contains an invalid integer representation.

Examples
1> list_to_integer("3FF", 16).
1023
2> list_to_integer("+3FF", 16).
1023
3> list_to_integer("3ff", 16).
1023
4> list_to_integer("-3FF", 16).
-1023
5> list_to_integer("Base36IsFun", 36).
41313437507787071
6> list_to_integer("102", 2).
** exception error: bad argument
     in function  list_to_integer/2
        called as list_to_integer("102",2)
        *** argument 1: not a textual representation of an integer
-spec list_to_pid(String) -> pid() when String :: string().

Returns a process identifier whose text representation is a String.

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

Warning

This BIF is intended for debugging and is not to be used in application programs.

Examples
> list_to_pid("<0.4.1>").
<0.4.1>
-spec list_to_port(String) -> port() when String :: string().

Returns a port identifier whose text representation is a String.

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

Warning

This BIF is intended for debugging and is not to be used in application programs.

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

Returns a reference whose text representation is a String.

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

Warning

This BIF is intended for debugging and is not to be used in application programs.

Examples
> list_to_ref("#Ref<0.4192537678.4073193475.71181>").
#Ref<0.4192537678.4073193475.71181>
-spec list_to_tuple(List) -> tuple() when List :: [term()].

Returns a tuple whose elements are the elements of List.

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

Returns a unique reference.

The reference is unique among connected nodes.

Warning

Before OTP 23, if a node was restarted multiple times with the same node name, references created on a newer instance could be mistaken for those created on an older instance with the same name.

Examples
1> is_reference(make_ref()).
true
-spec make_tuple(Arity, InitialValue) -> tuple() when Arity :: arity(), InitialValue :: term().

Creates a new tuple of the specified Arity, where all elements are InitialValue.

Examples
1> erlang:make_tuple(4, []).
{[],[],[],[]}
-spec make_tuple(Arity, DefaultValue, InitList) -> tuple()
                    when
                        Arity :: arity(),
                        DefaultValue :: term(),
                        InitList :: [{Position :: pos_integer(), term()}].

Creates a tuple of size Arity, where each element has value DefaultValue, and then fills in values from InitList.

Each list element in InitList must be a two-tuple, where the first element is a position in the newly created tuple and the second element is any term. If a position occurs more than once in the list, the term corresponding to the last occurrence is used.

Examples
1> erlang:make_tuple(5, [], [{2,ignored},{5,zz},{2,aa}]).
{[],aa,[],[],zz}
-spec map_get(Key, Map) -> Value when Map :: map(), Key :: any(), Value :: any().

Returns value Value associated with Key if Map contains Key.

The call fails with a {badmap,Map} exception if Map is not a map, or with a {badkey,Key} exception if no value is associated with Key.

Examples
1> Key = 1337.
2> Map = #{42 => value_two,Key => "value one","a" => 1}.
3> map_get(Key, Map).
"value one"
4> map_get(unknown_key, Map).
** exception error: bad key: unknown_key
     in function  map_get/2
        called as map_get(unknown_key,#{42 => value_two,1337 => "value one","a" => 1})
        *** argument 1: not present in map
5> map_get(key, no_map).
** exception error: bad map: no_map
     in function  map_get/2
        called as map_get(key,no_map)
        *** argument 2: not a map

Returns the number of key-value pairs in Map.

Examples
1> map_size(#{a=>1, b=>2, c=>3}).
3
-spec match_spec_test(MatchAgainst, MatchSpec, Type) -> TestResult
                         when
                             MatchAgainst :: [term()] | tuple(),
                             MatchSpec :: term(),
                             Type :: table | trace,
                             TestResult ::
                                 {ok, term(), [return_trace], [{error | warning, string()}]} |
                                 {error, [{error | warning, string()}]}.

Tests a match specification used in calls to ets:select/2 and trace:function/4.

The function tests both a match specification for "syntactic" correctness and runs the match specification against the object. If the match specification contains errors, the tuple {error, Errors} is returned, where Errors is a list of natural language descriptions of what was wrong with the match specification.

If Type is table, the object to match against is to be a tuple. The function then returns {ok,Result,[],Warnings}, where Result is what would have been the result in a real ets:select/2 call, or false if the match specification does not match the object tuple.

If Type is trace, the object to match against is to be a list. The function returns {ok, Result, Flags, Warnings}, where Result is one of the following:

Flags is a list of trace flags to be enabled; currently, the only available flag is return_trace.

See also ets:test_ms/2.

Examples
1> Ms = [{{'$1','$2'}, [], [{{'$2','$1'}}]}].
2> erlang:match_spec_test({a,b}, Ms, table).
{ok,{b,a},[],[]}
3> erlang:match_spec_test({a,b,c}, Ms, table).
{ok,false,[],[]}
-spec max(Term1, Term2) -> Maximum when Term1 :: term(), Term2 :: term(), Maximum :: term().

Returns the largest of Term1 and Term2.

If the terms compare equal with the == operator, Term1 is returned.

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

Change

Allowed in guards tests from Erlang/OTP 26.

Examples:
1> max(1, 2).
2
2> max(1.0, 1).
1.0
3> max(1, 1.0).
1
4> max("abc", "b").
"b"
-spec min(Term1, Term2) -> Minimum when Term1 :: term(), Term2 :: term(), Minimum :: term().

Returns the smallest of Term1 and Term2.

If the terms compare equal with the == operator, Term1 is returned.

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

Change

Allowed in guards tests from Erlang/OTP 26.

Examples
> min(1, 2).
1
> min(1.0, 1).
1.0
> min(1, 1.0).
1
> min("abc", "b").
"abc"

Returns the node where Arg originates.

If Arg originates from the local node and the local node is not alive, nonode@nohost is returned.

Examples
1> node(self()) =:= node().
true

Equivalent to phash2(Term, Range).

Returns a hash value for Term.

The hash value for the same Erlang term is guaranteed to be the same regardless of machine architecture and ERTS version.

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 to be used for hashing terms. It distributes small integers better than phash/2, and it is faster for large integers and binaries.

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

Examples
1> erlang:phash2({a,b,c}, 1_000).
870
2> erlang:phash2(41, 1_000).
297
3> erlang:phash2(42, 1_000).
368
4> erlang:phash2(43, 1_000).
725
-spec pid_to_list(Pid) -> string() when Pid :: pid().

Returns a string corresponding to the text representation of Pid.

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.

Examples
> erlang:pid_to_list(self()).
"<0.85.0>"
-spec port_to_list(Port) -> string() when Port :: port().

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

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.

Returns an integer by rounding Number to the nearest integer.

Example:

1> round(42.1).
42
2> round(5.5).
6
3> round(-5.5).
-6
4> round(36028797018963969.0).
36028797018963968

In the last example, round(36028797018963969.0) evaluates to 36028797018963968. The reason for this is that the number 36028797018963969.0 cannot be represented exactly as a float value. Instead, the float literal is represented as 36028797018963968.0, which is the closest number that can be represented exactly as a float value. See Representation of Floating Point Numbers for additional information.

-spec setelement(Index, Tuple1, Value) -> Tuple2
                    when Index :: pos_integer(), Tuple1 :: tuple(), Tuple2 :: tuple(), Value :: term().

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.

Examples
1> setelement(2, {10, green, bottles}, red).
{10,red,bottles}

Returns the number of elements in a tuple or the number of bytes in a binary or bitstring.

For bitstrings, the number of whole bytes is returned. That is, if the number of bits in the bitstring is not divisible by 8, the resulting number of bytes is rounded down.

See also tuple_size/1, byte_size/1, and bit_size/1.

Note

It is recommended to avoid size/1 in new code.

Examples
1> size({a, b, c}).
3
2> tuple_size({a, b, c}).
3
3> size(<<11, 22, 33>>).
3
4> byte_size(<<11, 22, 33>>).
3
5> size(<<11, 7:4>>).
1
6> byte_size(<<11, 7:4>>).
2
7> bit_size(<<11, 7:4>>).
12

Returns a tuple containing the binaries that are the result of splitting Bin into two parts at position Pos.

This operation is non-destructive. After the operation, there are three binaries altogether.

Examples
1> B = list_to_binary("0123456789").
<<"0123456789">>
2> byte_size(B).
10
3> {B1, B2} = split_binary(B, 3).
{<<"012">>,<<"3456789">>}
4> byte_size(B1).
3
5> byte_size(B2).
7

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, such as efficiently writing a term to a file or sending an Erlang term through a communication channel not supported by distributed Erlang.

See also binary_to_term/1.

Note

There is no guarantee that this function will always return the same encoded representation for the same term.

Examples
1> Bin = term_to_binary(hello).
<<131,119,5,104,101,108,108,111>>
2> hello = binary_to_term(Bin).
hello
-spec term_to_binary(Term, Options) -> ext_binary()
                        when
                            Term :: term(),
                            Options ::
                                [compressed |
                                 {compressed, Level :: 0..9} |
                                 deterministic |
                                 {minor_version, Version :: 0..2} |
                                 local].

Returns a binary data object that is the result of encoding Term according to the Erlang external term format.

Supported options:

Examples
1> List = lists:duplicate(20, $=).
"===================="
2> term_to_binary(List, []).
<<131,107,0,20,61,61,61,61,61,61,61,61,61,61,61,61,61,61,
  61,61,61,61,61,61>>
3> term_to_binary(List, [compressed]).
<<131,80,0,0,0,23,120,156,203,102,16,177,197,2,0,61,98,5,
  68>>

Returns the encoding of Term according to the Erlang external term format as ext_iovec/0.

This function produce the same encoding as term_to_binary/1, but with another return type. The call iolist_to_binary(term_to_iovec(Term)) will produce exactly the same result as the call term_to_binary(Term).

term_to_iovec/1 is a pure optimization of the functionality provided by term_to_binary/1. For example, it can reference off-heap binaries directly instead of copying their contents into the result.

See also term_to_binary/1.

Examples
1> term_to_iovec({binary:copy(~"a", 65), binary:copy(~"b", 65)}).
[<<131,104,2,109,0,0,0,65>>,
 <<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">>,
 <<109,0,0,0,65>>,
 <<"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb">>]
-spec term_to_iovec(Term, Options) -> ext_iovec()
                       when
                           Term :: term(),
                           Options ::
                               [compressed |
                                {compressed, Level :: 0..9} |
                                deterministic |
                                {minor_version, Version :: 0..2} |
                                local].

Returns the encoding of Term according to the Erlang external term format as ext_iovec/0.

This function produce the same encoding as term_to_binary/2, but with another return type. The call iolist_to_binary(term_to_iovec(Term, Opts)) will produce exactly the same result as term_to_binary(Term, Opts).

This function supports all options supported by term_to_binary/2.

term_to_iovec/2 is a pure optimization of the functionality provided by term_to_binary/2. For example, it can reference off-heap binaries directly instead of copying their contents into the result.

See also term_to_binary/2.

Examples
1> term_to_iovec({binary:copy(~"a", 65), binary:copy(~"b", 65)}, [deterministic]).
[<<131,104,2,109,0,0,0,65>>,
 <<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">>,
 <<109,0,0,0,65>>,
 <<"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb">>]

Returns the tail of List, which is the list without its first element.

It works with improper lists.

Examples
1> tl([geesties, guilies, beasties]).
[guilies, beasties]
2> tl([geesties]).
[]
3> tl([geesties, guilies, beasties | improper_end]).
[guilies, beasties | improper_end]
4> tl([geesties | improper_end]).
improper_end
5> tl([]).
** exception error: bad argument
     in function  tl/1
        called as tl([])
        *** argument 1: not a nonempty list

Failure: badarg if List is an empty list [].

Truncates the decimals of Number.

See also round/1, floor/1, and ceil/1.

Examples
1> trunc(5.7).
5
2> trunc(-5.7).
-5
3> trunc(5).
5
4> trunc(36028797018963969.0).
36028797018963968

In the last example, trunc(36028797018963969.0) evaluates to 36028797018963968. This happens because the number 36028797018963969.0 cannot be represented exactly as a floating-point value. Instead, it is represented as 36028797018963968.0, which is the closest representable floating-point value. See Representation of Floating Point Numbers for additional information.

Returns the number of elements in Tuple.

Examples
1> tuple_size({a, b, c}).
3
-spec tuple_to_list(Tuple) -> [term()] when Tuple :: tuple().

Returns a list corresponding to Tuple.

Examples
1> tuple_to_list({share, {'Ericsson_B', 163}}).
[share,{'Ericsson_B',163}]
-spec unique_integer() -> integer().

Generates and returns an integer unique on current runtime system instance.

Equivalent to calling erlang:unique_integer([]).

Examples
> erlang:unique_integer().
-576460752303422335
-spec unique_integer(ModifierList) -> integer()
                        when ModifierList :: [Modifier], Modifier :: positive | monotonic.

Generates and returns an integer unique on 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 to use the range of integers that do not 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:

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:

Examples
> erlang:unique_integer([positive]).
1186
Processes and Ports
-spec alias() -> Alias when Alias :: reference().

Equivalent to alias([]).

-spec alias(Opts) -> Alias when Alias :: reference(), Opts :: [explicit_unalias | reply | priority].

Create an alias which can be used when sending messages to the process that created the alias. When the alias has been deactivated, messages sent using the alias will be dropped. An alias can be deactivated using unalias/1.

Currently available options for alias/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.

Note that both the server and the client in this example must be executing on at least OTP 24 systems in order for this to work.

For more information on process aliases see the Process Aliases section of the Erlang Reference Manual.

Calls a fun, passing the elements in Args as arguments.

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

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.

-spec apply(Module, Function, Args) -> term()
               when Module :: module(), Function :: atom(), Args :: [term()].

Returns the result of applying Function in Module to Args. The applied function must be exported from Module. The arity of the function is the length of Args.

For example:

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

If the number of arguments are known at compile time, the call is better written as Module:Function(Arg1, Arg2, ..., ArgN).

Failure: error_handler:undefined_function/3 is called if the applied function is not exported. The error handler can be redefined (see process_flag/2). If error_handler is undefined, or if the user has redefined the default error_handler so the replacement module is undefined, an error with reason undef is generated.

-spec bump_reductions(Reductions) -> true when Reductions :: pos_integer().

This implementation-dependent function increments the reduction counter for the calling process.

In the Beam emulator, the reduction counter is normally incremented by one for each function and BIF call. A context switch is forced when the counter reaches the maximum number of reductions for a process (4000 reductions in Erlang/OTP 19.2 and later).

Warning

This BIF can be removed in a future version of the Beam machine without prior warning. It is unlikely to be implemented in other Erlang implementations.

-spec demonitor(MonitorRef) -> true when 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.

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

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

Change

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.

-spec demonitor(MonitorRef, OptionList) -> boolean()
                   when 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:

Change

More options can be added in a future release.

Failures:

-spec erase() -> [{Key, Val}] when Key :: term(), 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]}]
-spec erase(Key) -> Val | undefined when Key :: term(), 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.

For example:

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

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}]}]}}
-spec error(Reason, Args) -> no_return() when Reason :: term(), Args :: [term()] | none.

Raises an exception of class error with the reason Reason. Args is expected to be the list of arguments for the current function or the atom none.

If Args is a list, it 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.

Examples

test.erl:

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

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

Erlang shell:

1> c(test).
{ok,test}
2> 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")
-spec error(Reason, Args, Options) -> no_return()
               when
                   Reason :: term(),
                   Args :: [term()] | none,
                   Options :: [Option],
                   Option :: {error_info, ErrorInfoMap},
                   ErrorInfoMap :: #{cause => term(), module => module(), function => atom()}.

Raises an exception of class error with the reason Reason. Args is expected to be the list of arguments for the current function or the atom none.

If Args is a list, it 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 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.

Raises an exception of class exit with exit reason Reason.

As evaluating this function causes an exception to be raised, it has no return value.

The intent of the exception class exit is that the current process should be stopped (for example when a message telling a process to stop is received).

This function differ from error/1,2,3 by causing an exception of a different class and by having a reason that does not include the list of functions from the call stack.

See the guide about errors and error handling for additional information.

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. Such exit signals with exit reason kill can be trapped by the linked processes. Note that this means that signals with exit reason kill behave differently depending on how they are sent because the signal will be untrappable if a process sends such a signal to another process with erlang:exit/2.

Sends an exit signal with exit reason Reason to the process or port identified by Dest. If Dest is a reference, the exit signal will only affect the identified process if the reference is an active process alias of a process executing on an OTP 28.0 node or newer.

The following behavior applies if Reason is any term, except normal or kill, and P is the process or port identified by Dest:

The following behavior applies if Reason is the term normal and Dest is the identifier of a process P which is not the same as the process that invoked erlang:exit(Dest, normal) (the behavior when a process sends a signal with the normal reason to itself is described in the warning):

If Reason is the atom kill, that is, if exit(Dest, kill) is called, an untrappable exit signal is sent to the process that is identified by Dest, which unconditionally exits with exit reason killed. The exit reason is changed from kill to killed to hint to linked processes that the killed process got killed by a call to exit(Dest, kill).

Note

The functions erlang:exit/1 and erlang:exit/2 are named similarly but provide very different functionalities. The erlang:exit/1 function should be used when the intent is to stop the current process while erlang:exit/2 should be used when the intent is to send an exit signal to another process. Note also that erlang:exit/1 raises an exception that can be caught while erlang:exit/2 does not cause any exception to be raised.

Warning

The only scenario that has not been covered by the description above is when a process P sends an exit signal with reason normal to itself, that is erlang:exit(self(), normal). The behavior in this scenario is as follows:

Note that the behavior described above is different from when a process sends an exit signal with reason normal to another process. This is arguably strange but this behavior is kept for backward compatibility reasons.

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

-spec exit(Dest, Reason, OptList) -> true
              when Dest :: pid() | port() | reference(), Reason :: term(), OptList :: [priority].

Provides an option list for modification of the functionality provided by the exit/2 BIF. The Dest and Reason arguments has the same meaning as when passed to the exit/2 BIF.

Currently available options:

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

-spec garbage_collect(Pid) -> GCResult when Pid :: pid(), GCResult :: boolean().

Equivalent to garbage_collect(Pid, []).

-spec garbage_collect(Pid, OptionList) -> GCResult | async
                         when
                             Pid :: pid(),
                             RequestId :: term(),
                             Option :: {async, RequestId} | {type, major | minor},
                             OptionList :: [Option],
                             GCResult :: boolean().

Garbage collects the node local process identified by Pid.

Option:

If Pid equals self/0, and no async option has been passed, the garbage collection is performed at once, that is, the same as calling garbage_collect/0. Otherwise a request for garbage collection is sent to the process identified by Pid, and will be handled when appropriate. If no async option has been passed, the caller blocks until GCResult is available and can be returned.

GCResult informs about the result of the garbage collection request as follows:

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

Failures:

-spec get() -> [{Key, Val}] when Key :: term(), Val :: term().

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

For example:

> put(key1, merry),
put(key2, lambs),
put(key3, {are, playing}),
get().
[{key1,merry},{key2,lambs},{key3,{are,playing}}]
-spec get(Key) -> Val | undefined when Key :: term(), Val :: term().

Returns the value Val associated with Key in the process dictionary, or undefined if Key does not exist.

The expected time complexity for the current implementation of this function is O(1) and the worst case time complexity is O(N), where N is the number of items in the process dictionary.

For example:

> put(key1, merry),
put(key2, lambs),
put({any, [valid, term]}, {are, playing}),
get({any, [valid, term]}).
{are,playing}
-spec get_keys() -> [Key] when Key :: term().

Returns a list of all keys present in the process dictionary. The items in the returned list can be in any order.

For example:

> put(dog, {animal,1}),
put(cow, {animal,2}),
put(lamb, {animal,3}),
get_keys().
[dog,cow,lamb]
-spec get_keys(Val) -> [Key] when Val :: term(), Key :: term().

Returns a list of keys that are associated with the value Val in the process dictionary. The items in the returned list can be in any order.

For example:

> 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]
-spec group_leader() -> pid().

Returns the process identifier of the group leader for the process evaluating the function.

Every process is a member of some process group and all groups have a group leader. All I/O from the group is channeled to the group leader. When a new process is spawned, it gets the same group leader as the spawning process.

Initially, at system startup, init is both its own group leader and the group leader of all processes. During the boot of a system the group leader for processes will be changed depending on the need of the system. Some examples where this is done are:

-spec group_leader(GroupLeader, Pid) -> true when GroupLeader :: pid(), Pid :: pid().

Sets the group leader of Pid to GroupLeader. Typically, this is used when a process started from a certain shell is to have another group leader than init.

The group leader should be rarely changed in applications with a supervision tree, because OTP assumes the group leader of their processes is their application master.

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 OTP design principles related to starting and stopping applications.

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

Puts the calling process into a wait state where its memory allocation has been reduced as much as possible. This is useful if the process does not expect to receive any messages soon.

The process is awakened when a message is sent to it, and control resumes normally to the caller. Unlike erlang:hibernate/3, it does not discard the call stack.

-spec hibernate(Module, Function, Args) -> no_return()
                   when Module :: module(), Function :: atom(), Args :: [term()].

Puts the calling process into a wait state where its memory allocation has been reduced as much as possible. This is useful if the process does not expect to receive any messages soon.

The process is awakened when a message is sent to it, and control resumes in Module:Function with the arguments specified by Args with the call stack emptied, meaning that the process terminates when that function returns. Thus erlang:hibernate/3 never returns to its caller. The resume function Module:Function/Arity must be exported (Arity =:= length(Args)).

If the process has any message in its message queue, the process is awakened immediately in the same way as described earlier.

In more technical terms, erlang:hibernate/3 discards the call stack for the process, and then garbage collects the process. After this, all live data is in one continuous heap. The heap is then shrunken to the exact same size as the live data that it holds (even if that size is less than the minimum heap size for the process).

If the size of the live data in the process is less than the minimum heap size, the first garbage collection occurring after the process is awakened ensures that the heap size is changed to a size not smaller than the minimum heap size.

Notice that emptying the call stack means that any surrounding catch is removed and must be re-inserted after hibernation. One effect of this is that processes started using proc_lib (also indirectly, such as gen_server processes), are to use proc_lib:hibernate/3 instead, to ensure that the exception handler continues to work when the process wakes up.

-spec is_process_alive(Pid) -> boolean() when Pid :: pid().

Pid must refer to a process at the local node.

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.

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

-spec link(PidOrPort) -> true when PidOrPort :: pid() | port().

Sets up and activates a link between the calling process and another process or a port identified by PidOrPort.

We will from here on call the identified process or port linkee. If the linkee is a port, it must reside on the same node as the caller.

If one of the participants of a link terminates, it will send an exit signal to the other participant. The exit signal will contain the exit reason of the terminated participant. Other cases when exit signals are triggered due to a link are when no linkee exist (noproc exit reason) and when the connection between linked processes on different nodes is lost or cannot be established (noconnection exit reason).

An existing link can be removed by calling unlink/1. For more information on links and exit signals due to links, see the Processes chapter in the Erlang Reference Manual:

For historical reasons, link/1 has a strange semi-synchronous behavior when it is "cheap" to check if the linkee exists or not, and the caller does not trap exits. If the above is true and the linkee does not exist, link/1 will raise a noproc error exception. The expected behavior would instead have been that link/1 returned true, and the caller later was sent an exit signal with noproc exit reason, but this is unfortunately not the case. The noproc exception is not to be confused with an exit signal with exit reason noproc. Currently it is "cheap" to check if the linkee exists when it is supposed to reside on the same node as the calling process.

The link setup and activation is performed asynchronously. If the link already exists, or if the caller attempts to create a link to itself, nothing is done. A detailed description of the link protocol can be found in the Distribution Protocol chapter of the ERTS User's Guide.

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

Failure:

Provides an option list for modification of the link functionality provided by link/1. The PidOrPort argument has the same meaning as when passed to link/1.

Currently available options:

Sends a monitor request of type Type to the entity identified by Item.

If the monitored entity does not exist or it changes monitored state, the caller of monitor/2 is notified by a message on the following format:

{Tag, MonitorRef, Type, Object, Info}
Note

The monitor request is an asynchronous signal. That is, it takes time before the signal reaches its destination.

Type can be one of the following atoms: process, port or time_offset.

A process or port monitor is triggered only once, after that it is removed from both monitoring process and the monitored entity. Monitors are fired when the monitored process or port terminates, does not exist at the moment of creation, or if the connection to it is lost. If the connection to it is lost, we do not know if it still exists. The monitoring is also turned off when demonitor/1 is called.

A process or port monitor by name resolves the RegisteredName to pid/0 or port/0 only once at the moment of monitor instantiation, later changes to the name registration will not affect the existing monitor.

When a process or port monitor is triggered, a 'DOWN' message is sent that has the following pattern:

{'DOWN', MonitorRef, Type, Object, Info}

In the monitor message MonitorRef and Type are the same as described earlier, and:

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.

The monitor functionality is expected to be extended. That is, other Types and Items are expected to be supported in a future release.

Note

If or when monitor/2 is extended, other possible values for Tag, Object, and Info in the monitor message will be introduced.

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

Provides an option list for modification of monitoring functionality provided by monitor/2. The Type and Item arguments have the same meaning as when passed to monitor/2.

Currently available options:

Works exactly like error/1, but Dialyzer thinks that this BIF will return an arbitrary term. When used in a stub function for a NIF to generate an exception when the NIF library is not loaded, Dialyzer does not generate false warnings.

-spec nif_error(Reason, Args) -> no_return() when Reason :: term(), Args :: [term()].

Works exactly like error/2, but Dialyzer thinks that this BIF will return an arbitrary term. When used in a stub function for a NIF to generate an exception when the NIF library is not loaded, Dialyzer does not generate false warnings.

-spec open_port(PortName, PortSettings) -> port()
                   when
                       PortName ::
                           {spawn, Command :: string() | binary()} |
                           {spawn_driver, Command :: string() | binary()} |
                           {spawn_executable, FileName :: file:name_all()} |
                           {fd, In :: non_neg_integer(), Out :: non_neg_integer()},
                       PortSettings :: [Opt],
                       Opt ::
                           {packet, N :: 1 | 2 | 4} |
                           stream |
                           {line, L :: non_neg_integer()} |
                           {cd, Dir :: string() | binary()} |
                           {env,
                            Env :: [{Name :: os:env_var_name(), Val :: os:env_var_value() | [] | false}]} |
                           {args, [string() | binary()]} |
                           {arg0, string() | binary()} |
                           exit_status | use_stdio | nouse_stdio | stderr_to_stdout | in | out |
                           binary | eof |
                           {parallelism, Boolean :: boolean()} |
                           hide |
                           {busy_limits_port, {non_neg_integer(), non_neg_integer()} | disabled} |
                           {busy_limits_msgq, {non_neg_integer(), non_neg_integer()} | disabled}.

Returns a port identifier as the result of opening a new Erlang port. A port can be seen as an external Erlang process.

The name of the executable as well as the arguments specified in cd, env, args, and arg0 are subject to Unicode filename translation if the system is running in Unicode filename mode. To avoid translation or to force, for example UTF-8, supply the executable and/or arguments as a binary in the correct encoding. For details, see the module file, the function file:native_name_encoding/0 in Kernel, and the Using Unicode in Erlang User's Guide.

Note

The characters in the name (if specified as a list) can only be > 255 if the Erlang virtual machine is started in Unicode filename translation mode. Otherwise the name of the executable is limited to the ISO Latin-1 character set.

PortNames:

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

Default is stream for all port types and use_stdio for spawned ports.

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:

During use of a port opened using {spawn, Name}, {spawn_driver, Name}, or {spawn_executable, Name}, errors arising when sending messages to it are reported to the owning process using signals of the form {'EXIT', Port, PosixCode}. For the possible values of PosixCode, see file.

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

-spec port_call(Port, Operation, Data) -> term()
                   when 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:

-spec port_close(Port) -> true when Port :: port() | atom().

Closes an open port. Roughly the same as Port ! {self(), close} except for the error behavior (see below), being synchronous, and that the port does not reply with {Port, closed}.

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.

-spec port_command(Port, Data) -> true when Port :: port() | atom(), Data :: iodata().

Sends data to a port. Same as Port ! {PortOwner, {command, Data}} except for the error behavior and being synchronous (see below).

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:

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.

-spec port_command(Port, Data, OptionList) -> boolean()
                      when
                          Port :: port() | atom(),
                          Data :: iodata(),
                          Option :: force | nosuspend,
                          OptionList :: [Option].

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

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:

Change

More options can be added in a future release.

Failures:

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.

-spec port_connect(Port, Pid) -> true when Port :: port() | atom(), Pid :: pid().

Sets the port owner (the connected port) to Pid. Roughly the same as Port ! {Owner, {connect, Pid}} except for the following:

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.

For comparison: Port ! {self(), {connect, Pid}} only fails with badarg if Port does not refer to a port or a process. If Port is a closed port, nothing happens. If Port is an open port and the calling process is the port owner, the port replies with {Port, connected} to the old port owner. Notice that the old port owner is still linked to the port, while the new is not. If Port is an open port and the calling process is not the port owner, the port owner fails with badsig. The port owner fails with badsig also if Pid is not an existing local process identifier.

Notice that any process can set the port owner using Port ! {PortOwner, {connect, Pid}} as if it itself was the port owner, but the reply always goes to the port owner.

As from Erlang/OTP R16, Port ! {PortOwner, {connect, Pid}} is truly asynchronous. Notice that this operation has always been documented as an asynchronous operation, while the underlying implementation has been synchronous. port_connect/2 is however still fully synchronous because of its error behavior.

Failures:

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.

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.

Failures:

-spec port_info(Port) -> Result
                   when
                       Port :: port() | atom(),
                       ResultItem ::
                           {registered_name, RegisteredName :: atom()} |
                           {id, Index :: non_neg_integer()} |
                           {connected, Pid :: pid()} |
                           {links, Pids :: [pid()]} |
                           {name, String :: string()} |
                           {input, Bytes :: non_neg_integer()} |
                           {output, Bytes :: non_neg_integer()} |
                           {os_pid, OsPid :: non_neg_integer() | undefined},
                       Result :: [ResultItem] | undefined.

Returns a list 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. 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:

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

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

-spec port_info(Port, Item :: connected) -> {connected, Pid} | undefined
                   when Port :: port() | atom(), Pid :: pid();
               (Port, Item :: id) -> {id, Index} | undefined
                   when Port :: port() | atom(), Index :: non_neg_integer();
               (Port, Item :: input) -> {input, Bytes} | undefined
                   when Port :: port() | atom(), Bytes :: non_neg_integer();
               (Port, Item :: links) -> {links, Pids} | undefined
                   when Port :: port() | atom(), Pids :: [pid()];
               (Port, Item :: locking) -> {locking, Locking} | undefined
                   when Port :: port() | atom(), Locking :: false | port_level | driver_level;
               (Port, Item :: memory) -> {memory, Bytes} | undefined
                   when Port :: port() | atom(), Bytes :: non_neg_integer();
               (Port, Item :: monitors) -> {monitors, Monitors} | undefined
                   when Port :: port() | atom(), Monitors :: [{process, pid()}];
               (Port, Item :: monitored_by) -> {monitored_by, MonitoredBy} | undefined
                   when Port :: port() | atom(), MonitoredBy :: [pid()];
               (Port, Item :: name) -> {name, Name} | undefined
                   when Port :: port() | atom(), Name :: string();
               (Port, Item :: os_pid) -> {os_pid, OsPid} | undefined
                   when Port :: port() | atom(), OsPid :: non_neg_integer() | undefined;
               (Port, Item :: output) -> {output, Bytes} | undefined
                   when Port :: port() | atom(), Bytes :: non_neg_integer();
               (Port, Item :: parallelism) -> {parallelism, Boolean} | undefined
                   when Port :: port() | atom(), Boolean :: boolean();
               (Port, Item :: queue_size) -> {queue_size, Bytes} | undefined
                   when Port :: port() | atom(), Bytes :: non_neg_integer();
               (Port, Item :: registered_name) -> {registered_name, RegisteredName} | [] | undefined
                   when Port :: port() | atom(), RegisteredName :: atom().

Returns information about Port.

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.

Item is one of the following and can be used to get various information about the Port.

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

-spec ports() -> [port()].

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

Notice that an exiting port exists, but is not open.

-spec process_display(Pid, Type) -> true when Pid :: pid(), Type :: backtrace.

Writes information about the local process Pid on standard error.

The only allowed value for the atom Type is backtrace, which shows the contents of the call stack, including information about the call chain, with the current function printed first. The format of the output is not further defined.

-spec process_flag(async_dist, Boolean) -> OldBoolean when Boolean :: boolean(), OldBoolean :: boolean();
                  (trap_exit, Boolean) -> OldBoolean when Boolean :: boolean(), OldBoolean :: boolean();
                  (error_handler, Module) -> OldModule when Module :: atom(), OldModule :: atom();
                  (fullsweep_after, FullsweepAfter) -> OldFullsweepAfter
                      when FullsweepAfter :: non_neg_integer(), OldFullsweepAfter :: non_neg_integer();
                  (min_heap_size, MinHeapSize) -> OldMinHeapSize
                      when MinHeapSize :: non_neg_integer(), OldMinHeapSize :: non_neg_integer();
                  (min_bin_vheap_size, MinBinVHeapSize) -> OldMinBinVHeapSize
                      when MinBinVHeapSize :: non_neg_integer(), OldMinBinVHeapSize :: non_neg_integer();
                  (max_heap_size, MaxHeapSize) -> OldMaxHeapSize
                      when MaxHeapSize :: max_heap_size(), OldMaxHeapSize :: max_heap_size();
                  (message_queue_data, MQD) -> OldMQD
                      when MQD :: message_queue_data(), OldMQD :: message_queue_data();
                  (priority, Level) -> OldLevel
                      when Level :: priority_level(), OldLevel :: priority_level();
                  (save_calls, N) -> OldN when N :: 0..10000, OldN :: 0..10000;
                  (sensitive, Boolean) -> OldBoolean when Boolean :: boolean(), OldBoolean :: boolean();
                  ({monitor_nodes, term()}, term()) -> term();
                  (monitor_nodes, term()) -> term().

Sets the process flag indicated to the specified value. Returns the previous value of the flag.

Flag is one of the following:

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.

Failure: badarg if Pid is not a local process.

Returns a list containing InfoTuples with miscellaneous information about the process identified by Pid, or undefined if the process is not alive.

The order of the InfoTuples is undefined and all InfoTuples are not mandatory. The InfoTuples part of the result can be changed without prior notice.

The InfoTuples with the following items are part of the result:

If the process identified by Pid has a registered name, also an InfoTuple with item registered_name is included.

For information about specific InfoTuples, see process_info/2.

Warning

This BIF is intended for debugging only. For all other purposes, use process_info/2.

Failure: badarg if Pid is not a local process.

Returns information about the process identified by Pid, as specified by Item or ItemList. Returns undefined if the process is not alive.

If the process is alive and a single Item is specified, the returned value is the corresponding InfoTuple, unless Item =:= registered_name and the process has no registered name. In this case, [] is returned. This strange behavior is because of historical reasons, and is kept for backward compatibility.

If ItemList is specified, the result is InfoTupleList. The InfoTuples in InfoTupleList are included with the corresponding Items in the same order as the Items were included in ItemList. Valid Items can be included multiple times in ItemList.

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.

Valid InfoTuples with corresponding Items:

Notice that not all implementations support all these Items.

Failures:

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

Example:

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

Returns a processes iterator that can be used in processes_next/1.

Returns a 2-tuple, consisting of one process identifier and a new processes iterator. If the process iterator has run out of processes in the process table, none will be returned.

The two major benefits of using the processes_iterator/0/processes_next/1 BIFs instead of using the processes/0 BIF are that they scale better since no locking is needed, and you do not risk getting a huge list allocated on the heap if there are a huge amount of processes alive in the system.

Example:

> I0 = erlang:processes_iterator(), ok.
ok
> {Pid1, I1} = erlang:processes_next(I0), Pid1.
<0.0.0>,
> {Pid2, I2} = erlang:processes_next(I1), Pid2.
<0.1.0>
Note

This BIF has less consistency guarantee than processes/0. Process identifiers returned from consecutive calls of this BIF may not be a consistent snapshot of all elements existing in the table during any of the calls. The process identifier of a process that is alive before processes_iterator/0 is called and continues to be alive until processes_next/1 returns none is guaranteed to be part of the result returned from one of the calls to processes_next/1.

-spec put(Key, Val) -> term() when Key :: term(), Val :: term().

Adds a new Key to the process dictionary, associated with the value Val, and returns undefined. If Key exists, the old value 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.

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

-spec raise(Class, Reason, Stacktrace) -> badarg
               when Class :: error | exit | throw, Reason :: term(), Stacktrace :: raise_stacktrace().

Raises an exception of the specified class, reason, and call stack backtrace (stacktrace).

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.

-spec register(RegName, PidOrPort) -> true when RegName :: atom(), PidOrPort :: port() | pid().

Registers the name RegName with a process identifier (pid) or a port identifier in the name registry. RegName, which must be an atom, can be used instead of the pid or port identifier in send operator (RegName ! Message) and most other BIFs that take a pid or port identifies as an argument.

For example:

> register(db, Pid).
true

The registered name is considered a Directly Visible Erlang Resource and is automatically unregistered when the process terminates.

Failures:

-spec registered() -> [RegName] when 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]
-spec resume_process(Suspendee) -> true when 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:

Returns the process identifier of the calling process.

For example:

> self().
<0.26.0>

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

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

-spec send(Dest, Msg, Options) -> Res
              when
                  Dest :: send_destination(),
                  Msg :: term(),
                  Options :: [nosuspend | noconnect | priority],
                  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:

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

Warning

As with erlang:send_nosuspend/2,3: use with extreme care.

Send a message without suspending the caller.

Equivalent to erlang:send(Dest, Msg, [nosuspend]), but returns true if the message was sent and false if the message was not sent because the sender would have had to be suspended.

This function is intended for send operations to an unreliable remote node without ever blocking the sending (Erlang) process. If the connection to the remote node (usually not a real Erlang node, but a node written in C or Java) is overloaded, this function does not send the message and returns false.

The same occurs if Dest refers to a local port that is busy. For all other destinations (allowed for the ordinary send operator '!'), this function sends the message and returns true.

This function is only to be used in rare circumstances where a process communicates with Erlang nodes that can disappear without any trace, causing the TCP buffers and the drivers queue to be over-full before the node is shut down (because of tick time-outs) by net_kernel. The normal reaction to take when this occurs is some kind of premature shutdown of the other node.

Notice that ignoring the return value from this function would result in an unreliable message passing, which is contradictory to the Erlang programming model. The message is not sent if this function returns false.

In many systems, transient states of overloaded queues are normal. Although this function returns false does not mean that the other node is guaranteed to be non-responsive, it could be a temporary overload. Also, a return value of true does only mean that the message can be sent on the (TCP) channel without blocking; the message is not guaranteed to arrive at the remote node. For a disconnected non-responsive node, the return value is true (mimics the behavior of operator !). The expected behavior and the actions to take when the function returns false are application- and hardware-specific.

Warning

Use with extreme care.

Equivalent to erlang:send(Dest, Msg, [nosuspend | Options]), but with a Boolean return value.

This function behaves like erlang:send_nosuspend/2, but takes a third parameter, a list of options. The only option is noconnect, which makes the function return false if the remote node is not currently reachable by the local node. The normal behavior is to try to connect to the node, which can stall the process during a short period. The use of option noconnect makes it possible to be sure not to get the slightest delay when sending to a remote process. This is especially useful when communicating with nodes that expect to always be the connecting part (that is, nodes written in C or Java).

Whenever the function returns false (either when a suspend would occur or when noconnect was specified and the node was not already connected), the message is guaranteed not to have been sent.

Warning

Use with extreme care.

Returns the process identifier of a new process started by the application of Fun to the empty list []. Otherwise works like spawn/3.

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.

-spec spawn(Module, Function, Args) -> pid()
               when Module :: module(), Function :: atom(), Args :: [term()].

Returns the process identifier of a new process started by the application of Module:Function to Args.

error_handler:undefined_function(Module, Function, Args) is evaluated by the new process if Module:Function/Arity does not exist (where Arity is the length of Args). The error handler can be redefined (see process_flag/2). If error_handler is undefined, or the user has redefined the default error_handler and its replacement is undefined, a failure with reason undef occurs.

Example:

> spawn(speed, regulator, [high_speed, thin_cut]).
<0.13.1>
-spec spawn(Node, Module, Function, Args) -> pid()
               when Node :: node(), 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. If Node does not exist, a useless pid is returned. Otherwise works like spawn/3.

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.

-spec spawn_link(Node, Fun) -> pid() when Node :: node(), 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.

-spec spawn_link(Module, Function, Args) -> pid()
                    when Module :: module(), Function :: atom(), Args :: [term()].

Returns the process identifier of a new process started by the application of Module:Function to Args. A link is created between the calling process and the new process, atomically. Otherwise works like spawn/3.

-spec spawn_link(Node, Module, Function, Args) -> pid()
                    when Node :: node(), 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.

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.

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.

If the node identified by Node does not support distributed spawn_monitor(), the call will fail with a notsup exception.

-spec spawn_monitor(Module, Function, Args) -> {pid(), reference()}
                       when Module :: module(), Function :: atom(), Args :: [term()].

A new process is started by the application of Module:Function to Args. The process is monitored at the same time. Returns the process identifier and a reference for the monitor. Otherwise works like spawn/3.

-spec spawn_monitor(Node, Module, Function, Args) -> {pid(), reference()}
                       when Node :: node(), Module :: module(), Function :: atom(), Args :: [term()].

A new process is started by the application of Module:Function to Args on the node Node. The process is monitored at the same time. Returns the 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.

Returns the process identifier (pid) of a new process started by the application of Fun to the empty list []. Otherwise works like spawn_opt/4.

If option monitor is specified, the newly created process is monitored, and both the pid and reference for the monitor are returned.

Returns the process identifier (pid) 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_opt/4.

Valid options depends on what options are supported by the node identified by Node. A description of valid Options for the local node of current OTP version can be found in the documentation of spawn_opt/4.

-spec spawn_opt(Module, Function, Args, Options) -> Pid | {Pid, MonitorRef}
                   when
                       Module :: module(),
                       Function :: atom(),
                       Args :: [term()],
                       Options :: [spawn_opt_option()],
                       Pid :: pid(),
                       MonitorRef :: reference().

Works as spawn/3, except that an extra option list is specified when creating the process.

If option monitor is specified, the newly created process is monitored, and both the pid and reference for the monitor are returned.

Options:

-spec spawn_opt(Node, Module, Function, Args, Options) -> pid() | {pid(), reference()}
                   when
                       Node :: node(),
                       Module :: module(),
                       Function :: atom(),
                       Args :: [term()],
                       Options :: [monitor | {monitor, [monitor_option()]} | link | OtherOption],
                       OtherOption :: term().

Returns the process identifier (pid) of a new process started by the application of Module:Function to Args on Node. If Node does not exist, a useless pid is returned. Otherwise works like spawn_opt/4.

Valid options depends on what options are supported by the node identified by Node. A description of valid Options for the local node of current OTP version can be found in the documentation of spawn_opt/4.

Equivalent to the call spawn_request(node(),Fun,[]). That is, a spawn request on the local node with no options.

-spec spawn_request(Fun, Options) -> ReqId
                       when
                           Fun :: function(),
                           Option :: {reply_tag, ReplyTag} | {reply, Reply} | spawn_opt_option(),
                           ReplyTag :: term(),
                           Reply :: yes | no | error_only | success_only,
                           Options :: [Option],
                           ReqId :: reference();
                   (Node, Fun) -> ReqId when Node :: node(), Fun :: function(), ReqId :: reference().

Equivalent to spawn_request(node(),Fun,Options) or spawn_request(Node,Fun,[]) depending on the arguments.

That is either:

-spec spawn_request(Node, Fun, Options) -> ReqId
                       when
                           Node :: node(),
                           Fun :: function(),
                           Options :: [Option],
                           Option ::
                               monitor |
                               {monitor, [monitor_option()]} |
                               link |
                               {reply_tag, ReplyTag} |
                               {reply, Reply} |
                               OtherOption,
                           ReplyTag :: term(),
                           Reply :: yes | no | error_only | success_only,
                           OtherOption :: term(),
                           ReqId :: reference();
                   (Module, Function, Args) -> ReqId
                       when
                           Module :: module(),
                           Function :: atom(),
                           Args :: [term()],
                           ReqId :: reference().

Equivalent to spawn_request(Node,erlang,apply,[Fun,[]],Options) or spawn_request(node(),Module,Function,Args,[]) depending on the arguments.

That is either:

This function will fail with a badarg exception if:

-spec spawn_request(Node, Module, Function, Args) -> ReqId
                       when
                           Node :: node(),
                           Module :: module(),
                           Function :: atom(),
                           Args :: [term()],
                           ReqId :: reference();
                   (Module, Function, Args, Options) -> ReqId
                       when
                           Module :: module(),
                           Function :: atom(),
                           Args :: [term()],
                           Option :: {reply_tag, ReplyTag} | {reply, Reply} | spawn_opt_option(),
                           ReplyTag :: term(),
                           Reply :: yes | no | error_only | success_only,
                           Options :: [Option],
                           ReqId :: reference().

Equivalent to spawn_request(Node,Module,Function,Args,[]) or spawn_request(node(),Module,Function,Args,Options) depending on the arguments.

That is either:

-spec spawn_request(Node, Module, Function, Args, Options) -> ReqId
                       when
                           Node :: node(),
                           Module :: module(),
                           Function :: atom(),
                           Args :: [term()],
                           Options :: [Option],
                           Option ::
                               monitor |
                               {monitor, [monitor_option()]} |
                               link |
                               {reply_tag, ReplyTag} |
                               {reply, Reply} |
                               OtherOption,
                           ReplyTag :: term(),
                           Reply :: yes | no | error_only | success_only,
                           OtherOption :: term(),
                           ReqId :: reference().

Asynchronously send a spawn request. Returns a request identifier ReqId.

If the spawn operation succeeds, a new process is created on the node identified by Node. When a spawn operation succeeds, the caller will by default be sent a message of the form {ReplyTag, ReqId, ok, Pid} where Pid is the process identifier of the newly created process. Such a message is referred to as a success message below in the text. ReplyTag is by default the atom spawn_reply unless modified by 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. Such a message is referred to as an error message below in the text. Currently the following spawn error Reasons are defined, but other reasons can appear at any time without prior notice:

Valid Options:

If a spawn reply message is delivered, it is guaranteed to be delivered before any other signals from the newly spawned process are delivered to the process issuing the spawn request.

This function will fail with a badarg exception if:

Note that not all individual Options are checked when the spawn request is sent. Some Options can only be checked on reception of the request. Therefore an invalid option does not cause a badarg exception, but will cause the spawn operation to fail with an error reason of badopt.

A spawn request can be abandoned by calling spawn_request_abandon/1.

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

Abandon a previously issued spawn request. ReqId corresponds to a request identifier previously returned by spawn_request() in a call from current process. That is, only the process that has made the request can abandon the request.

A spawn request can only be successfully abandoned until the spawn request has completed. When a spawn request has been successfully abandoned, the caller will not be effected by future direct effects of the spawn request itself. For example, it will not receive a spawn reply message. The request is however not withdrawn, so a new process may or may not be created due to the request. If a new process is created after the spawn request was abandoned, no monitors nor links will be set up to the caller of spawn_request_abandon/1 due to the spawn request. If the spawn request included the link option, the process created due to this request will be sent an exit signal from its parent with the exit reason abandoned when it is detected that the spawn operation has succeeded.

Note

A process created due to a spawn request that has been abandoned may communicate with its parent as any other process. It is only the direct effects on the parent of the actual spawn request, that will be canceled by abandoning a spawn request.

Return values:

This function fail with a badarg exception if ReqId is not a reference.

-spec suspend_process(Suspendee) -> true when Suspendee :: pid().

Suspends the process identified by Suspendee. Equivalent to calling erlang:suspend_process(Suspendee, []).

Warning

This BIF is intended for debugging only.

-spec suspend_process(Suspendee, OptList) -> boolean()
                         when
                             Suspendee :: pid(),
                             OptList :: [Opt],
                             Opt :: unless_suspending | asynchronous | {asynchronous, term()}.

Increases the suspend count on the process identified by Suspendee and puts it in the suspended state if it is not already in that state. A suspended process is not scheduled for execution until the process has been resumed. If the suspended process currently is waiting in a receive ... after expression, the timer for the timeout will, as of OTP 28.0, also be suspended until the process is resumed.

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.

Options (Opts):

If the suspend count on the process identified by Suspendee is increased, true is returned, otherwise false.

Warning

This BIF is intended for debugging only.

Warning

You can easily create deadlocks if processes suspends each other (directly or in circles). In ERTS versions prior to ERTS version 10.0, the runtime system prevented such deadlocks, but this prevention has now been removed due to performance reasons.

Failures:

Raises an exception of class throw. Intended to be used to do non-local returns from functions.

If evaluated within a catch expression, the catch expression returns value Any.

For example:

> catch throw({hello, there}).
        {hello,there}

If evaluated within a try-block of a try expression, the value Any can be caught within the catch block.

For example:

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.

See the guide about errors and error handling for additional information.

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

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.

-spec unlink(Id) -> true when Id :: pid() | port().

Removes a link between the calling process and another process or a port identified by Id.

We will from here on call the identified process or port unlinkee.

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:

Once unlink(Id) has returned, it is guaranteed that the link between the caller and the unlinkee has no effect on the caller in the future (unless the link is setup again). Note that if the caller is trapping exits, an {'EXIT', Id, ExitReason} message due to the link may have been placed in the message queue of the caller before the unlink(Id) call completed. Also note that the {'EXIT', Id, ExitReason} message may be the result of the link, but may also be the result of the unlikee sending the caller an exit signal by calling the exit/2 BIF. Therefore, it may or may not be appropriate to clean up the message queue after a call to unlink(Id) as follows, when trapping exits:

unlink(Id),
receive
    {'EXIT', Id, _} ->
        true
after 0 ->
        true
end

The link removal is performed asynchronously. If such a link does not exist, nothing is done. A detailed description of the link protocol can be found in the Distribution Protocol chapter of the ERTS User's Guide.

Note

For some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual.

Failure: badarg if Id does not identify a process or a node local port.

-spec unregister(RegName) -> true when 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.

Users are advised not to unregister system processes.

Failure: badarg if RegName is not a registered name.

-spec whereis(RegName) -> pid() | port() | undefined when RegName :: atom().

Returns the process identifier or port identifier with the registered name RegName from the name registry. Returns undefined if the name is not registered.

For example:

> whereis(db).
<0.43.0>

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.

System

Equivalent to calling halt(0, []).

For example:

> halt().
os_prompt%

Equivalent to calling halt(HaltType, []).

For example:

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

Halt the runtime system.

Returns a list with information about memory dynamically allocated by the Erlang emulator.

Each list element is a tuple {Type, Size}. The first element Type is an atom describing memory type. The second element Size is the memory size in bytes.

Memory types:

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 is not part of the result.

total      = processes + system
processes  = processes_used + ProcessesNotUsed
system     = atom + binary + code + ets + OtherSystem
atom       = atom_used + AtomNotUsed
RealTotal  = processes + RealSystem
RealSystem = system + MissedSystem

More tuples in the returned list can be added in a future release.

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.

Change

As from ERTS 5.6.4, erlang:memory/0 requires that all erts_alloc(3) allocators are enabled (default behavior).

Failure: notsup if an erts_alloc(3) allocator has been disabled.

Returns the memory size in bytes allocated for memory of type Type. The argument can also be specified as a list of memory_type/0 atoms, in which case a corresponding list of {memory_type(), Size :: integer >= 0} tuples is returned.

Change

As from ERTS 5.6.4, erlang:memory/1 requires that all erts_alloc(3) allocators are enabled (default behavior).

Failures:

See also erlang:memory/0.

-spec statistics(active_tasks) -> [ActiveTasks] when ActiveTasks :: non_neg_integer();
                (active_tasks_all) -> [ActiveTasks] when ActiveTasks :: non_neg_integer();
                (context_switches) -> {ContextSwitches, 0} when ContextSwitches :: non_neg_integer();
                (exact_reductions) -> {Total_Exact_Reductions, Exact_Reductions_Since_Last_Call}
                    when
                        Total_Exact_Reductions :: non_neg_integer(),
                        Exact_Reductions_Since_Last_Call :: non_neg_integer();
                (garbage_collection) -> {Number_of_GCs, Words_Reclaimed, 0}
                    when Number_of_GCs :: non_neg_integer(), Words_Reclaimed :: non_neg_integer();
                (io) -> {{input, Input}, {output, Output}}
                    when Input :: non_neg_integer(), Output :: non_neg_integer();
                (microstate_accounting) -> [MSAcc_Thread] | undefined
                    when
                        MSAcc_Thread ::
                            #{type := MSAcc_Thread_Type,
                              id := MSAcc_Thread_Id,
                              counters := MSAcc_Counters},
                        MSAcc_Thread_Type ::
                            async | aux | dirty_io_scheduler | dirty_cpu_scheduler | poll | scheduler,
                        MSAcc_Thread_Id :: non_neg_integer(),
                        MSAcc_Counters :: #{MSAcc_Thread_State => non_neg_integer()},
                        MSAcc_Thread_State ::
                            alloc | aux | bif | busy_wait | check_io | emulator | ets | gc |
                            gc_fullsweep | nif | other | port | send | sleep | timers;
                (reductions) -> {Total_Reductions, Reductions_Since_Last_Call}
                    when
                        Total_Reductions :: non_neg_integer(),
                        Reductions_Since_Last_Call :: non_neg_integer();
                (run_queue) -> non_neg_integer();
                (run_queue_lengths) -> [RunQueueLength] when RunQueueLength :: non_neg_integer();
                (run_queue_lengths_all) -> [RunQueueLength] when RunQueueLength :: non_neg_integer();
                (runtime) -> {Total_Run_Time, Time_Since_Last_Call}
                    when Total_Run_Time :: non_neg_integer(), Time_Since_Last_Call :: non_neg_integer();
                (scheduler_wall_time) -> [{SchedulerId, ActiveTime, TotalTime}] | undefined
                    when
                        SchedulerId :: pos_integer(),
                        ActiveTime :: non_neg_integer(),
                        TotalTime :: non_neg_integer();
                (scheduler_wall_time_all) -> [{SchedulerId, ActiveTime, TotalTime}] | undefined
                    when
                        SchedulerId :: pos_integer(),
                        ActiveTime :: non_neg_integer(),
                        TotalTime :: non_neg_integer();
                (total_active_tasks) -> ActiveTasks when ActiveTasks :: non_neg_integer();
                (total_active_tasks_all) -> ActiveTasks when ActiveTasks :: non_neg_integer();
                (total_run_queue_lengths) -> TotalRunQueueLengths
                    when TotalRunQueueLengths :: non_neg_integer();
                (total_run_queue_lengths_all) -> TotalRunQueueLengths
                    when TotalRunQueueLengths :: non_neg_integer();
                (wall_clock) -> {Total_Wallclock_Time, Wallclock_Time_Since_Last_Call}
                    when
                        Total_Wallclock_Time :: non_neg_integer(),
                        Wallclock_Time_Since_Last_Call :: non_neg_integer().

Returns statistics about the current system.

The possible flags are:

-spec system_flag(backtrace_depth, Depth) -> OldDepth
                     when Depth :: non_neg_integer(), OldDepth :: non_neg_integer();
                 (cpu_topology, CpuTopology) -> OldCpuTopology
                     when CpuTopology :: cpu_topology(), OldCpuTopology :: cpu_topology();
                 (dirty_cpu_schedulers_online, DirtyCPUSchedulersOnline) -> OldDirtyCPUSchedulersOnline
                     when
                         DirtyCPUSchedulersOnline :: pos_integer(),
                         OldDirtyCPUSchedulersOnline :: pos_integer();
                 (erts_alloc, {Alloc, F, V}) -> ok | notsup
                     when Alloc :: atom(), F :: atom(), V :: integer();
                 (fullsweep_after, Number) -> OldNumber
                     when Number :: non_neg_integer(), OldNumber :: non_neg_integer();
                 (microstate_accounting, Action) -> OldState
                     when Action :: true | false | reset, OldState :: true | false;
                 (min_heap_size, MinHeapSize) -> OldMinHeapSize
                     when MinHeapSize :: non_neg_integer(), OldMinHeapSize :: non_neg_integer();
                 (min_bin_vheap_size, MinBinVHeapSize) -> OldMinBinVHeapSize
                     when MinBinVHeapSize :: non_neg_integer(), OldMinBinVHeapSize :: non_neg_integer();
                 (max_heap_size, MaxHeapSize) -> OldMaxHeapSize
                     when MaxHeapSize :: max_heap_size(), OldMaxHeapSize :: max_heap_size();
                 (multi_scheduling, BlockState) -> OldBlockState
                     when
                         BlockState :: block | unblock | block_normal | unblock_normal,
                         OldBlockState :: blocked | disabled | enabled;
                 (outstanding_system_requests_limit, NewLimit) -> OldLimit
                     when NewLimit :: 1..134217727, OldLimit :: 1..134217727;
                 (scheduler_bind_type, How) -> OldBindType
                     when
                         How :: scheduler_bind_type() | default_bind,
                         OldBindType :: scheduler_bind_type();
                 (scheduler_wall_time, Boolean) -> OldBoolean
                     when Boolean :: boolean(), OldBoolean :: boolean();
                 (schedulers_online, SchedulersOnline) -> OldSchedulersOnline
                     when SchedulersOnline :: pos_integer(), OldSchedulersOnline :: pos_integer();
                 (system_logger, Logger) -> PrevLogger
                     when Logger :: logger | undefined | pid(), PrevLogger :: logger | undefined | pid();
                 (trace_control_word, TCW) -> OldTCW
                     when TCW :: non_neg_integer(), OldTCW :: non_neg_integer();
                 (time_offset, finalize) -> OldState when OldState :: preliminary | final | volatile;
                 (internal_cpu_topology, term()) -> term();
                 (sequential_tracer, Tracer) -> PrevTracer | false
                     when
                         Tracer :: pid() | port() | {module(), term()} | false,
                         PrevTracer :: pid() | port() | {module(), term()} | false;
                 (reset_seq_trace, true) -> true.

Sets a system flag to the given value.

The possible flags to set are:

-spec system_info(allocated_areas) -> [tuple()];
                 (allocator) -> {Allocator, Version, Features, Settings}
                     when
                         Allocator :: undefined | glibc,
                         Version :: [non_neg_integer()],
                         Features :: [atom()],
                         Settings :: [{Subsystem :: atom(), [{Parameter :: atom(), Value :: term()}]}];
                 ({allocator, Alloc}) -> [_] when Alloc :: atom();
                 (alloc_util_allocators) -> [Alloc] when Alloc :: atom();
                 ({allocator_sizes, Alloc}) -> [_] when Alloc :: atom();
                 (atom_count) -> pos_integer();
                 (atom_limit) -> pos_integer();
                 (build_type) -> opt | debug | gcov | valgrind | gprof | lcnt | frmptr;
                 (c_compiler_used) -> {atom(), term()};
                 (check_io) -> [_];
                 (cpu_topology) -> CpuTopology when CpuTopology :: cpu_topology();
                 ({cpu_topology, defined | detected | used}) -> CpuTopology
                     when CpuTopology :: cpu_topology();
                 (cpu_quota) -> pos_integer() | unknown;
                 (creation) -> integer();
                 (debug_compiled) -> boolean();
                 (delayed_node_table_gc) -> infinity | non_neg_integer();
                 (dirty_cpu_schedulers) -> non_neg_integer();
                 (dirty_cpu_schedulers_online) -> non_neg_integer();
                 (dirty_io_schedulers) -> non_neg_integer();
                 (dist) -> binary();
                 (dist_buf_busy_limit) -> non_neg_integer();
                 (dist_ctrl) -> [{Node :: node(), ControllingEntity :: port() | pid()}];
                 (driver_version) -> string();
                 (dynamic_trace) -> none | dtrace | systemtap;
                 (dynamic_trace_probes) -> boolean();
                 (eager_check_io) -> boolean();
                 (emu_flavor) -> emu | jit;
                 (emu_type) -> opt | debug | gcov | valgrind | gprof | lcnt | frmptr;
                 (end_time) -> non_neg_integer();
                 (ets_count) -> pos_integer();
                 (ets_limit) -> pos_integer();
                 (fullsweep_after) -> {fullsweep_after, non_neg_integer()};
                 (garbage_collection) -> garbage_collection_defaults();
                 (heap_sizes) -> [non_neg_integer()];
                 (heap_type) -> private;
                 (info) -> binary();
                 (kernel_poll) -> boolean();
                 (loaded) -> binary();
                 (logical_processors | logical_processors_available | logical_processors_online) ->
                     unknown | pos_integer();
                 (machine) -> string();
                 (max_heap_size) -> {max_heap_size, MaxHeapSize :: max_heap_size()};
                 (message_queue_data) -> message_queue_data();
                 (min_heap_size) -> {min_heap_size, MinHeapSize :: pos_integer()};
                 (min_bin_vheap_size) -> {min_bin_vheap_size, MinBinVHeapSize :: pos_integer()};
                 (modified_timing_level) -> integer() | undefined;
                 (multi_scheduling) -> disabled | blocked | blocked_normal | enabled;
                 (multi_scheduling_blockers) -> [Pid :: pid()];
                 (nif_version) -> string();
                 (normal_multi_scheduling_blockers) -> [Pid :: pid()];
                 (otp_release) -> string();
                 (os_monotonic_time_source) -> [{atom(), term()}];
                 (os_system_time_source) -> [{atom(), term()}];
                 (outstanding_system_requests_limit) -> 1..134217727;
                 (port_parallelism) -> boolean();
                 (port_count) -> non_neg_integer();
                 (port_limit) -> pos_integer();
                 (process_count) -> pos_integer();
                 (process_limit) -> pos_integer();
                 (procs) -> binary();
                 (scheduler_bind_type) -> scheduler_bind_type();
                 (scheduler_bindings) -> tuple();
                 (scheduler_id) -> SchedulerId :: pos_integer();
                 (schedulers | schedulers_online) -> pos_integer();
                 (smp_support) -> boolean();
                 (start_time) -> integer();
                 (system_architecture) -> string();
                 (system_logger) -> logger | undefined | pid();
                 (system_version) -> string();
                 (threads) -> boolean();
                 (thread_pool_size) -> non_neg_integer();
                 (time_correction) -> true | false;
                 (time_offset) -> preliminary | final | volatile;
                 (time_warp_mode) -> no_time_warp | single_time_warp | multi_time_warp;
                 (tolerant_timeofday) -> enabled | disabled;
                 (trace_control_word) -> non_neg_integer();
                 (update_cpu_info) -> changed | unchanged;
                 (version) -> string();
                 (wordsize | {wordsize, internal} | {wordsize, external}) -> 4 | 8;
                 (async_dist) -> boolean();
                 (halt_flush_timeout) -> non_neg_integer() | infinity.

Returns information about the current system.

The documentation of this function is broken into the following sections in order to make it easier to navigate.

Memory Allocation

Returns various information about the memory allocators of the current system (emulator) as specified by Item:

CPU Topology

Returns various information about the CPU topology of the current system (emulator) as specified by Item:

Process Information

Returns information about the default process heap settings:

System Limits

Returns information about the current system (emulator) limits as specified by Item:

System Time

Returns information about the current system (emulator) time as specified by Item:

Scheduler Information

Returns information about schedulers, scheduling and threads in the current system as specified by Item:

Distribution Information

Returns information about Erlang Distribution in the current system as specified by Item:

System Information

Returns various information about the current system (emulator) as specified by Item:

-spec system_monitor() -> MonSettings
                        when
                            MonSettings :: undefined | {MonitorPid, Options},
                            MonitorPid :: pid(),
                            Options :: [system_monitor_option()].

Returns the current system monitoring settings set by erlang:system_monitor/2 as {MonitorPid, Options}, or undefined if no settings exist.

The order of the options can be different from the one that was set.

-spec system_monitor(Arg) -> MonSettings
                        when
                            Arg :: undefined | {MonitorPid, Options},
                            MonSettings :: undefined | {MonitorPid, Options},
                            MonitorPid :: pid(),
                            Options :: [system_monitor_option()].

When called with argument undefined, all system performance monitoring settings are cleared.

Calling the function with {MonitorPid, Options} as argument is the same as calling erlang:system_monitor(MonitorPid, Options).

Returns the previous system monitor settings just like erlang:system_monitor/0.

-spec system_monitor(MonitorPid, Options) -> MonSettings
                        when
                            MonitorPid :: pid(),
                            Options :: [system_monitor_option()],
                            MonSettings :: undefined | {OldMonitorPid, OldOptions},
                            OldMonitorPid :: pid(),
                            OldOptions :: [system_monitor_option()].

Sets the system event monitoring options. MonitorPid is a local process identifier (pid) receiving system monitor messages.

Change

This function is superseded by trace:system/3 that operate on dynamic trace sessions.

The second argument is a list of monitoring options to enable:

For more detailed descriptions about the monitoring options, see trace:system/3.

Unlink trace:system/3, the arguments to system_monitor/2 specifies how all system monitoring should be set, not how it should be changed. This means only one process at a time (MonitorPid) can be the receiver of messages from system monitoring set with this function. Also, the way to clear a specific monitor option is to not include it in the list Options. All system monitoring will, however, be cleared if the process identified by MonitorPid terminates.

There are no special option values (like zero) to clear an option. Some of the options have a unspecified minimum value. Lower values will be adjusted to the minimum value. For example, it is currently not possible to monitor all garbage collections with {long_gc, 0}.

Returns the previous system monitor settings just like erlang:system_monitor/0.

Note

If a monitoring process gets so large that it itself starts to cause system monitor messages when garbage collecting, the messages enlarge the process message queue and probably make the problem worse.

Keep the monitoring process neat and do not set the system monitor limits too tight.

Failures:

-spec system_profile() -> ProfilerSettings
                        when
                            ProfilerSettings :: undefined | {ProfilerPid, Options},
                            ProfilerPid :: pid() | port(),
                            Options :: [system_profile_option()].

Returns the current system profiling settings set by erlang:system_profile/2 as {ProfilerPid, Options}, or undefined if there are no settings. The order of the options can be different from the one that was set.

Sets system profiler options. ProfilerPid is a local process identifier (pid) or port receiving profiling messages. The receiver is excluded from all profiling. The second argument is a list of profiling options:

Note

erlang:system_profile behavior can change in a future release.

Time and timers

Equivalent to erlang:cancel_timer(TimerRef, []).

-spec cancel_timer(TimerRef, Options) -> Result | ok
                      when
                          TimerRef :: reference(),
                          Async :: boolean(),
                          Info :: boolean(),
                          Option :: {async, Async} | {info, Info},
                          Options :: [Option],
                          Time :: non_neg_integer(),
                          Result :: Time | false.

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:

More Options may be added in the future.

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.

-spec convert_time_unit(Time, FromUnit, ToUnit) -> ConvertedTime
                           when
                               Time :: integer(),
                               ConvertedTime :: integer(),
                               FromUnit :: time_unit(),
                               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/1 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.

Returns the current date as {Year, Month, Day}.

The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time.

For example:

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

Returns the current local date and time, {{Year, Month, Day}, {Hour, Minute, Second}}.

For example:

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

The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time.

Converts local date and time to Universal Time Coordinated (UTC), if supported by the underlying OS. Otherwise no conversion is done and Localtime is returned.

For example:

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

Failure: badarg if Localtime denotes an invalid date and time.

-spec localtime_to_universaltime(Localtime, IsDst) -> Universaltime
                                    when
                                        Localtime :: calendar:datetime(),
                                        Universaltime :: calendar:datetime(),
                                        IsDst :: true | false | undefined.

Converts local date and time to Universal Time Coordinated (UTC) as erlang:localtime_to_universaltime/1, but the caller decides if Daylight Saving Time is active.

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

Examples:

> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, true).
{{1996,11,6},{12,45,17}}
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, false).
{{1996,11,6},{13,45,17}}
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}, undefined).
{{1996,11,6},{13,45,17}}

Failure: badarg if Localtime denotes an invalid date and time.

-spec monotonic_time() -> integer().

Returns the current Erlang monotonic time in native time unit. This is a monotonically increasing time since some unspecified point in time.

Note

This is a monotonically increasing time, but not a strictly monotonically increasing time. That is, consecutive calls to erlang:monotonic_time/0 can produce the same result.

Different runtime system instances will use different unspecified points in time as base for their Erlang monotonic clocks. That is, it is pointless comparing monotonic times from different runtime system instances. Different runtime system instances can also place this unspecified point in time different relative runtime system start. It can be placed in the future (time at start is a negative value), the past (time at start is a positive value), or the runtime system start (time at start is zero). The monotonic time at runtime system start can be retrieved by calling erlang:system_info(start_time).

Returns the current Erlang monotonic time converted into the Unit passed as argument.

Same as calling erlang:convert_time_unit( erlang:monotonic_time(), native, Unit), however optimized for commonly used Units.

Equivalent to erlang:read_timer(TimerRef, []).

-spec read_timer(TimerRef, Options) -> Result | ok
                    when
                        TimerRef :: reference(),
                        Async :: boolean(),
                        Option :: {async, Async},
                        Options :: [Option],
                        Time :: non_neg_integer(),
                        Result :: Time | false.

Reads the state of a timer that has been created by either erlang:start_timer or erlang:send_after. TimerRef identifies the timer, and was returned by the BIF that created the timer.

Options:

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.

Equivalent to erlang:send_after(Time, Dest, Msg, []).

-spec send_after(Time, Dest, Msg, Options) -> TimerRef
                    when
                        Time :: integer(),
                        Dest :: pid() | atom(),
                        Msg :: term(),
                        Options :: [Option],
                        Abs :: boolean(),
                        Option :: {abs, Abs},
                        TimerRef :: reference().

Starts a timer. When the timer expires, the message Msg is sent to the process identified by Dest. Apart from the format of the time-out message, this function works exactly as erlang:start_timer/4.

Equivalent to erlang:start_timer(Time, Dest, Msg, []).

-spec start_timer(Time, Dest, Msg, Options) -> TimerRef
                     when
                         Time :: integer(),
                         Dest :: pid() | atom(),
                         Msg :: term(),
                         Options :: [Option],
                         Abs :: boolean(),
                         Option :: {abs, Abs},
                         TimerRef :: reference().

Starts a timer. When the timer expires, the message {timeout, TimerRef, Msg} is sent to the process identified by Dest.

Options:

More Options can be added in the future.

The absolute point in time, the timer is set to expire on, must be in the interval [erlang:convert_time_unit(erlang:system_info(start_time), native, millisecond),erlang:convert_time_unit(erlang:system_info(end_time), native, millisecond) ]. If a relative time is specified, the Time value is not allowed to be negative.

If Dest is a pid/0, it must be a pid/0 of a process created on the current runtime system instance. This process has either terminated or not. If Dest is an atom/0, it is interpreted as the name of a locally registered process. The process referred to by the name is looked up at the time of timer expiration. No error is returned if the name does not refer to a process.

If Dest is a pid/0, the timer is automatically canceled if the process referred to by the pid/0 is not alive, or if the process exits. This feature was introduced in ERTS 5.4.11. Notice that timers are not automatically canceled when Dest is an atom/0.

See also erlang:send_after/4, erlang:cancel_timer/2, and erlang:read_timer/2.

For more information on timers in Erlang in general, see the Timers section of the Time and Time Correction in Erlang ERTS User's guide.

Failure: badarg if the arguments do not satisfy the requirements specified here.

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.

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. For more information, see the documentation of time warp modes in the User's Guide.

Returns the current time as {Hour, Minute, Second}.

The time zone and Daylight Saving Time correction depend on the underlying OS. The return value is based on the OS System Time.

For example:

> time().
{9,42,44}

Returns the current time offset between Erlang monotonic time and Erlang system time in native time unit. Current time offset added to an Erlang monotonic time gives corresponding Erlang system time.

The time offset may or may not change during operation depending on the time warp mode used.

Note

A change in time offset can be observed at slightly different points in time by different processes.

If the runtime system is in multi-time warp mode, the time offset is changed when the runtime system detects that the OS system time has changed. The runtime system will, however, not detect this immediately when it occurs. A task checking the time offset is scheduled to execute at least once a minute; so, under normal operation this is to be detected within a minute, but during heavy load it can take longer time.

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.

-spec timestamp() -> Timestamp when Timestamp :: timestamp().

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.

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.

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.

Returns the current date and time according to Universal Time Coordinated (UTC) in the form {{Year, Month, Day}, {Hour, Minute, Second}} if supported by the underlying OS. Otherwise erlang:universaltime() is equivalent to erlang:localtime(). The return value is based on the OS System Time.

For example:

> erlang:universaltime().
{{1996,11,6},{14,18,43}}

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.

For example:

> erlang:universaltime_to_localtime({{1996,11,6},{14,18,43}}).
{{1996,11,7},{15,18,43}}

Failure: badarg if Universaltime denotes an invalid date and time.

Tracing
-spec trace(PidPortSpec, How, FlagList) -> integer()
               when
                   PidPortSpec ::
                       pid() |
                       port() |
                       all | processes | ports | existing | existing_processes | existing_ports | new |
                       new_processes | new_ports,
                   How :: boolean(),
                   FlagList :: [trace_flag()].

Turn on or off trace flags on processes or ports for the static legacy trace session.

Change

This function is superseded by trace:process/4 and trace:port/4 that operate on dynamic trace sessions.

Argument FlagList can contain two additional options:

If no tracer is specified, the calling process receives all the trace messages. The legacy trace session has no specified tracer.

For further documentation see trace:process/4 and trace:port/4.

-spec trace_delivered(Tracee) -> Ref when Tracee :: pid() | all, Ref :: reference().

Calling this function makes sure all trace messages have been delivered.

The delivery of trace messages (generated by erlang:trace/3, seq_trace, or erlang:system_profile/2) is dislocated on the time-line compared to other events in the system. 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, use erlang:trace_delivered(Tracee).

When it is 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) .

Notice that 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. It is not an error if Tracee is not, and has not been traced by someone, but if this is the case, no trace messages have been delivered when the trace_delivered message arrives.

Notice that 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.

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.

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.

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.

-spec trace_info(PidPortFuncEvent, Item) -> Res
                    when
                        PidPortFuncEvent ::
                            pid() |
                            port() |
                            new | new_processes | new_ports |
                            {Module, Function, Arity} |
                            on_load | send | 'receive',
                        Module :: module(),
                        Function :: atom(),
                        Arity :: arity(),
                        Item ::
                            flags | tracer | traced | match_spec | meta | meta_match_spec | call_count |
                            call_time | call_memory | all,
                        Res :: trace_info_return().

Returns trace information about a port, process, function, or event for the static legacy trace session.

Change

This function is superseded by trace:info/3 that operates on dynamic trace sessions.

Equivalent to erlang:trace_pattern(Event, MatchSpec, []), retained for backward compatibility.

Set trace pattern for call, send and receive tracing on the static legacy trace session.

Change

This function is superseded by trace:function/4, trace:send/3 and trace:recv/3 that operate on dynamic trace sessions.

Argument FlagList can contain two additional options for call tracing:

For further documentation see trace:function/4 , trace:send/3 and trace:recv/3.

Deprecated functions

This function is deprecated. erlang:now/0 is deprecated; see the "Time and Time Correction in Erlang" chapter of the ERTS User's Guide for more information.

-spec now() -> Timestamp when Timestamp :: timestamp().
Warning

This function is deprecated. Do not use it.

For more information, 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 provided by the underlying OS. Otherwise some other point in time is chosen. It is also guaranteed that the following calls to this BIF return continuously increasing values. Hence, the return value from erlang:now/0 can be used to generate unique time stamps. If it is called in a tight loop on a fast machine, the time of the node 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.

This function is deprecated. erlang:phash/2 is deprecated; use erlang:phash2/2 instead.

Warning

This function is deprecated as erlang:phash2/2 should be used for new code. Note that erlang:phash(X,N) is not necessary 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.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4