erlang
(erts)The Erlang BIFs
By convention, most built-in functions (BIFs) are seen as being
in the module erlang
. A number of the BIFs 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 and both the calls atom_to_list(Erlang)
and
erlang:atom_to_list(Erlang)
are identical.
In the text, auto-imported BIFs are listed without module prefix. BIFs listed with module prefix are not auto-imported.
BIFs may fail for a variety of reasons. All BIFs fail with
reason badarg
if they are called with arguments of an
incorrect type. The other reasons that may make BIFs fail are
described in connection with the description of each individual
BIF.
Some BIFs may be used in guard tests, these are marked with "Allowed in guard tests".
A binary data object, structured according to the Erlang external term format.
See now/0.
Functions
abs(Number) -> integer() | float()
Number = number()
Returns an integer or float which is the arithmetical
absolute value of Number
.
>abs(-3.33).
3.33 >abs(-3).
3
Allowed in guard tests.
erlang:adler32(Data) -> integer()
Data = iodata()
Computes and returns the adler32 checksum for Data
.
erlang:adler32(OldAdler, Data) -> integer()
OldAdler = integer()
Data = iodata()
Continue 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).
- would assign the same value to Y
as this would:
Y = erlang:adler32([Data1,Data2]).
erlang:adler32_combine(FirstAdler, SecondAdler, SecondSize) -> integer()
FirstAdler = SecondAdler = integer()
SecondSize = integer()
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).
- would assign the same value to Z
as this would:
X = erlang:adler32(Data1),
Y = erlang:adler32(Data2),
Z = erlang:adler32_combine(X,Y,iolist_size(Data2)).
erlang:append_element(Tuple1, Term) -> Tuple2
Tuple1 = Tuple2 = tuple()
Term = term()
Returns a new tuple which 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(Tuple) ++ [Term])
, but much
faster.
> erlang:append_element({one, two}, three).
{one,two,three}
apply/2
Call a fun, passing the elements in
as
arguments.
Note: If the number of elements in the arguments are known at
compile-time, the call is better written as
.
Warning!
Earlier,
could also be given as
{Module, Function}
, equivalent to
apply(Module, Function, Args)
. This usage is
deprecated and will stop working in a future release of
Erlang/OTP.
apply/3
Returns the result of applying Function
in
to
. The applied function must
be exported from Module
. The arity of the function is
the length of Args
.
> apply(lists, reverse, [[a, b, c]]).
[c,b,a]
apply
can be used to evaluate BIFs by using
the module name erlang
.
> apply(erlang, atom_to_list, ['Erlang']).
"Erlang"
Note: If the number of arguments are known at compile-time,
the call is better written as
.
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 the error_handler
is undefined, or if the user has
redefined the default error_handler
so the replacement
module is undefined, an error with the reason undef
is generated.
atom_to_binary(Atom, Encoding) -> binary()
Atom = atom()
Encoding = latin1 | utf8 | unicode
Returns a binary which corresponds to the text
representation of Atom
. If Encoding
is latin1
, there will be one byte for each character
in the text representation. If Encoding
is utf8
or
unicode
, the characters will encoded using UTF-8
(meaning that characters from 16#80 up to 0xFF will be
encode in two bytes).
Note!
Currently, atom_to_binary(Atom, latin1)
can
never fail because the text representation of an atom can only contain
characters from 0 to 16#FF. In a future release, the text representation
of atoms might be allowed to contain any Unicode character
and atom_to_binary(Atom, latin1)
will fail if the
text representation for the Atom
contains a Unicode
character greater than 16#FF.
> atom_to_binary('Erlang', latin1).
<<"Erlang">>
atom_to_list(Atom) -> string()
Atom = atom()
Returns a string which corresponds to the text
representation of Atom
.
> atom_to_list('Erlang').
"Erlang"
binary_part(Subject, PosLen) -> binary()
Subject = binary()
PosLen = {Start,Length}
Start = integer() >= 0
Length = integer() >= 0
Extracts the part of the binary described by PosLen
.
Negative length can be used to extract bytes at the end of a binary:
1> Bin = <<1,2,3,4,5,6,7,8,9,10>>.
2> binary_part(Bin,{byte_size(Bin), -5)).
<<6,7,8,9,10>>
If PosLen
in any way references outside the binary, a badarg
exception is raised.
Start
is zero-based, i.e:
1> Bin = <<1,2,3>>
2> binary_part(Bin,{0,2}).
<<1,2>>
See the STDLIB module binary
for details about the PosLen
semantics.
Allowed in guard tests.
binary_part(Subject, Start, Length) -> binary()
Subject = binary()
Start = integer() >= 0
Length = integer() >= 0
The same as binary_part(Subject, {Pos, Len})
.
Allowed in guard tests.
binary_to_atom(Binary, Encoding) -> atom()
Binary = binary()
Encoding = latin1 | utf8 | unicode
Returns the atom whose text representation is
Binary
. If Encoding
is latin1
, no
translation of bytes in the binary is done. If Encoding
is utf8
or unicode
, the binary must contain
valid UTF-8 sequences; furthermore, only Unicode characters up
to 0xFF are allowed.
Note!
binary_to_atom(Binary, utf8)
will fail if
the binary contains Unicode characters greater than 16#FF.
In a future release, such Unicode characters might be allowed
and binary_to_atom(Binary, utf8)
will not fail in that case.
>binary_to_atom(<<"Erlang">>, latin1).
'Erlang' >binary_to_atom(<<1024/utf8>>, utf8).
** exception error: bad argument in function binary_to_atom/2 called as binary_to_atom(<<208,128>>,utf8)
binary_to_existing_atom(Binary, Encoding) -> atom()
Binary = binary()
Encoding = latin1 | utf8 | unicode
Works like binary_to_atom/2, but the atom must already exist.
Failure: badarg
if the atom does not already exist.
binary_to_list(Binary) -> [char()]
Binary = binary()
Returns a list of integers which correspond to the bytes of
Binary
.
binary_to_list(Binary, Start, Stop) -> [char()]
Binary = binary()
Start = Stop = 1..byte_size(Binary)
As binary_to_list/1
, but returns a list of integers
corresponding to the bytes from position Start
to
position Stop
in Binary
. Positions in the
binary are numbered starting from 1.
Note!
This function's indexing style of using one-based indices for
binaries is deprecated. New code should use the functions in
the STDLIB module binary
instead. They consequently
use the same (zero-based) style of indexing.
bitstring_to_list(Bitstring) -> [char()|bitstring()]
Bitstring = bitstring()
Returns a list of integers which correspond to the bytes of
Bitstring
. If the number of bits in the binary is not
divisible by 8, the last element of the list will be a bitstring
containing the remaining bits (1 up to 7 bits).
binary_to_term(Binary) -> term()
Binary = ext_binary()
Returns an Erlang term which is the result of decoding
the binary object Binary
, which must be encoded
according to the Erlang external term format.
Warning!
When decoding binaries from untrusted sources, consider using
binary_to_term/2
to prevent denial of service attacks.
See also term_to_binary/1 and binary_to_term/2.
binary_to_term(Binary, Opts) -> term()
Opts = [safe]
Binary = ext_binary()
As binary_to_term/1
, but takes options that affect decoding
of the binary.
safe
Use this option when receiving binaries from an untrusted source.
When enabled, it prevents decoding data that may be used to attack the Erlang system. In the event of receiving unsafe data, decoding fails with a badarg error.
Currently, this prevents creation of new atoms directly, creation of new atoms indirectly (as they are embedded in certain structures like pids, refs, funs, etc.), and creation of new external function references. None of those resources are currently garbage collected, so unchecked creation of them can exhaust available memory.
Failure: badarg
if safe
is specified and unsafe data
is decoded.
See also term_to_binary/1, binary_to_term/1, and list_to_existing_atom/1.
bit_size(Bitstring) -> integer() >= 0
Bitstring = bitstring()
Returns an integer which is the size in bits of Bitstring
.
>bit_size(<<433:16,3:3>>).
19 >bit_size(<<1,2,3>>).
24
Allowed in guard tests.
erlang:bump_reductions(Reductions) -> void()
Reductions = integer() >= 0
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, and a context switch is forced when the counter reaches the maximum number of reductions for a process (2000 reductions in R12B).
Warning!
This BIF might be removed in a future version of the Beam machine without prior warning. It is unlikely to be implemented in other Erlang implementations.
byte_size(Bitstring) -> integer() >= 0
Bitstring = bitstring()
Returns an integer which is the number of bytes needed to contain
Bitstring
. (That is, if the number of bits in Bitstring
is not
divisible by 8, the resulting number of bytes will be rounded up.)
>byte_size(<<433:16,3:3>>).
3 >byte_size(<<1,2,3>>).
3
Allowed in guard tests.
erlang:cancel_timer(TimerRef) -> Time | false
TimerRef = reference()
Time = integer() >= 0
Cancels a timer, where TimerRef
was returned by
either
erlang:send_after/3
or
erlang:start_timer/3.
If the timer is there to be removed, the function returns
the time in milliseconds left until the timer would have expired,
otherwise false
(which means that TimerRef
was
never a timer, that it has already been cancelled, or that it
has already delivered its message).
See also erlang:send_after/3, erlang:start_timer/3, and erlang:read_timer/1.
Note: Cancelling a timer does not guarantee that the message has not already been delivered to the message queue.
check_old_code(Module) -> boolean()
Module = atom()
Returns true
if the Module
has old code,
and false
otherwise.
See also code(3).
check_process_code(Pid, Module) -> boolean()
Pid = pid()
Module = atom()
Returns true
if the process Pid
is executing
old code for Module
. That is, if the current call of
the process executes old code for this module, or if the
process has references to old code for this module, or if the
process contains funs that references old code for this
module. Otherwise, it returns false
.
> check_process_code(Pid, lists).
false
See also code(3).
erlang:crc32(Data) -> integer() >= 0
Data = iodata()
Computes and returns the crc32 (IEEE 802.3 style) checksum for Data
.
erlang:crc32(OldCrc, Data) -> integer() >= 0
OldCrc = integer() >= 0
Data = iodata()
Continue 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).
- would assign the same value to Y
as this would:
Y = erlang:crc32([Data1,Data2]).
erlang:crc32_combine(FirstCrc, SecondCrc, SecondSize) -> integer() >= 0
FirstCrc = SecondCrc = integer() >= 0
SecondSize = integer() >= 0
Combines two previously computed crc32 checksums. This computation requires the size of the data object for the second checksum to be known.
The following code:
Y = erlang:crc32(Data1),
Z = erlang:crc32(Y,Data2).
- would assign the same value to Z
as this would:
X = erlang:crc32(Data1),
Y = erlang:crc32(Data2),
Z = erlang:crc32_combine(X,Y,iolist_size(Data2)).
date() -> Date
Date = calendar:date()
Returns the current date as {Year, Month, Day}
.
The time zone and daylight saving time correction depend on the underlying OS.
> date().
{1995,2,19}
erlang:decode_packet(Type,Bin,Options) -> {ok,Packet,Rest} | {more,Length} | {error,Reason}
Bin = binary()
Options = [Opt]
Packet = binary() | HttpPacket
Rest = binary()
Length = integer() > 0 | undefined
Reason = term()
Type, Opt -- see below
HttpPacket = HttpRequest | HttpResponse | HttpHeader | http_eoh | HttpError
HttpRequest = {http_request, HttpMethod, HttpUri, HttpVersion}
HttpResponse = {http_response, HttpVersion, integer(), HttpString}
HttpHeader = {http_header, integer(), HttpField, Reserved=term(), Value=HttpString}
HttpError = {http_error, HttpString}
HttpMethod = HttpMethodAtom | HttpString
HttpMethodAtom = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE'
HttpUri = '*' | {absoluteURI, http|https, Host=HttpString, Port=integer()|undefined, Path=HttpString} | {scheme, Scheme=HttpString, HttpString} | {abs_path, HttpString} | HttpString
HttpVersion = {Major=integer(), Minor=integer()}
HttpString = string() | binary()
HttpField = HttpFieldAtom | HttpString
HttpFieldAtom = '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'
Decodes the binary Bin
according to the packet
protocol specified by Type
. Very similar to the packet
handling done by sockets with the option {packet,Type}.
If an entire packet is contained in Bin
it is
returned together 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 not known. decode_packet
can then be called again with more data added.
If the packet does not conform to the protocol format
{error,Reason}
is returned.
The following values of Type
are valid:
raw | 0
No packet handling is done. Entire binary is returned unless it is empty.
1 | 2 | 4
Packets consist of a header specifying the number of bytes in the packet, followed by that number of bytes. The length of header can be one, two, or four bytes; the order of the bytes is big-endian. The header will be stripped off when the packet is returned.
line
A packet is a line terminated with newline. The
newline character is included in the returned packet
unless the line was truncated according to the option
line_length
.
asn1 | cdr | sunrm | fcgi | tpkt
The header is not stripped off.
The meanings of the packet types are as follows:
asn1
- ASN.1 BERsunrm
- Sun's RPC encodingcdr
- CORBA (GIOP 1.1)fcgi
- Fast CGItpkt
- TPKT format [RFC1006]http | httph | http_bin | httph_bin
The Hypertext Transfer Protocol. The packets
are returned with the format according to
HttpPacket
described above. A packet is either a
request, a response, a header or an end of header
mark. Invalid lines are returned as HttpError
.
Recognized request methods and header fields are returned as atoms. Others are returned as strings.
The protocol type http
should only be used for
the first line when a HttpRequest
or a
HttpResponse
is expected. The following calls
should use httph
to get HttpHeader
's until
http_eoh
is returned that marks the end of the
headers and the beginning of any following message body.
The variants http_bin
and httph_bin
will return
strings (HttpString
) as binaries instead of lists.
The following options are available:
{packet_size, integer()}
Sets the max allowed size of the packet body. If the packet header indicates that the length of the packet is longer than the max allowed length, the packet is considered invalid. Default is 0 which means no size limit.
{line_length, integer()}
For packet type line
, truncate lines longer
than the indicated length.
Option line_length
also applies to http*
packet types as an alias for option packet_size
in the
case when packet_size
itself is not set. This usage is
only intended for backward compatibility.
>erlang:decode_packet(1,<<3,"abcd">>,[]).
{ok,<<"abc">>,<<"d">>} >erlang:decode_packet(1,<<5,"abcd">>,[]).
{more,6}
delete_module(Module) -> true | undefined
Module = atom()
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(3)) and should not be used elsewhere.
Failure: badarg
if there is already an old version of
Module
.
demonitor(MonitorRef) -> true
MonitorRef = reference()
If MonitorRef
is a reference which 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
due to the monitor will be placed in the callers message queue
in the future. A {'DOWN', MonitorRef, _, _, _}
message
might have been placed in the callers message queue prior to
the call, though. Therefore, in most cases, it is 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!
Prior to OTP release R11B (erts version 5.5) demonitor/1
behaved completely asynchronous, i.e., the monitor was active
until the "demonitor signal" reached the monitored entity. This
had one undesirable effect, though. You could never know when
you were guaranteed not to receive a DOWN
message
due to the monitor.
Current behavior can be viewed as two combined operations: asynchronously send a "demonitor signal" to the monitored entity and ignore any future results of the monitor.
Failure: It is an error if MonitorRef
refers to a
monitoring started by another process. Not all such cases are
cheap to check; if checking is cheap, the call fails with
badarg
(for example if MonitorRef
is a remote
reference).
demonitor(MonitorRef, OptionList) -> boolean()
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).
Currently the following Option
s are valid:
flush
Remove (one) {_, MonitorRef, _, _, _}
message,
if there is one, from the callers message queue after
monitoring has been stopped.
Calling demonitor(MonitorRef, [flush])
is equivalent to the following, but more efficient:
demonitor(MonitorRef), receive {_, MonitorRef, _, _, _} -> true after 0 -> true end
info
The returned value is one of the following:
true
The monitor was found and removed. In this case
no 'DOWN'
message due to this monitor have
been nor will be placed in the message queue
of the caller.
false
The monitor was not found and could not be removed.
This probably because someone already has placed a
'DOWN'
message corresponding to this monitor
in the callers message queue.
If the info
option is combined with the flush
option, false
will be returned if a flush was needed;
otherwise, true
.
Note!
More options may be added in the future.
Failure: badarg
if OptionList
is not a list, or
if Option
is not a valid option, or the same failure as for
demonitor/1
disconnect_node/1
Forces the disconnection of a node. This will appear to
the 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,
the function returns ignored
.
erlang:display(Term) -> true
Term = term()
Prints a text representation of Term
on the standard
output.
Warning!
This BIF is intended for debugging only.
element(N, Tuple) -> term()
N = 1..tuple_size(Tuple)
Tuple = tuple()
Returns the N
th element (numbering from 1) of
Tuple
.
> element(2, {a, b, c}).
b
Allowed in guard tests.
erase() -> [{Key, Val}]
Key = Val = term()
Returns the process dictionary and deletes it.
>put(key1, {1, 2, 3}),
put(key2, [a, b, c]),
erase().
[{key1,{1,2,3}},{key2,[a,b,c]}]
erase(Key) -> Val | undefined
Key = Val = term()
Returns the value Val
associated with Key
and
deletes it from the process dictionary. Returns
undefined
if no value is associated with Key
.
>put(key1, {merry, lambs, are, playing}),
X = erase(key1),
{X, erase(key1)}.
{{merry,lambs,are,playing},undefined}
error(Reason)
Reason = term()
Stops the execution of the calling process with the reason
Reason
, where Reason
is any term. The actual
exit reason will be {Reason, Where}
, where Where
is a list of the functions most recently called (the current
function first). Since evaluating this function causes
the process to terminate, it has no return value.
> catch error(foobar).
{'EXIT',{foobar,[{erl_eval,do_apply,5},
{erl_eval,expr,5},
{shell,exprs,6},
{shell,eval_exprs,6},
{shell,eval_loop,3}]}}
error(Reason, Args)
Reason = term()
Args = [term()]
Stops the execution of the calling process with the reason
Reason
, where Reason
is any term. The actual
exit reason will be {Reason, Where}
, where Where
is a list of the functions most recently called (the current
function first). Args
is expected to be the list of
arguments for the current function; in Beam it will be used
to provide the actual arguments for the current function in
the Where
term. Since evaluating this function causes
the process to terminate, it has no return value.
exit(Reason)
Reason = term()
Stops the execution of the calling process with the exit
reason Reason
, where Reason
is any term. Since
evaluating this function causes the process to terminate, it
has no return value.
>exit(foobar).
** exception exit: foobar >catch exit(foobar).
{'EXIT',foobar}
exit(Pid, Reason) -> true
Pid = pid()
Reason = term()
Sends an exit signal with exit reason Reason
to
the process Pid
.
The following behavior apply if Reason
is any term
except normal
or kill
:
If Pid
is not trapping exits, Pid
itself will
exit with exit reason Reason
. If Pid
is trapping
exits, the exit signal is transformed into a message
{'EXIT', From, Reason}
and delivered to the message
queue of Pid
. From
is the pid of the process
which sent the exit signal. See also
process_flag/2.
If Reason
is the atom normal
, Pid
will
not exit. If it is trapping exits, the exit signal is
transformed into a message {'EXIT', From, normal}
and delivered to its message queue.
If Reason
is the atom kill
, that is if
exit(Pid, kill)
is called, an untrappable exit signal
is sent to Pid
which will unconditionally exit with
exit reason killed
.
erlang:external_size(Term) -> integer() >= 0
Term = term()
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
This is equivalent to a call to: erlang:external_size(Term, [])
erlang:external_size(Term, [Option]) -> integer() >= 0
Term = term()
Option = {minor_version, Version}
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
The option {minor_version, Version}
specifies how floats
are encoded. See
term_to_binary/2 for
a more detailed description.
float(Number) -> float()
Number = number()
Returns a float by converting Number
to a float.
> float(55).
55.0
Allowed in guard tests.
Note!
Note that if used on the top-level in a guard, it will test 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 above.
float_to_list(Float) -> string()
Float = float()
Returns a string which corresponds to the text
representation of Float
.
> float_to_list(7.0).
"7.00000000000000000000e+00"
fun_info/1
Returns a list containing information about the fun
. Each element of the list is a tuple. The order of
the tuples is not defined, and more tuples may be added in a
future release.
Warning!
This BIF is mainly intended for debugging, but it can occasionally be useful in library functions that might need to verify, for instance, the arity of a fun.
There are two types of funs with slightly different semantics:
A fun created by fun M:F/A
is called an
external fun. Calling it will always call the
function F
with arity A
in the latest code for
module M
. Note that module M
does not even need
to be loaded when the fun fun M:F/A
is created.
All other funs are called local. When a local fun is called, the same version of the code that created the fun will be called (even if newer version of the module has been loaded).
The following elements will always be present in the list for both local and external funs:
{type, Type}
Type
is either local
or external
.
{module, Module}
Module
(an atom) is the module name.
If Fun
is a local fun, Module
is the module
in which the fun is defined.
If Fun
is an external fun, Module
is the
module that the fun refers to.
{name, Name}
Name
(an atom) is a function name.
If Fun
is a local fun, Name
is the name
of the local function that implements the fun.
(This name was generated by the compiler, and is generally
only of informational use. As it is a local function, it
is not possible to call it directly.)
If no code is currently loaded for the fun, []
will be returned instead of an atom.
If Fun
is an external fun, Name
is the name
of the exported function that the fun refers to.
{arity, Arity}
Arity
is the number of arguments that the fun
should be called with.
{env, Env}
Env
(a list) is the environment or free variables
for the fun. (For external funs, the returned list is
always empty.)
The following elements will only be present in the list if
Fun
is local:
{pid, Pid}
Pid
is the pid of the process that originally
created the fun.
{index, Index}
Index
(an integer) is an index into the module's
fun table.
{new_index, Index}
Index
(an integer) is an index into the module's
fun table.
{new_uniq, Uniq}
Uniq
(a binary) is a unique value for this fun.
It is calculated from the compiled code for the entire module.
{uniq, Uniq}
Uniq
(an integer) is a unique value for this fun.
Starting in the R15 release, this integer is calculated from
the compiled code for the entire module. Before R15, this
integer was based on only the body of the fun.
erlang:fun_info(Fun, Item) -> {Item, Info}
Fun = fun()
Item, Info -- see below
Returns information about Fun
as specified by
Item
, in the form {Item,Info}
.
For any fun, Item
can be any of the atoms
module
, name
, arity
, env
, or type
.
For a local fun, Item
can also be any of the atoms
index
, new_index
, new_uniq
,
uniq
, and pid
. For an external fun, the value
of any of these items is always the atom undefined
.
See erlang:fun_info/1.
erlang:fun_to_list(Fun) -> string()
Fun = fun()
Returns a string which corresponds to the text
representation of Fun
.
erlang:function_exported(Module, Function, Arity) -> boolean()
Module = Function = atom()
Arity = arity()
Returns true
if the module Module
is loaded
and contains an exported function Function/Arity
;
otherwise false
.
Returns false
for any BIF (functions implemented in C
rather than in Erlang).
garbage_collect() -> true
Forces an immediate garbage collection of the currently executing process. The function should not 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. Improper use may seriously degrade system performance.
Compatibility note: In versions of OTP prior to R7,
the garbage collection took place at the next context switch,
not immediately. To force a context switch after a call to
erlang:garbage_collect()
, it was sufficient to make
any function call.
garbage_collect(Pid) -> boolean()
Pid = pid()
Works like erlang:garbage_collect()
but on any
process. The same caveats apply. Returns false
if
Pid
refers to a dead process; true
otherwise.
get() -> [{Key, Val}]
Key = Val = term()
Returns the process dictionary as a list of
{Key, Val}
tuples.
>put(key1, merry),
put(key2, lambs),
put(key3, {are, playing}),
get().
[{key1,merry},{key2,lambs},{key3,{are,playing}}]
get(Key) -> Val | undefined
Key = Val = term()
Returns the value Val
associated with Key
in
the process dictionary, or undefined
if Key
does not exist.
>put(key1, merry),
put(key2, lambs),
put({any, [valid, term]}, {are, playing}),
get({any, [valid, term]}).
{are,playing}
get_cookie/0
Returns the magic cookie of the local node, if the node is
alive; otherwise the atom nocookie
.
get_keys(Val) -> [Key]
Val = Key = term()
Returns a list of keys which are associated with the value
Val
in the process dictionary.
>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]
erlang:get_stacktrace() -> [{Module, Function, Arity | Args, Location}]
Module = Function = atom()
Arity = arity()
Args = [term()]
Location = [{atom(),term()}]
Get the call stack back-trace (stacktrace) of the last
exception in the calling process as a list of
{Module,Function,Arity,Location}
tuples.
The Arity
field in the first tuple may be the argument
list of that function call instead of an arity integer,
depending on the exception.
If there has not been any exceptions in a process, the stacktrace is []. After a code change for the process, the stacktrace may also be reset to [].
The stacktrace is the same data as the catch
operator
returns, for example:
{'EXIT',{badarg,Stacktrace}} = catch abs(x)
Location
is a (possibly empty) list of two-tuples that
may indicate the location in the source code of the function.
The first element is an atom that describes the type of
information in the second element. Currently the following
items may occur:
file
The second element of the tuple is a string (list of characters) representing the filename of the source file of the function.
line
The second element of the tuple is the line number (an integer greater than zero) in the source file where the exception occurred or the function was called.
See also erlang:error/1 and erlang:error/2.
group_leader() -> GroupLeader
GroupLeader = pid()
Returns the pid of the group leader for the process which evaluates the function.
Every process is a member of some process group and all
groups have a group leader. All IO 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 start-up, init
is both
its own group leader and the group leader of all processes.
group_leader(GroupLeader, Pid) -> true
GroupLeader = Pid = pid()
Sets the group leader of Pid
to GroupLeader
.
Typically, this is used when a processes started from a
certain shell should have another group leader than
init
.
See also group_leader/0.
halt()
Halts the Erlang runtime system and indicates normal exit to the calling environment. Has no return value.
> halt().
os_prompt%
halt(Status)
Status = integer() >= 0 | string()
Status
must be a non-negative integer, or a string.
Halts the Erlang runtime system. Has no return value.
If Status
is an integer, it is returned as an exit
status of Erlang to the calling environment.
If Status
is a string, produces an Erlang crash dump
with String
as slogan, and then exits with a non-zero
status code.
Note that on many platforms, only the status codes 0-255 are supported by the operating system.
erlang:hash(Term, Range) -> Hash
Returns a hash value for Term
within the range
1..Range
. The allowed range is 1..2^27-1.
Warning!
This BIF is deprecated as the hash value may differ on
different architectures. Also the hash values for integer
terms larger than 2^27 as well as large binaries are very
poor. The BIF is retained for backward compatibility
reasons (it may have been used to hash records into a file),
but all new code should use one of the BIFs
erlang:phash/2
or erlang:phash2/1,2
instead.
hd(List) -> term()
List = [term()]
Returns the head of List
, that is, the first element.
> hd([1,2,3,4,5]).
1
Allowed in guard tests.
Failure: badarg
if List
is the empty list [].
erlang:hibernate(Module, Function, Args)
Module = Function = atom()
Args = [term()]
Puts the calling process into a wait state where its memory allocation has been reduced as much as possible, which is useful if the process does not expect to receive any messages in the near future.
The process will be awaken when a message is sent to it, and
control will resume in Module:Function
with
the arguments given by Args
with the call stack
emptied, meaning that the process will terminate when that
function returns. Thus erlang:hibernate/3
will never
return to its caller.
If the process has any message in its message queue, the process will be awaken immediately in the same way as described above.
In more technical terms, what erlang:hibernate/3
does
is the following. It discards the call stack for the process.
Then it garbage collects the process. After the garbage
collection, all live data is in one continuous heap. The heap
is then shrunken to the exact same size as the live data
which 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 has been awaken will ensure that the heap size is changed to a size not smaller than the minimum heap size.
Note that emptying the call stack means that any surrounding
catch
is removed and has to be re-inserted after
hibernation. One effect of this is that processes started
using proc_lib
(also indirectly, such as
gen_server
processes), should use
proc_lib:hibernate/3
instead to ensure that the exception handler continues to work
when the process wakes up.
integer_to_list(Integer) -> string()
Integer = integer()
Returns a string which corresponds to the text
representation of Integer
.
> integer_to_list(77).
"77"
integer_to_list/2
Returns a string which corresponds to the text
representation of
in base
.
> integer_to_list(1023, 16).
"3FF"
iolist_to_binary(IoListOrBinary) -> binary()
IoListOrBinary = iolist() | binary()
Returns a binary which is made from the integers and
binaries in IoListOrBinary
.
>Bin1 = <<1,2,3>>.
<<1,2,3>> >Bin2 = <<4,5>>.
<<4,5>> >Bin3 = <<6>>.
<<6>> >iolist_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6>>
iolist_size(Item) -> integer() >= 0
Item = iolist() | binary()
Returns an integer which is the size in bytes
of the binary that would be the result of
iolist_to_binary(Item)
.
> iolist_size([1,2|<<3,4>>]).
4
is_alive() -> boolean()
Returns true
if the local node is alive; that is, if
the node can be part of a distributed system. Otherwise, it
returns false
.
is_atom(Term) -> boolean()
Term = term()
Returns true
if Term
is an atom;
otherwise returns false
.
Allowed in guard tests.
is_binary(Term) -> boolean()
Term = term()
Returns true
if Term
is a binary;
otherwise returns false
.
A binary always contains a complete number of bytes.
Allowed in guard tests.
is_bitstring(Term) -> boolean()
Term = term()
Returns true
if Term
is a bitstring (including a binary);
otherwise returns false
.
Allowed in guard tests.
is_boolean(Term) -> boolean()
Term = term()
Returns true
if Term
is
either the atom true
or the atom false
(i.e. a boolean); otherwise returns false
.
Allowed in guard tests.
erlang:is_builtin(Module, Function, Arity) -> boolean()
Module = Function = atom()
Arity = arity()
Returns true
if Module:Function/Arity
is
a BIF implemented in C; otherwise returns false
.
This BIF is useful for builders of cross reference tools.
is_float(Term) -> boolean()
Term = term()
Returns true
if Term
is a floating point
number; otherwise returns false
.
Allowed in guard tests.
is_function(Term) -> boolean()
Term = term()
Returns true
if Term
is a fun; otherwise
returns false
.
Allowed in guard tests.
is_function(Term, Arity) -> boolean()
Term = term()
Arity = arity()
Returns true
if Term
is a fun that can be
applied with Arity
number of arguments; otherwise
returns false
.
Allowed in guard tests.
Warning!
Currently, is_function/2
will also return
true
if the first argument is a tuple fun (a tuple
containing two atoms). In a future release, tuple funs will
no longer be supported and is_function/2
will return
false
if given a tuple fun.
is_integer(Term) -> boolean()
Term = term()
Returns true
if Term
is an integer;
otherwise returns false
.
Allowed in guard tests.
is_list(Term) -> boolean()
Term = term()
Returns true
if Term
is a list with
zero or more elements; otherwise returns false
.
Allowed in guard tests.
is_number(Term) -> boolean()
Term = term()
Returns true
if Term
is either an integer or a
floating point number; otherwise returns false
.
Allowed in guard tests.
is_pid(Term) -> boolean()
Term = term()
Returns true
if Term
is a pid (process
identifier); otherwise returns false
.
Allowed in guard tests.
is_port(Term) -> boolean()
Term = term()
Returns true
if Term
is a port identifier;
otherwise returns false
.
Allowed in guard tests.
is_process_alive(Pid) -> boolean()
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
.
is_record(Term, RecordTag) -> boolean()
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, that its first element is RecordTag
, and that
the size is correct. However, if the RecordTag
is
not a literal atom, the is_record/2
BIF will be
called instead and the size of the tuple will not be
verified.
Allowed in guard tests, if RecordTag
is a literal
atom.
is_record(Term, RecordTag, Size) -> boolean()
Term = term()
RecordTag = atom()
Size = integer()
RecordTag
must be an 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, provided that RecordTag
is
a literal atom and Size
is a literal integer.
Note!
This BIF is documented for completeness. In most cases
is_record/2
should be used.
is_reference(Term) -> boolean()
Term = term()
Returns true
if Term
is a reference;
otherwise returns false
.
Allowed in guard tests.
is_tuple(Term) -> boolean()
Term = term()
Returns true
if Term
is a tuple;
otherwise returns false
.
Allowed in guard tests.
length(List) -> integer() >= 0
List = [term()]
Returns the length of List
.
> length([1,2,3,4,5,6,7,8,9]).
9
Allowed in guard tests.
link(Pid) -> true
Pid = pid() | port()
Creates a link between the calling process and another
process (or port) Pid
, if there is not such a link
already. If a process attempts to create a link to itself,
nothing is done. Returns true
.
If Pid
does not exist, the behavior of the BIF depends
on if the calling process is trapping exits or not (see
process_flag/2):
- If the calling process is not trapping exits, and
checking
Pid
is cheap -- that is, ifPid
is local --link/1
fails with reasonnoproc
. - Otherwise, if the calling process is trapping exits,
and/or
Pid
is remote,link/1
returnstrue
, but an exit signal with reasonnoproc
is sent to the calling process.
list_to_atom(String) -> atom()
String = string()
Returns the atom whose text representation is String
.
> list_to_atom("Erlang").
'Erlang'
list_to_binary(IoList) -> binary()
IoList = iolist()
Returns a binary which is made from the integers and
binaries in IoList
.
>Bin1 = <<1,2,3>>.
<<1,2,3>> >Bin2 = <<4,5>>.
<<4,5>> >Bin3 = <<6>>.
<<6>> >list_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6>>
list_to_bitstring(BitstringList) -> bitstring()
BitstringList = [BitstringList | bitstring() | char()]
Returns a bitstring which is made from the integers and
bitstrings in BitstringList
. (The last tail in BitstringList
is allowed to be a bitstring.)
>Bin1 = <<1,2,3>>.
<<1,2,3>> >Bin2 = <<4,5>>.
<<4,5>> >Bin3 = <<6,7:4,>>.
<<6>> >list_to_binary([Bin1,1,[2,3,Bin2],4|Bin3]).
<<1,2,3,1,2,3,4,5,4,6,7:46>>
list_to_existing_atom(String) -> atom()
String = string()
Returns the atom whose text representation is String
,
but only if there already exists such atom.
Failure: badarg
if there does not already exist an atom
whose text representation is String
.
list_to_float(String) -> float()
String = string()
Returns the float whose text representation is String
.
> list_to_float("2.2017764e+0").
2.2017764
Failure: badarg
if String
contains a bad
representation of a float.
list_to_integer(String) -> integer()
String = string()
Returns an integer whose text representation is
String
.
> list_to_integer("123").
123
Failure: badarg
if String
contains a bad
representation of an integer.
list_to_integer/2
Returns an integer whose text representation in base
is
.
> list_to_integer("3FF", 16).
1023
Failure: badarg
if
contains a bad
representation of an integer.
list_to_pid(String) -> pid()
String = string()
Returns a pid whose text representation is String
.
Warning!
This BIF is intended for debugging and for use in the Erlang operating system. It should not be used in application programs.
> list_to_pid("<0.4.1>").
<0.4.1>
Failure: badarg
if String
contains a bad
representation of a pid.
list_to_tuple(List) -> tuple()
List = [term()]
Returns a tuple which corresponds to List
. List
can contain any Erlang terms.
> list_to_tuple([share, ['Ericsson_B', 163]]).
{share, ['Ericsson_B', 163]}
load_module(Module, Binary) -> {module, Module} | {error, Reason}
Module = atom()
Binary = binary()
Reason = badfile | not_purged | badfile
If Binary
contains the object code for the module
Module
, this BIF loads that object code. Also, if
the code for the 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 may still be processes which are
executing that code. It returns either
{module, Module}
, or {error, Reason}
if loading
fails. Reason
is one of the following:
badfile
The object code in Binary
has an incorrect format.
not_purged
Binary
contains a module which cannot be loaded
because old code for this module already exists.
badfile
The object code contains code for another module than
Module
Warning!
This BIF is intended for the code server (see code(3)) and should not be used elsewhere.
erlang:load_nif(Path, LoadInfo) -> ok | {error, {Reason, Text}}
Path = string()
LoadInfo = term()
Reason = load_failed | bad_lib | load | reload | upgrade | old_code
Text = string()
Note!
In releases older than OTP R14B, NIFs were an
experimental feature. Versions of OTP older than R14B might
have different and possibly incompatible NIF semantics and
interfaces. For example, in R13B03 the return value on
failure was
{error,Reason,Text}
.
Loads and links a dynamic library containing native
implemented functions (NIFs) for a module. Path
is a
file path to the sharable object/dynamic library file minus
the OS-dependent file extension (.so for Unix and .dll for
Windows). See erl_nif
on how to implement a NIF library.
LoadInfo
can be any term. It will be 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 atoms below,
while Text
is a human readable string that may give
some more information about the failure.
load_failed
The OS failed to load the NIF library.
bad_lib
The library did not fulfil the requirements as a NIF library of the calling module.
load | reload | upgrade
The corresponding library callback was not successful.
old_code
The call to load_nif/2
was made from the old
code of a module that has been upgraded. This is not
allowed.
erlang:loaded() -> [Module]
Module = atom()
Returns a list of all loaded Erlang modules (current and/or old code), including preloaded modules.
See also code(3).
erlang:localtime() -> DateTime
DateTime = calendar:datetime()
Returns the current local date and time
{{Year, Month, Day}, {Hour, Minute, Second}}
.
The time zone and daylight saving time correction depend on the underlying OS.
> erlang:localtime().
{{1996,11,6},{14,45,17}}
localtime_to_universaltime/1
Converts local date and time to Universal Time Coordinated
(UTC), if this is supported by the underlying OS. Otherwise,
no conversion is done and {
is returned.
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}).
{{1996,11,6},{13,45,17}}
Failure: badarg
if Date1
or Time1
do
not denote a valid date or time.
erlang:localtime_to_universaltime({Date1, Time1}, IsDst) -> {Date2, Time2}
Date1 = Date2 = calendar:date()
Time1 = Time2 = calendar:time()
IsDst = true | false | undefined
Converts local date and time to Universal Time Coordinated
(UTC) just like erlang:localtime_to_universaltime/1
,
but the caller decides if daylight saving time is active or
not.
If IsDst == true
the {Date1, Time1}
is during
daylight saving time, if IsDst == false
it is not,
and if IsDst == undefined
the underlying OS may
guess, which is the same as calling
erlang:localtime_to_universaltime({Date1, Time1})
.
>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 Date1
or Time1
do
not denote a valid date or time.
make_ref() -> reference()
Returns an almost unique reference.
The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes.
> make_ref().
#Ref<0.0.0.135>
erlang:make_tuple(Arity, InitialValue) -> tuple()
Arity = arity()
InitialValue = term()
Returns a new tuple of the given Arity
, where all
elements are InitialValue
.
> erlang:make_tuple(4, []).
{[],[],[],[]}
erlang:make_tuple(Arity, Default, InitList) -> tuple()
Arity = arity()
Default = term()
InitList = [{Position,term()}]
Position = integer()
erlang:make_tuple
first creates a tuple of size Arity
where each element has the value Default
. It 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
last occurrence will be used.
> erlang:make_tuple(5, [], [{2,ignored},{5,zz},{2,aa}]).
{{[],aa,[],[],zz}
max/2
Return the largest of
and
;
if the terms compare equal,
will be returned.
erlang:md5(Data) -> Digest
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.
See The MD5 Message Digest Algorithm (RFC 1321) for more information about MD5.
Warning!
The MD5 Message Digest Algorithm is not considered safe for code-signing or software integrity purposes.
erlang:md5_final(Context) -> Digest
Context = Digest = binary()
Finishes the update of an MD5 Context
and returns
the computed MD5
message digest.
erlang:md5_init() -> Context
Context = binary()
Creates an MD5 context, to be used in subsequent calls to
md5_update/2
.
erlang:md5_update(Context, Data) -> NewContext
Data = iodata()
Context = NewContext = binary()
Updates an MD5 Context
with Data
, and returns
a NewContext
.
erlang:memory() -> [{Type, Size}]
Type, Size -- see below
Returns a list containing information about memory
dynamically allocated by the Erlang emulator. Each element of
the list is a tuple {Type, Size}
. The first element
Type
is an atom describing memory type. The second
element Size
is memory size in bytes. A description of
each memory type follows:
total
The total amount of memory currently allocated, which is
the same as the sum of memory size for processes
and system
.
processes
The total amount of memory currently allocated by the Erlang processes.
processes_used
The total amount of memory currently used by the Erlang processes.
This memory is part of the memory presented as
processes
memory.
system
The total amount of memory currently allocated by the emulator that is not directly related to any Erlang process.
Memory presented as processes
is not included in
this memory.
atom
The total amount of memory currently allocated for atoms.
This memory is part of the memory presented as
system
memory.
atom_used
The total amount of memory currently used for atoms.
This memory is part of the memory presented as
atom
memory.
binary
The total amount of memory currently allocated for binaries.
This memory is part of the memory presented as
system
memory.
code
The total amount of memory currently allocated for Erlang code.
This memory is part of the memory presented as
system
memory.
ets
The total amount of memory currently allocated for ets tables.
This memory is part of the memory presented as
system
memory.
maximum
The maximum total amount of memory allocated since the emulator was started.
This tuple is only present when the emulator is run with instrumentation.
For information on how to run the emulator with instrumentation see instrument(3) and/or erl(1).
low
Only on 64-bit halfword emulator.
The total amount of memory allocated in low memory areas that are restricted to less than 4 Gb even though the system may have more physical memory.
May be removed in future releases of halfword emulator.
Note!
The system
value is not complete. Some allocated
memory that should be part of the system
value are
not.
When the emulator is run with instrumentation,
the system
value is more accurate, but memory
directly allocated by malloc
(and friends) are 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.
Since the total
value is the sum of processes
and system
the error in system
will propagate
to the total
value.
The different amounts of memory that are summed are not gathered atomically which also introduce an error in the result.
The different values has 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 may be added in the future.
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 stack(s) 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.
Furthermore, due to fragmentation and pre-reservation of
memory areas, the size of the memory segments which contain
the dynamically allocated memory blocks can be substantially
larger than the total size of the dynamically allocated
memory blocks.
Note!
Since erts version 5.6.4 erlang:memory/0
requires that
all erts_alloc(3)
allocators are enabled (default behaviour).
Failure:
notsup
erlang:memory(Type | [Type]) -> Size | [{Type, Size}]
Type, Size -- see below
Returns the memory size in bytes allocated for memory of
type Type
. The argument can also be given as a list
of Type
atoms, in which case a corresponding list of
{Type, Size}
tuples is returned.
Note!
Since erts version 5.6.4 erlang:memory/1
requires that
all erts_alloc(3)
allocators are enabled (default behaviour).
Failures:
badarg
Type
is not one of the memory types listed in the
documentation of
erlang:memory/0.
badarg
maximum
is passed as Type
and the emulator
is not run in instrumented mode.
notsup
See also erlang:memory/0.
min/2
Return the smallest of
and
;
if the terms compare equal,
will be returned.
module_loaded(Module) -> boolean()
Module = atom()
Returns true
if the module Module
is loaded,
otherwise returns false
. It does not attempt to load
the module.
Warning!
This BIF is intended for the code server (see code(3)) and should not be used elsewhere.
monitor(Type, Item) -> MonitorRef
Type = process
Item = pid() | {RegName, Node} | RegName
RegName = atom()
Node = node()
MonitorRef = reference()
The calling process starts monitoring Item
which is
an object of type Type
.
Currently only processes can be monitored, i.e. the only
allowed Type
is process
, but other types may be
allowed in the future.
Item
can be:
pid()
The pid of the process to monitor.
{RegName, Node}
A tuple consisting of a registered name of a process and
a node name. The process residing on the node Node
with the registered name RegName
will be monitored.
RegName
The process locally registered as RegName
will be
monitored.
Note!
When a process is monitored by registered name, the process
that has the registered name at the time when
monitor/2
is called will be monitored.
The monitor will not be effected, if the registered name is
unregistered.
A 'DOWN'
message will be sent to the monitoring
process if Item
dies, if Item
does not exist,
or if the connection is lost to the node which Item
resides on. A 'DOWN'
message has the following pattern:
{'DOWN', MonitorRef, Type, Object, Info}
where MonitorRef
and Type
are the same as
described above, and:
Object
A reference to the monitored object:
- the pid of the monitored process, if
Item
was specified as a pid. {RegName, Node}
, ifItem
was specified as{RegName, Node}
.{RegName, Node}
, ifItem
was specified asRegName
.Node
will in this case be the name of the local node (node()
).
Info
Either the exit reason of the process, noproc
(non-existing process), or noconnection
(no
connection to Node
).
Note!
If/when monitor/2
is extended (e.g. to
handle other item types than process
), other
possible values for Object
, and Info
in the
'DOWN'
message will be introduced.
The monitoring is turned off either when the 'DOWN'
message is sent, or when
demonitor/1
is called.
If an attempt is made to monitor a process on an older node
(where remote process monitoring is not implemented or one
where remote process monitoring by registered name is not
implemented), the call fails with badarg
.
Making several calls to monitor/2
for the same
Item
is not an error; it results in as many, completely
independent, monitorings.
Note!
The format of the 'DOWN'
message changed in the 5.2
version of the emulator (OTP release R9B) for monitor by registered name. The Object
element of
the 'DOWN'
message could in earlier versions
sometimes be the pid of the monitored process and sometimes
be the registered name. Now the Object
element is
always a tuple consisting of the registered name and
the node name. Processes on new nodes (emulator version 5.2
or greater) will always get 'DOWN'
messages on
the new format even if they are monitoring processes on old
nodes. Processes on old nodes will always get 'DOWN'
messages on the old format.
monitor_node(Node, Flag) -> true
Node = node()
Flag = boolean()
Monitors the status of the node Node
. If Flag
is true
, monitoring is turned on; if Flag
is
false
, monitoring is turned off.
Making several calls to monitor_node(Node, true)
for
the same Node
is not an error; it results in as many,
completely independent, monitorings.
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
, there will be an attempt to create one. If this
fails, a nodedown
message is delivered.
Nodes connected through hidden connections can be monitored as any other node.
Failure: badarg
if the local node is not alive.
erlang:monitor_node(Node, Flag, Options) -> true
Node = node()
Flag = boolean()
Options = [Option]
Option = allow_passive_connect
Behaves as monitor_node/2
except that it allows an
extra option to be given, namely allow_passive_connect
.
The option allows the BIF to wait the normal net connection
timeout for the monitored node to connect itself,
even if it cannot be actively connected from this node
(i.e. it is blocked). The state where this might be useful can
only be achieved by using the kernel option
dist_auto_connect once
. If that kernel option is not
used, the allow_passive_connect
option has no
effect.
Note!
The allow_passive_connect
option is used
internally and is seldom needed in applications where the
network topology and the kernel options in effect is known in
advance.
Failure: badarg
if the local node is not alive or the
option list is malformed.
erlang:nif_error(Reason)
Reason = term()
Works exactly like erlang: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 will not generate false warnings.
erlang:nif_error(Reason, Args)
Reason = term()
Args = [term()]
Works exactly like erlang: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 will not generate false warnings.
node() -> Node
Node = node()
Returns the name of the local node. If the node is not alive,
nonode@nohost
is returned instead.
Allowed in guard tests.
node(Arg) -> Node
Arg = pid() | port() | reference()
Node = node()
Returns the node where Arg
is located. Arg
can
be a pid, a reference, or a port. If the local node is not
alive, nonode@nohost
is returned.
Allowed in guard tests.
nodes/0
Returns a list of all visible nodes in the system, excluding
the local node. Same as nodes(visible)
.
nodes(Arg | [Arg]) -> Nodes
Arg = visible | hidden | connected | this | known
Nodes = [node()]
Returns a list of nodes according to argument given. The result returned when the argument is a list, is the list of nodes satisfying the disjunction(s) of the list elements.
Arg
can be any of the following:
visible
Nodes connected to this node through normal connections.
hidden
Nodes connected to this node through hidden connections.
connected
All nodes connected to this node.
this
This node.
known
Nodes which are known to this node, i.e., connected, previously connected, etc.
Some equalities: [node()] = nodes(this)
,
nodes(connected) = nodes([visible, hidden])
, and
nodes() = nodes(visible)
.
If the local node is not alive,
nodes(this) == nodes(known) == [nonode@nohost]
, for
any other Arg
the empty list [] is returned.
now() -> timestamp()
timestamp() = {MegaSecs, Secs, MicroSecs}
MegaSecs = Secs = MicroSecs = integer() >= 0
Returns the tuple {MegaSecs, Secs, MicroSecs}
which is
the elapsed time since 00:00 GMT, January 1, 1970 (zero hour)
on the assumption that the underlying OS supports this.
Otherwise, some other point in time is chosen. It is also
guaranteed that subsequent calls to this BIF returns
continuously increasing values. Hence, the return value from
now()
can be used to generate unique time-stamps,
and if it is called in a tight loop on a fast machine
the time of the node can become skewed.
It can only be used to check the local time of day if the time-zone info of the underlying operating system is properly configured.
open_port(PortName, PortSettings) -> port()
PortName = {spawn, Command} | {spawn_driver, Command} | {spawn_executable, FileName} | {fd, In, Out}
Command = string()
FileName = [ FileNameChar ] | binary()
FileNameChar = integer() (1..255 or any Unicode codepoint, see description)
In = Out = integer()
PortSettings = [Opt]
Opt = {packet, N} | stream | {line, L} | {cd, Dir} | {env, Env} | {args, [ ArgString ]} | {arg0, ArgString} | exit_status | use_stdio | nouse_stdio | stderr_to_stdout | in | out | binary | eof
N = 1 | 2 | 4
L = integer()
Dir = string()
ArgString = [ FileNameChar ] | binary()
Env = [{Name, Val}]
Name = string()
Val = string() | false
Returns a port identifier as the result of opening a
new Erlang port. A port can be seen as an external Erlang
process. PortName
is one of the following:
{spawn, Command}
Starts an external program. Command
is the name
of the external program which will be run. Command
runs outside the Erlang work space unless an Erlang
driver with the name Command
is found. If found,
that driver will be started. A driver runs in the Erlang
workspace, which means that it is linked with the Erlang
runtime system.
When starting external programs on Solaris, the system
call vfork
is used in preference to fork
for performance reasons, although it has a history of
being less robust. If there are problems with using
vfork
, setting the environment variable
ERL_NO_VFORK
to any value will cause fork
to be used instead.
For external programs, the PATH
is searched
(or an equivalent method is used to find programs,
depending on operating system). This is done by invoking
the shell on certain platforms. The first space
separated token of the command will be considered as the
name of the executable (or driver). This (among other
things) makes this option unsuitable for running
programs having spaces in file or directory names. Use
{spawn_executable, Command} instead if spaces in executable
file names is desired.
{spawn_driver, Command}
Works like {spawn, Command}
, but demands the
first (space separated) token of the command to be the name of a
loaded driver. If no driver with that name is loaded, a
badarg
error is raised.
{spawn_executable, Command}
Works like {spawn, Command}
, but only runs
external executables. The Command
in its whole
is used as the name of the executable, including any
spaces. If arguments are to be passed, the
args
and arg0
PortSettings
can be used.
The shell is not usually invoked to start the
program, it's executed directly. Neither is the
PATH
(or equivalent) searched. To find a program
in the PATH to execute, use os:find_executable/1.
Only if a shell script or .bat
file is
executed, the appropriate command interpreter will
implicitly be invoked, but there will still be no
command argument expansion or implicit PATH search.
The name of the executable as well as the arguments
given in args
and arg0
is subject to
Unicode file name translation if the system is running
in Unicode file name mode. To avoid
translation or force i.e. UTF-8, supply the executable
and/or arguments as a binary in the correct
encoding. See the file module, the
file:native_name_encoding/0 function and the
stdlib users guide
for details.
Note!
The characters in the name (if given as a list) can only be > 255 if the Erlang VM is started in Unicode file name translation mode, otherwise the name of the executable is limited to the ISO-latin-1 character set.
If the Command
cannot be run, an error
exception, with the posix error code as the reason, is
raised. The error reason may differ between operating
systems. Typically the error enoent
is raised
when one tries to run a program that is not found and
eaccess
is raised when the given file is not
executable.
{fd, In, Out}
Allows an Erlang process to access any currently opened
file descriptors used by Erlang. The file descriptor
In
can be used for standard input, and the file
descriptor Out
for standard output. It is only
used for various servers in the Erlang operating system
(shell
and user
). Hence, its use is very
limited.
PortSettings
is a list of settings for the port.
Valid settings are:
{packet, N}
Messages are preceded by their length, sent in N
bytes, with the most significant byte first. Valid values
for N
are 1, 2, or 4.
stream
Output messages are sent without packet lengths. A user-defined protocol must be used between the Erlang process and the external object.
{line, L}
Messages are delivered on a per line basis. Each line
(delimited by the OS-dependent newline sequence) is
delivered in one single message. The message data format
is {Flag, Line}
, where Flag
is either
eol
or noeol
and Line
is the actual
data delivered (without the newline sequence).
L
specifies the maximum line length in bytes.
Lines longer than this will be delivered in more than one
message, with the Flag
set to noeol
for all
but the last message. If end of file is encountered
anywhere else than immediately following a newline
sequence, the last line will also be delivered with
the Flag
set to noeol
. In all other cases,
lines are delivered with Flag
set to eol
.
The {packet, N}
and {line, L}
settings are
mutually exclusive.
{cd, Dir}
This is only valid for {spawn, Command}
and
{spawn_executable, Command}
.
The external program starts using Dir
as its
working directory. Dir
must be a string. Not
available on VxWorks.
{env, Env}
This is only valid for {spawn, Command}
and
{spawn_executable, Command}
.
The environment of the started process is extended using
the environment specifications in Env
.
Env
should be a list of tuples {Name, Val}
,
where Name
is the name of an environment variable,
and Val
is the value it is to have in the spawned
port process. Both Name
and Val
must be
strings. The one exception is Val
being the atom
false
(in analogy with os:getenv/1
), which
removes the environment variable. Not available on
VxWorks.
{args, [ string() ]}
This option is only valid for {spawn_executable, Command}
and specifies arguments to the executable. Each argument
is given as a separate string and (on Unix) eventually
ends up as one element each in the argument vector. On
other platforms, similar behavior is mimicked.
The arguments are not expanded by the shell prior to being supplied to the executable, most notably this means that file wildcard expansion will not happen. Use filelib:wildcard/1 to expand wildcards for the arguments. Note that even if the program is a Unix shell script, meaning that the shell will ultimately be invoked, wildcard expansion will not happen and the script will be provided with the untouched arguments. On Windows�, wildcard expansion is always up to the program itself, why this isn't an issue.
Note also that the actual executable name (a.k.a. argv[0]
)
should not be given in this list. The proper executable name will
automatically be used as argv[0] where applicable.
When the Erlang VM is running in Unicode file name mode, the arguments can contain any Unicode characters and will be translated into whatever is appropriate on the underlying OS, which means UTF-8 for all platforms except Windows, which has other (more transparent) ways of dealing with Unicode arguments to programs. To avoid Unicode translation of arguments, they can be supplied as binaries in whatever encoding is deemed appropriate.
Note!
The characters in the arguments (if given as a list of characters) can only be > 255 if the Erlang VM is started in Unicode file name mode, otherwise the arguments are limited to the ISO-latin-1 character set.
If one, for any reason, wants to explicitly set the
program name in the argument vector, the arg0
option can be used.
{arg0, string()}
This option is only valid for {spawn_executable, Command}
and explicitly specifies the program name argument when
running an executable. This might in some circumstances,
on some operating systems, be desirable. How the program
responds to this is highly system dependent and no specific
effect is guaranteed.
The unicode file name translation rules of the
args
option apply to this option as well.
exit_status
This is only valid for {spawn, Command}
where
Command
refers to an external program, and for
{spawn_executable, Command}
.
When the external process connected to the port exits, a
message of the form {Port,{exit_status,Status}}
is
sent to the connected process, where Status
is the
exit status of the external process. If the program
aborts, on Unix the same convention is used as the shells
do (i.e., 128+signal).
If the eof
option has been given as well,
the eof
message and the exit_status
message
appear in an unspecified order.
If the port program closes its stdout without exiting,
the exit_status
option will not work.
use_stdio
This is only valid for {spawn, Command}
and
{spawn_executable, Command}
. It
allows the standard input and output (file descriptors 0
and 1) of the spawned (UNIX) process for communication
with Erlang.
nouse_stdio
The opposite of use_stdio
. Uses file descriptors
3 and 4 for communication with Erlang.
stderr_to_stdout
Affects ports to external programs. The executed program
gets its standard error file redirected to its standard
output file. stderr_to_stdout
and
nouse_stdio
are mutually exclusive.
overlapped_io
Affects ports to external programs on Windows� only. The standard input and standard output handles of the port program will, if this option is supplied, be opened with the flag FILE_FLAG_OVERLAPPED, so that the port program can (and has to) do overlapped I/O on its standard handles. This is not normally the case for simple port programs, but an option of value for the experienced Windows programmer. On all other platforms, this option is silently discarded.
in
The port can only be used for input.
out
The port can only be used for output.
binary
All IO from the port are binary data objects as opposed to lists of bytes.
eof
The port will not be closed at the end of the file and
produce an exit signal. Instead, it will remain open and
a {Port, eof}
message will be sent to the process
holding the port.
hide
When running on Windows, suppress creation of a new console window when spawning the port program. (This option has no effect on other platforms.)
The default is stream
for all types of port 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 which
most closely describes the error, or einval
if no Posix code
is appropriate:
badarg
Bad input arguments to open_port
.
system_limit
All available ports in the Erlang emulator are in use.
enomem
There was not enough memory to create the port.
eagain
There are no more available operating system processes.
enametoolong
The external command given was too long.
emfile
There are no more available file descriptors (for the operating system process that the Erlang emulator runs in).
enfile
The file table is full (for the entire operating system).
eacces
The Command
given in {spawn_executable, Command}
does not point out an executable file.
enoent
The Command
given in {spawn_executable, Command}
does not point out an existing file.
During use of a port opened using {spawn, Name}
,
{spawn_driver, Name}
or {spawn_executable, Name}
,
errors arising when sending messages to it are reported to
the owning process using signals of the form
{'EXIT', Port, PosixCode}
. See file(3)
for
possible values of PosixCode
.
The maximum number of ports that can be open at the same
time is 1024 by default, but can be configured by
the environment variable ERL_MAX_PORTS
.
erlang:phash(Term, Range) -> Hash
Term = term()
Range = 1..2^32
Hash = 1..Range
Portable hash function that will give 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). Range
can be between 1 and 2^32, the function returns a hash value
for Term
within the range 1..Range
.
This BIF could be used instead of the old deprecated
erlang:hash/2
BIF, as it calculates better hashes for
all data-types, but consider using phash2/1,2
instead.
erlang:phash2(Term [, Range]) -> Hash
Term = term()
Range = 1..2^32
Hash = 0..Range-1
Portable hash function that will give the same hash for
the same Erlang term regardless of machine architecture and
ERTS version (the BIF was introduced in ERTS 5.2). Range can
be between 1 and 2^32, the function returns a hash value for
Term
within the range 0..Range-1
. When called
without the Range
argument, a value in the range
0..2^27-1
is returned.
This BIF should always be used for hashing terms. It
distributes small integers better than phash/2
, and
it is faster for bignums and binaries.
Note that the range 0..Range-1
is different from
the range of phash/2
(1..Range
).
pid_to_list(Pid) -> string()
Pid = pid()
Returns a string which corresponds to the text
representation of Pid
.
Warning!
This BIF is intended for debugging and for use in the Erlang operating system. It should not be used in application programs.
port_close(Port) -> true
Port = port() | atom()
Closes an open port. Roughly the same as
Port ! {self(), close}
except for the error behaviour
(see below), and that the port does not reply with
{Port, closed}
. Any process may close a port with
port_close/1
, not only the port owner (the connected
process).
For comparison: Port ! {self(), close}
fails with
badarg
if Port
cannot be sent to (i.e.,
Port
refers neither to a port nor to 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, but if
the calling process is not the port owner the port owner fails with badsig
.
Note that any process can close a port using
Port ! {PortOwner, close}
just as if it itself was
the port owner, but the reply always goes to the port owner.
In short: port_close(Port)
has a cleaner and more
logical behaviour than Port ! {self(), close}
.
Failure: badarg
if Port
is not an open port or
the registered name of an open port.
port_command(Port, Data) -> true
Port = port() | atom()
Data = iodata()
Sends data to a port. Same as
Port ! {self(), {command, Data}}
except for the error
behaviour (see below). Any process may send data to a port
with port_command/2
, not only the port owner
(the connected process).
For comparison: Port ! {self(), {command, Data}}
fails with badarg
if Port
cannot be sent to
(i.e., Port
refers neither to a port nor to 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 not a valid IO list.
Note that any process can send to a port using
Port ! {PortOwner, {command, Data}}
just as if it
itself was the port owner.
In short: port_command(Port, Data)
has a cleaner and
more logical behaviour than
Port ! {self(), {command, Data}}
.
If the port is busy, the calling process will be suspended until the port is not busy anymore.
Failures:
badarg
Port
is not an open port or the registered name
of an open port.
badarg
Data
is not a valid io list.
port_command(Port, Data, OptionList) -> boolean()
Port = port() | atom()
Data = iodata()
OptionList = [Option]
Option = force
Option = nosuspend
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
is returned.
If the port is busy, the calling process will be suspended until the port is not busy anymore.
Currently the following Option
s are valid:
force
notsup
exception if the
driver of the port does not support this. For more
information see the
ERL_DRV_FLAG_SOFT_BUSY
driver flag.
nosuspend
false
is returned.
Note!
More options may be added in the future.
Failures:
badarg
Port
is not an open port or the registered name
of an open port.
badarg
Data
is not a valid io list.
badarg
OptionList
is not a valid option list.
notsup
force
option has been passed, but the
driver of the port does not allow forcing through
a busy port.
port_connect(Port, Pid) -> true
Port = port() | atom()
Pid = pid()
Sets the port owner (the connected port) to Pid
.
Roughly the same as Port ! {self(), {connect, Pid}}
except for the following:
-
The error behavior differs, see below.
-
The port does not reply with
{Port,connected}
. -
The new port owner gets linked to the port.
The old port owner stays linked to the port and have to call
unlink(Port)
if this is not desired. Any process may
set the port owner to be any process with
port_connect/2
.
For comparison: Port ! {self(), {connect, Pid}}
fails
with badarg
if Port
cannot be sent to (i.e.,
Port
refers neither to a port nor to 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. Note that the old port owner is still linked to
the port, and that 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 pid.
Note that any process can set the port owner using
Port ! {PortOwner, {connect, Pid}}
just as if it
itself was the port owner, but the reply always goes to
the port owner.
In short: port_connect(Port, Pid)
has a cleaner and
more logical behaviour than
Port ! {self(),{connect,Pid}}
.
Failure: badarg
if Port
is not an open port
or the registered name of an open port, or if Pid
is
not an existing local pid.
port_control(Port, Operation, Data) -> Res
Port = port() | atom()
Operation = integer()
Data = Res = iodata()
Performs a synchronous control operation on a port.
The meaning of Operation
and Data
depends on
the port, i.e., on the port driver. Not all port drivers
support this control feature.
Returns: a list of integers in the range 0 through 255, or a binary, depending on the port driver. The meaning of the returned data also depends on the port driver.
Failure: badarg
if Port
is not an open port or
the registered name of an open port, if Operation
cannot fit in a 32-bit integer, if the port driver does not
support synchronous control operations, or if the port driver
so decides for any reason (probably something wrong with
Operation
or Data
).
erlang:port_call(Port, Operation, Data) -> term()
Port = port() | atom()
Operation = integer()
Data = term()
Performs a synchronous call to a port. The meaning of
Operation
and Data
depends on the port, i.e.,
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.
Failure: badarg
if Port
is not an open port or
the registered name of an open port, if Operation
cannot fit in a 32-bit integer, if the port driver does not
support synchronous control operations, or if the port driver
so decides for any reason (probably something wrong with
Operation
or Data
).
erlang:port_info(Port) -> [{Item, Info}] | undefined
Port = port() | atom()
Item, Info -- see below
Returns a list containing tuples with information about
the Port
, or undefined
if the port is not open.
The order of the tuples is not defined, nor are all the
tuples mandatory.
{registered_name, RegName}
RegName
(an atom) is the registered name of
the port. If the port has no registered name, this tuple
is not present in the list.
{id, Index}
Index
(an integer) is the internal index of the
port. This index may be used to separate ports.
{connected, Pid}
Pid
is the process connected to the port.
{links, Pids}
Pids
is a list of pids to which processes the
port is linked.
{name, String}
String
is the command name set by
open_port
.
{input, Bytes}
Bytes
is the total number of bytes read from
the port.
{output, Bytes}
Bytes
is the total number of bytes written to
the port.
Failure: badarg
if Port
is not a local port.
erlang:port_info(Port, Item) -> {Item, Info} | undefined | []
Port = port() | atom()
Item, Info -- see below
Returns information about Port
as specified
by Item
, or undefined
if the port is not open.
Also, if Item == registered_name
and the port has no
registered name, [] is returned.
For valid values of Item
, and corresponding
values of Info
, see
erlang:port_info/1.
Failure: badarg
if Port
is not a local port.
erlang:port_to_list(Port) -> string()
Port = port()
Returns a string which corresponds to the text
representation of the port identifier Port
.
Warning!
This BIF is intended for debugging and for use in the Erlang operating system. It should not be used in application programs.
erlang:ports() -> [port()]
Returns a list of all ports on the local node.
pre_loaded() -> [Module]
Module = atom()
Returns a list of Erlang modules which are pre-loaded in
the system. As all loading of code is done through the file
system, the file system must have been loaded previously.
Hence, at least the module init
must be pre-loaded.
erlang:process_display(Pid, Type) -> void()
Pid = pid()
Type = backtrace
Writes information about the local process Pid
on
standard error. The currently allowed value for the atom
Type
is backtrace
, which shows the contents of
the call stack, including information about the call chain, with
the current function printed first. The format of the output
is not further defined.
process_flag(Flag, Value) -> OldValue
Flag, Value, OldValue -- see below
Sets certain flags for the process which calls this function. Returns the old value of the flag.
process_flag(trap_exit, Boolean)
When trap_exit
is set to true
, exit signals
arriving to a process are converted to {'EXIT', From, Reason}
messages, which can be received as ordinary
messages. If trap_exit
is set to false
, the
process exits if it receives an exit signal other than
normal
and the exit signal is propagated to its
linked processes. Application processes should normally
not trap exits.
See also exit/2.
process_flag(error_handler, Module)
This is used by a process to redefine the error handler for undefined function calls and undefined registered processes. Inexperienced users should not use this flag since code auto-loading is dependent on the correct operation of the error handling module.
process_flag(min_heap_size, MinHeapSize)
This changes the minimum heap size for the calling process.
process_flag(min_bin_vheap_size, MinBinVHeapSize)
This changes the minimum binary virtual heap size for the calling process.
process_flag(priority, Level)
This sets the process priority. Level
is an atom.
There are currently four priority levels: low
,
normal
, high
, and max
. The default
priority level is normal
. NOTE: The
max
priority level is reserved for internal use in
the Erlang runtime system, and should not be used
by others.
Internally in each priority level processes are scheduled in a round robin fashion.
Execution of processes on priority normal
and
priority low
will be interleaved. Processes on
priority low
will be selected for execution less
frequently than processes on priority normal
.
When there are runnable processes on priority high
no processes on priority low
, or normal
will
be selected for execution. Note, however, that this does
not mean that no processes on priority low
,
or normal
will be able to run when there are
processes on priority high
running. On the runtime
system with SMP support there might be more processes running
in parallel than processes on priority high
, i.e.,
a low
, and a high
priority process might
execute at the same time.
When there are runnable processes on priority max
no processes on priority low
, normal
, or
high
will be selected for execution. As with the
high
priority, processes on lower priorities might
execute in parallel with processes on priority max
.
Scheduling is preemptive. Regardless of priority, a process is preempted when it has consumed more than a certain amount of reductions since the last time it was selected for execution.
NOTE: You should not depend on the scheduling to remain exactly as it is today. Scheduling, at least on the runtime system with SMP support, is very likely to be modified in the future in order to better utilize available processor cores.
There is currently no automatic mechanism for avoiding priority inversion, such as priority inheritance, or priority ceilings. When using priorities you have to take this into account and handle such scenarios by yourself.
Making calls from a high
priority process into code
that you don't have control over may cause the high
priority process to wait for a processes with lower
priority, i.e., effectively decreasing the priority of the
high
priority process during the call. Even if this
isn't the case with one version of the code that you don't
have under your control, it might be the case in a future
version of it. This might, for example, happen if a
high
priority process triggers code loading, since
the code server runs on priority normal
.
Other priorities than normal
are normally not needed.
When other priorities are used, they need to be used
with care, especially the high
priority must
be used with care. A process on high
priority should
only perform work for short periods of time. Busy looping for
long periods of time in a high
priority process will
most likely cause problems, since there are important servers
in OTP running on priority normal
.
process_flag(save_calls, N)
N
must be an integer in the interval 0..10000.
If N
> 0, call saving is made active for the
process, which means that information about the N
most recent global function calls, BIF calls, sends and
receives made by the process are saved in a list, which
can be retrieved with
process_info(Pid, last_calls)
. A global function
call is one in which the module of the function is
explicitly mentioned. Only a fixed amount of information
is saved: a tuple {Module, Function, Arity}
for
function calls, and the mere atoms send
,
'receive'
and timeout
for sends and receives
('receive'
when a message is received and
timeout
when a receive times out). If N
= 0,
call saving is disabled for the process, which is the
default. Whenever the size of the call saving list is set,
its contents are reset.
process_flag(sensitive, Boolean)
Set or clear the sensitive
flag for the current process.
When a process has been marked as sensitive by calling
process_flag(sensitive, true)
, features in the run-time
system that can be used for examining the data and/or inner working
of the process are silently disabled.
Features that are disabled include (but are not limited to) the following:
Tracing: Trace flags can still be set for the process, but no
trace messages of any kind will be generated.
(If the sensitive
flag is turned off, trace messages will
again be generated if there are any trace flags set.)
Sequential tracing: The sequential trace token will be propagated as usual, but no sequential trace messages will be generated.
process_info/1,2
cannot be used to read out the message
queue or the process dictionary (both will be returned as empty lists).
Stack back-traces cannot be displayed for the process.
In crash dumps, the stack, messages, and the process dictionary will be omitted.
If {save_calls,N}
has been set for the process, no
function calls will be saved to the call saving list.
(The call saving list will not be cleared; furthermore, send, receive,
and timeout events will still be added to the list.)
process_flag(Pid, Flag, Value) -> OldValue
Pid = pid()
Flag, Value, OldValue -- see below
Sets certain flags for the process Pid
, in the same
manner as
process_flag/2.
Returns the old value of the flag. The allowed 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.
process_info(Pid) -> InfoResult
Pid = pid()
Item = atom()
Info = term()
InfoTuple = {Item, Info}
InfoTupleList = [InfoTuple]
InfoResult = InfoTupleList | undefined
Returns a list containing InfoTuple
s with
miscellaneous information about the process identified by
Pid
, or undefined
if the process is not alive.
The order of the InfoTuple
s is not defined, nor
are all the InfoTuple
s mandatory. The InfoTuple
s
part of the result may be changed without prior notice.
Currently InfoTuple
s with the following Item
s
are part of the result:
current_function
, initial_call
, status
,
message_queue_len
, messages
, links
,
dictionary
, trap_exit
, error_handler
,
priority
, group_leader
, total_heap_size
,
heap_size
, stack_size
, reductions
, and
garbage_collection
.
If the process identified by Pid
has a registered name
also an InfoTuple
with Item == registered_name
will appear.
See process_info/2
for information about specific InfoTuple
s.
Warning!
This BIF is intended for debugging only, use process_info/2 for all other purposes.
Failure: badarg
if Pid
is not a local process.
process_info(Pid, ItemSpec) -> InfoResult
Pid = pid()
Item = atom()
Info = term()
ItemList = [Item]
ItemSpec = Item | ItemList
InfoTuple = {Item, Info}
InfoTupleList = [InfoTuple]
InfoResult = InfoTuple | InfoTupleList | undefined | []
Returns information about the process identified by Pid
as specified by the ItemSpec
, or undefined
if the
process is not alive.
If the process is alive and ItemSpec
is a single
Item
, the returned value is the corresponding
InfoTuple
unless ItemSpec == registered_name
and the process has no registered name. In this case
[]
is returned. This strange behavior is due to
historical reasons, and is kept for backward compatibility.
If ItemSpec
is an ItemList
, the result is an
InfoTupleList
. The InfoTuple
s in the
InfoTupleList
will appear with the corresponding
Item
s in the same order as the Item
s appeared
in the ItemList
. Valid Item
s may appear multiple
times in the ItemList
.
Note!
If registered_name
is part of an ItemList
and the process has no name registered a
{registered_name, []}
InfoTuple
will
appear in the resulting InfoTupleList
. This
behavior is different than when
ItemSpec == registered_name
, and than when
process_info/1
is used.
Currently the following InfoTuple
s with corresponding
Item
s are valid:
{backtrace, Bin}
The binary Bin
contains the same information as
the output from
erlang:process_display(Pid, backtrace)
. Use
binary_to_list/1
to obtain the string of characters
from the binary.
{binary, BinInfo}
BinInfo
is a list containing miscellaneous information
about binaries currently being referred to by this process.
This InfoTuple
may be changed or removed without prior
notice.
{catchlevel, CatchLevel}
CatchLevel
is the number of currently active
catches in this process. This InfoTuple
may be
changed or removed without prior notice.
{current_function, {Module, Function, Arity}}
Module
, Function
, Arity
is
the current function call of the process.
{current_location, {Module, Function, Arity, Location}}
Module
, Function
, Arity
is
the current function call of the process.
Location
is a list of two-tuples that describes the
location in the source code.
{current_stacktrace, Stack}
Return the current call stack back-trace (stacktrace) of the process. The stack has the same format as returned by erlang:get_stacktrace/0.
{dictionary, Dictionary}
Dictionary
is the dictionary of the process.
{error_handler, Module}
Module
is the error handler module used by
the process (for undefined function calls, for example).
{garbage_collection, GCInfo}
GCInfo
is a list which contains miscellaneous
information about garbage collection for this process.
The content of GCInfo
may be changed without
prior notice.
{group_leader, GroupLeader}
GroupLeader
is group leader for the IO of
the process.
{heap_size, Size}
Size
is the size in words of youngest heap generation
of the process. This generation currently include the stack
of the process. This information is highly implementation
dependent, and may change if the implementation change.
{initial_call, {Module, Function, Arity}}
Module
, Function
, Arity
is
the initial function call with which the process was
spawned.
{links, Pids}
Pids
is a list of pids, with processes to
which the process has a link.
{last_calls, false|Calls}
The value is false
if call saving is not active
for the process (see
process_flag/3).
If call saving is active, a list is returned, in which
the last element is the most recent called.
{memory, Size}
Size
is the size in bytes of the process. This
includes call stack, heap and internal structures.
{message_binary, BinInfo}
BinInfo
is a list containing miscellaneous information
about binaries currently being referred to by the message
area. This InfoTuple
is only valid on an emulator
using the hybrid heap type. This InfoTuple
may be
changed or removed without prior notice.
{message_queue_len, MessageQueueLen}
MessageQueueLen
is the number of messages
currently in the message queue of the process. This is
the length of the list MessageQueue
returned as
the info item messages
(see below).
{messages, MessageQueue}
MessageQueue
is a list of the messages to
the process, which have not yet been processed.
{min_heap_size, MinHeapSize}
MinHeapSize
is the minimum heap size for the process.
{min_bin_vheap_size, MinBinVHeapSize}
MinBinVHeapSize
is the minimum binary virtual heap size for the process.
{monitored_by, Pids}
A list of pids that are monitoring the process (with
monitor/2
).
{monitors, Monitors}
A list of monitors (started by monitor/2
)
that are active for the process. For a local process
monitor or a remote process monitor by pid, the list item
is {process, Pid}
, and for a remote process
monitor by name, the list item is
{process, {RegName, Node}}
.
{priority, Level}
Level
is the current priority level for
the process. For more information on priorities see
process_flag(priority, Level).
{reductions, Number}
Number
is the number of reductions executed by
the process.
{registered_name, Atom}
Atom
is the registered name of the process. If
the process has no registered name, this tuple is not
present in the list.
{sequential_trace_token, [] | SequentialTraceToken}
SequentialTraceToken
the sequential trace token for
the process. This InfoTuple
may be changed or removed
without prior notice.
{stack_size, Size}
Size
is the stack size of the process in words.
{status, Status}
Status
is the status of the process. Status
is exiting
, garbage_collecting
,
waiting
(for a message), running
,
runnable
(ready to run, but another process is
running), or suspended
(suspended on a "busy" port
or by the erlang:suspend_process/[1,2]
BIF).
{suspending, SuspendeeList}
SuspendeeList
is a list of {Suspendee,
ActiveSuspendCount, OutstandingSuspendCount}
tuples.
Suspendee
is the pid of a process that have been or is to
be suspended by the process identified by Pid
via the
erlang:suspend_process/2
BIF, or the
erlang:suspend_process/1
BIF. ActiveSuspendCount
is the number of times the
Suspendee
has been suspended by Pid
.
OutstandingSuspendCount
is the number of not yet
completed suspend requests sent by Pid
. That is,
if ActiveSuspendCount /= 0
, Suspendee
is
currently in the suspended state, and if
OutstandingSuspendCount /= 0
the asynchronous
option of erlang:suspend_process/2
has been used and
the suspendee has not yet been suspended by Pid
.
Note that the ActiveSuspendCount
and
OutstandingSuspendCount
are not the total suspend count
on Suspendee
, only the parts contributed by Pid
.
{total_heap_size, Size}
Size
is the total size in words of all heap
fragments of the process. This currently include the stack
of the process.
{trace, InternalTraceFlags}
InternalTraceFlags
is an integer representing
internal trace flag for this process. This InfoTuple
may be changed or removed without prior notice.
{trap_exit, Boolean}
Boolean
is true
if the process is trapping
exits, otherwise it is false
.
Note however, that not all implementations support every one
of the above Items
.
Failure: badarg
if Pid
is not a local process,
or if Item
is not a valid Item
.
processes() -> [pid()]
Returns a list of process identifiers corresponding to all the processes currently existing on the local node.
Note that a process that is exiting, exists but is not alive, i.e.,
is_process_alive/1
will return false
for a process
that is exiting, but its process identifier will be part
of the result returned from processes/0
.
> processes().
[<0.0.0>,<0.2.0>,<0.4.0>,<0.5.0>,<0.7.0>,<0.8.0>]
purge_module(Module) -> void()
Module = atom()
Removes old code for Module
. Before this BIF is used,
erlang:check_process_code/2
should be called to check
that no processes are executing old code in the module.
Warning!
This BIF is intended for the code server (see code(3)) and should not be used elsewhere.
Failure: badarg
if there is no old code for
Module
.
put(Key, Val) -> OldVal | undefined
Key = Val = OldVal = term()
Adds a new Key
to the process dictionary, associated
with the value Val
, and returns undefined
. If
Key
already exists, the old value is deleted and
replaced by Val
and the function returns the old value.
Note!
The values stored when put
is evaluated within
the scope of a catch
will not be retracted if a
throw
is evaluated, or if an error occurs.
>X = put(name, walrus), Y = put(name, carpenter),
Z = get(name),
{X, Y, Z}.
{undefined,walrus,carpenter}
erlang:raise(Class, Reason, Stacktrace)
Class = error | exit | throw
Reason = term()
Stacktrace = [{Module, Function, Arity | Args} | {Fun, Args}]
Module = Function = atom()
Arity = arity()
Args = [term()]
Fun = [fun()]
Stops the execution of the calling process with an exception of given class, reason and call stack backtrace (stacktrace).
Warning!
This BIF is intended for debugging and for use in the Erlang operating system. In general, it should be avoided in applications, unless you know very well what you are doing.
Class
is one of error
, exit
or
throw
, so if it were not for the stacktrace
erlang:raise(Class, Reason, Stacktrace)
is
equivalent to erlang:Class(Reason)
.
Reason
is any term and Stacktrace
is a list as
returned from get_stacktrace()
, that is a list of
4-tuples {Module, Function, Arity | Args,
Location}
where Module
and Function
are atoms and the third element is an integer arity or an
argument list. The stacktrace may also contain {Fun,
Args, Location}
tuples where
Fun
is a local fun and Args
is an argument list.
The Location
element 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 will be truncated to the current maximum stacktrace depth.
Because 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, that is badarg
. If you want to be
really sure not to return you can call
error(erlang:raise(Class, Reason, Stacktrace))
and hope to distinguish exceptions later.
erlang:read_timer(TimerRef) -> integer() >= 0 | false
TimerRef = reference()
TimerRef
is a timer reference returned by
erlang:send_after/3
or
erlang:start_timer/3.
If the timer is active, the function returns the time in
milliseconds left until the timer will expire, otherwise
false
(which means that TimerRef
was never a
timer, that it has been cancelled, or that it has already
delivered its message).
See also erlang:send_after/3, erlang:start_timer/3, and erlang:cancel_timer/1.
erlang:ref_to_list(Ref) -> string()
Ref = reference()
Returns a string which corresponds to the text
representation of Ref
.
Warning!
This BIF is intended for debugging and for use in the Erlang operating system. It should not be used in application programs.
register(RegName, Pid | Port) -> true
RegName = atom()
Pid = pid()
Port = port()
Associates the name RegName
with a pid or a port
identifier. RegName
, which must be an atom, can be used
instead of the pid / port identifier in the send operator
(RegName ! Message
).
> register(db, Pid).
true
Failure: badarg
if Pid
is not an existing,
local process or port, if RegName
is already in use,
if the process or port is already registered (already has a
name), or if RegName
is the atom undefined
.
registered() -> [RegName]
RegName = atom()
Returns a list of names which have been registered using register/2.
> registered().
[code_server, file_server, init, user, my_db]
erlang:resume_process(Suspendee) -> true
Suspendee = pid()
Decreases the suspend count on the process identified by
Suspendee
. Suspendee
should previously have been
suspended via
erlang:suspend_process/2,
or
erlang:suspend_process/1
by the process calling erlang:resume_process(Suspendee)
. When
the suspend count on Suspendee
reach zero, Suspendee
will be resumed, i.e., the state of the Suspendee
is changed
from suspended into the state Suspendee
was in before it was
suspended.
Warning!
This BIF is intended for debugging only.
Failures:
badarg
Suspendee
isn't a process identifier.
badarg
erlang:resume_process/1
had
not previously increased the suspend count on the process
identified by Suspendee
.
badarg
Suspendee
is not alive.
round(Number) -> integer()
Number = number()
Returns an integer by rounding Number
.
> round(5.5).
6
Allowed in guard tests.
self() -> pid()
Returns the pid (process identifier) of the calling process.
> self().
<0.26.0>
Allowed in guard tests.
erlang:send(Dest, Msg) -> Msg
Dest = pid() | port() | RegName | {RegName, Node}
Msg = term()
RegName = atom()
Node = node()
Sends a message and returns Msg
. This is the same as
Dest ! Msg
.
Dest
may be a remote or local pid, a (local) port, a
locally registered name, or a tuple {RegName, Node}
for a registered name at another node.
erlang:send(Dest, Msg, [Option]) -> Res
Dest = pid() | port() | RegName | {RegName, Node}
RegName = atom()
Node = node()
Msg = term()
Option = nosuspend | noconnect
Res = ok | nosuspend | noconnect
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. See
also
erlang:send_nosuspend/2,3.
for more detailed explanation and warnings.
The possible options are:
nosuspend
If the sender would have to be suspended to do the send,
nosuspend
is returned instead.
noconnect
If the destination node would have to be auto-connected
before doing the send, noconnect
is returned
instead.
Warning!
As with erlang:send_nosuspend/2,3
: Use with extreme
care!
erlang:send_after(Time, Dest, Msg) -> TimerRef
Time = integer() >= 0
0 <= Time <= 4294967295
Dest = pid() | RegName
LocalPid = pid() (of a process, alive or dead, on the local node)
Msg = term()
TimerRef = reference()
Starts a timer which will send the message Msg
to Dest
after Time
milliseconds.
If Dest
is an atom, it is supposed to be the name of
a registered process. The process referred to by the name is
looked up at the time of delivery. No error is given if
the name does not refer to a process.
If Dest
is a pid, the timer will be automatically
canceled if the process referred to by the pid is not alive,
or when the process exits. This feature was introduced in
erts version 5.4.11. Note that timers will not be
automatically canceled when Dest
is an atom.
See also erlang:start_timer/3, erlang:cancel_timer/1, and erlang:read_timer/1.
Failure: badarg
if the arguments does not satisfy
the requirements specified above.
send_nosuspend/2
The same as
erlang:send(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 towards 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 will not send the message but return false
instead.
The same happens, if
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 very 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 will actually
be shut down (due to tick timeouts) by net_kernel
. The
normal reaction to take when this happens is some kind of
premature shutdown of the other node.
Note that ignoring the return value from this function would
result in unreliable message passing, which is
contradictory to the Erlang programming model. The message is
not sent if this function returns false
.
Note also that in many systems, transient states of
overloaded queues are normal. The fact that this function
returns false
does not in any way 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 could be sent on the (TCP) channel
without blocking, the message is not guaranteed to have
arrived at the remote node. Also in the case of a disconnected
non-responsive node, the return value is true
(mimics
the behaviour of the !
operator). The expected
behaviour as well as the actions to take when the function
returns false
are application and hardware specific.
Warning!
Use with extreme care!
send_nosuspend/3
The same as
erlang:send(
This function behaves like
erlang:send_nosuspend/2),
but takes a third parameter, a list of options. The only
currently implemented option is noconnect
. The option
noconnect
makes the function return false
if
the remote node is not currently reachable by the local
node. The normal behaviour is to try to connect to the node,
which may stall the process for a shorter period. The use of
the noconnect
option makes it possible to be
absolutely sure not to get even the slightest delay when
sending to a remote process. This is especially useful when
communicating with nodes who expect to always be
the connecting part (i.e. 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!
set_cookie/2
Sets the magic cookie of
to the atom
. If
is the local node, the function
also sets the cookie of all other unknown nodes to
(see
Distributed Erlang in the Erlang Reference Manual).
Failure: function_clause
if the local node is not
alive.
setelement(Index, Tuple1, Value) -> Tuple2
Index = 1..tuple_size(Tuple1)
Tuple1 = Tuple2 = tuple()
Value = term()
Returns a tuple which is a copy of the argument Tuple1
with the element given by the integer argument Index
(the first element is the element with index 1) replaced by
the argument Value
.
> setelement(2, {10, green, bottles}, red).
{10,red,bottles}
size(Item) -> integer() >= 0
Item = tuple() | binary()
Returns an integer which is the size of the argument
Item
, which must be either a tuple or a binary.
> size({morni, mulle, bwange}).
3
Allowed in guard tests.
spawn/1
Returns the pid of a new process started by the application
of
to the empty list []
. Otherwise works
like spawn/3.
spawn/2
Returns the pid of a new process started by the application
of
to the empty list []
on
. If
does not exist, a useless pid is returned.
Otherwise works like
spawn/3.
spawn(Module, Function, Args) -> pid()
Module = Function = atom()
Args = [term()]
Returns the pid of a new process started by the application
of Module:Function
to Args
. The new process
created will be placed in the system scheduler queue and be
run some time later.
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
its replacement is
undefined, a failure with the reason undef
will occur.
> spawn(speed, regulator, [high_speed, thin_cut]).
<0.13.1>
spawn/4
Returns the pid of a new process started by the application
of
to
on Node
. If
does not exists, a useless pid is returned.
Otherwise works like
spawn/3.
spawn_link/1
Returns the pid of a new process started by the application
of
to the empty list []. A link is created between
the calling process and the new process, atomically.
Otherwise works like
spawn/3.
spawn_link/2
Returns the pid of a new process started by the application
of
to the empty list [] on
. A link is
created between the calling process and the new process,
atomically. If
does not exist, a useless pid is
returned (and due to the link, an exit signal with exit
reason noconnection
will be received). Otherwise works
like spawn/3.
spawn_link(Module, Function, Args) -> pid()
Module = Function = atom()
Args = [term()]
Returns the pid 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.
spawn_link/4
Returns the pid of a new process started by the application
of
to
on Node
. A
link is created between the calling process and the new
process, atomically. If
does not exist, a useless
pid is returned (and due to the link, an exit signal with exit
reason noconnection
will be received). Otherwise works
like spawn/3.
spawn_monitor/1
Returns the pid of a new process started by the application
of
to the empty list [] and reference for a monitor
created to the new process.
Otherwise works like
spawn/3.
spawn_monitor/3
A new process is started by the application
of
to
, and the process is
monitored at the same time. Returns the pid and a reference
for the monitor.
Otherwise works like
spawn/3.
spawn_opt/2
Returns the pid of a new process started by the application
of
to the empty list []
. Otherwise
works like
spawn_opt/4.
If the option monitor
is given, the newly created
process will be monitored and both the pid and reference for
the monitor will be returned.
spawn_opt/3
Returns the pid of a new process started by the application
of
to the empty list []
on
. If
does not exist, a useless pid is returned.
Otherwise works like
spawn_opt/4.
spawn_opt/4
Works exactly like spawn/3, except that an extra option list is given when creating the process.
If the option monitor
is given, the newly created
process will be monitored and both the pid and reference for
the monitor will be returned.
link
Sets a link to the parent process (like
spawn_link/3
does).
monitor
Monitor the new process (just like monitor/2 does).
{priority, Level }
Sets the priority of the new process. Equivalent to
executing
process_flag(priority,
{fullsweep_after, Number }
This option is only useful for performance tuning. In general, you should not use this option unless you know that there is problem with execution times and/or memory consumption, and you should measure to make sure that the option improved matters.
The Erlang runtime system uses a generational garbage collection scheme, using an "old heap" for data that has survived at least one garbage collection. When there is no more room on the old heap, a fullsweep garbage collection will be done.
The fullsweep_after
option makes it possible to
specify the maximum number of generational collections
before forcing a fullsweep even if there is still room on
the old heap. Setting the number to zero effectively
disables the general collection algorithm, meaning that
all live data is copied at every garbage collection.
Here are a few cases when it could be useful to change
fullsweep_after
. Firstly, if binaries that are no
longer used should be thrown away as soon as possible.
(Set
to zero.) Secondly, a process that
mostly have short-lived data will be fullsweeped seldom
or never, meaning that the old heap will contain mostly
garbage. To ensure a fullsweep once in a while, set
to a suitable value such as 10 or 20.
Thirdly, in embedded systems with limited amount of RAM
and no virtual memory, one might want to preserve memory
by setting
to zero. (The value may be set
globally, see
erlang:system_flag/2.)
{min_heap_size, Size }
This option is only useful for performance tuning. In general, you should not use this option unless you know that there is problem with execution times and/or memory consumption, and you should measure to make sure that the option improved matters.
Gives a minimum heap size in words. Setting this value
higher than the system default might speed up some
processes because less garbage collection is done.
Setting too high value, however, might waste memory and
slow down the system due to worse data locality.
Therefore, it is recommended to use this option only for
fine-tuning an application and to measure the execution
time with various
values.
{min_bin_vheap_size, VSize }
This option is only useful for performance tuning. In general, you should not use this option unless you know that there is problem with execution times and/or memory consumption, and you should measure to make sure that the option improved matters.
Gives a minimum binary virtual heap size in words. Setting this value
higher than the system default might speed up some
processes because less garbage collection is done.
Setting too high value, however, might waste memory.
Therefore, it is recommended to use this option only for
fine-tuning an application and to measure the execution
time with various
values.
spawn_opt/5
Returns the pid of a new process started by the application
of
to
on Node
. If
does not exist, a useless pid is returned.
Otherwise works like
spawn_opt/4.
split_binary(Bin, Pos) -> {Bin1, Bin2}
Bin = Bin1 = Bin2 = binary()
Pos = 0..byte_size(Bin)
Returns a tuple containing the binaries which are the result
of splitting Bin
into two parts at position Pos
.
This is not a destructive operation. After the operation,
there will be three binaries altogether.
>B = list_to_binary("0123456789").
<<"0123456789">> >byte_size(B).
10 >{B1, B2} = split_binary(B,3).
{<<"012">>,<<"3456789">>} >byte_size(B1).
3 >byte_size(B2).
7
erlang:start_timer(Time, Dest, Msg) -> TimerRef
Time = integer() >= 0
0 <= Time <= 4294967295
Dest = LocalPid | RegName
LocalPid = pid() (of a process, alive or dead, on the local node)
RegName = atom()
Msg = term()
TimerRef = reference()
Starts a timer which will send the message
{timeout, TimerRef, Msg}
to Dest
after Time
milliseconds.
If Dest
is an atom, it is supposed to be the name of
a registered process. The process referred to by the name is
looked up at the time of delivery. No error is given if
the name does not refer to a process.
If Dest
is a pid, the timer will be automatically
canceled if the process referred to by the pid is not alive,
or when the process exits. This feature was introduced in
erts version 5.4.11. Note that timers will not be
automatically canceled when Dest
is an atom.
See also erlang:send_after/3, erlang:cancel_timer/1, and erlang:read_timer/1.
Failure: badarg
if the arguments does not satisfy
the requirements specified above.
statistics(Type) -> Res
Type, Res -- see below
Returns information about the system as specified by
Type
:
context_switches
Returns {ContextSwitches, 0}
, where
ContextSwitches
is the total number of context
switches since the system started.
exact_reductions
Returns
{Total_Exact_Reductions, Exact_Reductions_Since_Last_Call}
.
NOTE:statistics(exact_reductions)
is
a more expensive operation than
statistics(reductions)
especially on an Erlang machine with SMP support.
garbage_collection
Returns {Number_of_GCs, Words_Reclaimed, 0}
. This
information may not be valid for all implementations.
io
Returns {{input, Input}, {output, Output}}
,
where Input
is the total number of bytes received
through ports, and Output
is the total number of
bytes output to ports.
reductions
Returns
{Total_Reductions, Reductions_Since_Last_Call}
.
NOTE: From erts version 5.5 (OTP release R11B) this value does not include reductions performed in current time slices of currently scheduled processes. If an exact value is wanted, use statistics(exact_reductions).
run_queue
Returns the length of the run queue, that is, the number of processes that are ready to run.
runtime
Returns {Total_Run_Time, Time_Since_Last_Call}
.
Note that the run-time is the sum of the run-time for all
threads in the Erlang run-time system and may therefore be greater
than the wall-clock time.
wall_clock
Returns
{Total_Wallclock_Time, Wallclock_Time_Since_Last_Call}
.
wall_clock
can be used in the same manner as
runtime
, except that real time is measured as
opposed to runtime or CPU time.
All times are in milliseconds.
>statistics(runtime).
{1690,1620} >statistics(reductions).
{2046,11} >statistics(garbage_collection).
{85,23961,0}
erlang:suspend_process(Suspendee, OptList) -> boolean()
Suspendee = pid()
OptList = [Opt]
Opt = atom()
Increases the suspend count on the process identified by
Suspendee
and puts it in the suspended state if it isn't
already in the suspended state. A suspended process will not be
scheduled for execution until the process has been resumed.
A process can be suspended by multiple processes and can
be suspended multiple times by a single process. A suspended
process will not leave the suspended state until its suspend
count reach 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 will automatically be
decreased when the process terminates.
Currently the following options (Opt
s) are available:
asynchronous
Suspendee
. Suspendee
will eventually suspend
unless it is resumed before it was able to suspend. The caller
of erlang:suspend_process/2
will return immediately,
regardless of whether the Suspendee
has suspended yet
or not. Note that the point in time when the Suspendee
will actually suspend cannot be deduced from other events
in the system. The only guarantee given is that the
Suspendee
will eventually suspend (unless it
is resumed). If the asynchronous
option has not
been passed, the caller of erlang:suspend_process/2
will
be blocked until the Suspendee
has actually suspended.
unless_suspending
Suspendee
will be suspended
unless the calling process already is suspending the
Suspendee
. If unless_suspending
is combined
with the asynchronous
option, a suspend request will be
sent unless the calling process already is suspending the
Suspendee
or if a suspend request already has been sent
and is in transit. If the calling process already is suspending
the Suspendee
, or if combined with the asynchronous
option and a send request already is in transit,
false
is returned and the suspend count on Suspendee
will remain unchanged.
If the suspend count on the process identified by
Suspendee
was increased, true
is returned; otherwise,
false
is returned.
Warning!
This BIF is intended for debugging only.
Failures:
badarg
Suspendee
isn't a process identifier.
badarg
Suspendee
is same the process as
the process calling erlang:suspend_process/2
.
badarg
Suspendee
is not alive.
badarg
Suspendee
resides on another node.
badarg
OptList
isn't a proper list of valid Opt
s.
system_limit
Suspendee
has been suspended more
times by the calling process than can be represented by the
currently used internal data structures. The current system limit
is larger than 2 000 000 000 suspends, and it will never be less
than that.
suspend_process/1
Suspends the process identified by
. The
same as calling
erlang:suspend_process(
Warning!
This BIF is intended for debugging only.
erlang:system_flag(Flag, Value) -> OldValue
Flag, Value, OldValue -- see below
Warning!
The
cpu_topology,
and
scheduler_bind_type
Flag
s are deprecated and have been scheduled for
removal in erts-5.10/OTP-R16.
Sets various system properties of the Erlang node. Returns the old value of the flag.
erlang:system_flag(backtrace_depth, Depth)
Sets the maximum depth of call stack back-traces in the
exit reason element of 'EXIT'
tuples.
erlang:system_flag(cpu_topology, CpuTopology)
NOTE: This argument is deprecated and
scheduled for removal in erts-5.10/OTP-R16. Instead of using
this argument you are advised to use the erl
command
line argument +sct.
When this argument has been removed a final CPU topology to use
will be determined at emulator boot time.
Sets the user defined CpuTopology
. The user defined
CPU topology will override any automatically detected
CPU topology. By passing undefined
as CpuTopology
the system will revert back to the CPU topology automatically
detected. The returned value equals the value returned
from erlang:system_info(cpu_topology)
before the
change was made.
The CPU topology is used when binding schedulers to logical processors. If schedulers are already bound when the CPU topology is changed, the schedulers will be sent a request to rebind according to the new CPU topology.
The user defined CPU topology can also be set by passing
the +sct command
line argument to erl
.
For information on the CpuTopology
type
and more, see the documentation of
erlang:system_info(cpu_topology),
and the erl
+sct
and +sbt
command line flags.
erlang:system_flag(fullsweep_after, Number)
Number
is a non-negative integer which indicates
how many times generational garbage collections can be
done without forcing a fullsweep collection. The value
applies to new processes; processes already running are
not affected.
In low-memory systems (especially without virtual memory), setting the value to 0 can help to conserve memory.
An alternative way to set this value is through the
(operating system) environment variable
ERL_FULLSWEEP_AFTER
.
erlang:system_flag(min_heap_size, MinHeapSize)
Sets the default minimum heap size for processes. The
size is given in words. The new min_heap_size
only
effects processes spawned after the change of
min_heap_size
has been made.
The min_heap_size
can be set for individual
processes by use of
spawn_opt/N or
process_flag/2.
erlang:system_flag(min_bin_vheap_size, MinBinVHeapSize)
Sets the default minimum binary virtual heap size for processes. The
size is given in words. The new min_bin_vhheap_size
only
effects processes spawned after the change of
min_bin_vhheap_size
has been made.
The min_bin_vheap_size
can be set for individual
processes by use of
spawn_opt/N or
process_flag/2.
erlang:system_flag(multi_scheduling, BlockState)
BlockState = block | unblock
If multi-scheduling is enabled, more than one scheduler thread is used by the emulator. Multi-scheduling can be blocked. When multi-scheduling has been blocked, only one scheduler thread will schedule Erlang processes.
If BlockState =:= block
, multi-scheduling will
be blocked. If BlockState =:= unblock
and no-one
else is blocking multi-scheduling and this process has
only blocked one time, multi-scheduling will be unblocked.
One process can block multi-scheduling multiple times.
If a process has blocked multiple times, it has to
unblock exactly as many times as it has blocked before it
has released its multi-scheduling block. If a process that
has blocked multi-scheduling exits, it will release its
blocking of multi-scheduling.
The return values are disabled
, blocked
,
or enabled
. The returned value describes the
state just after the call to
erlang:system_flag(multi_scheduling, BlockState)
has been made. The return values are described in the
documentation of erlang:system_info(multi_scheduling).
NOTE: Blocking of multi-scheduling should normally not be needed. If you feel that you need to block multi-scheduling, think through the problem at least a couple of times again. Blocking multi-scheduling should only be used as a last resort since it will most likely be a very inefficient way to solve the problem.
See also erlang:system_info(multi_scheduling), erlang:system_info(multi_scheduling_blockers), and erlang:system_info(schedulers).
erlang:system_flag(scheduler_bind_type, How)
NOTE: This argument is deprecated and
scheduled for removal in erts-5.10/OTP-R16. Instead of using
this argument you are advised to use the erl
command
line argument +sbt.
When this argument has been removed a final scheduler bind type
to use will be determined at emulator boot time.
Controls if and how schedulers are bound to logical processors.
When erlang:system_flag(scheduler_bind_type, How)
is
called, an asynchronous signal is sent to all schedulers
online which causes them to try to bind or unbind as requested.
NOTE: If a scheduler fails to bind, this
will often be silently ignored. This since it isn't always
possible to verify valid logical processor identifiers. If
an error is reported, it will be reported to the
error_logger
. If you want to verify that the
schedulers actually have bound as requested, call
erlang:system_info(scheduler_bindings).
Schedulers can currently only be bound on newer Linux, Solaris, FreeBSD, and Windows systems, but more systems will be supported in the future.
In order for the runtime system to be able to bind schedulers,
the CPU topology needs to be known. If the runtime system fails
to automatically detect the CPU topology, it can be defined.
For more information on how to define the CPU topology, see
the erl
+sct command
line flag.
The runtime system will by default not bind schedulers to logical processors.
NOTE: If the Erlang runtime system is the only operating system process that binds threads to logical processors, this improves the performance of the runtime system. However, if other operating system processes (as for example another Erlang runtime system) also bind threads to logical processors, there might be a performance penalty instead. In some cases this performance penalty might be severe. If this is the case, you are advised to not bind the schedulers.
Schedulers can be bound in different ways. The How
argument determines how schedulers are bound. How
can
currently be one of:
unbound
Same as the erl
command line argument
+sbt u.
no_spread
Same as the erl
command line argument
+sbt ns.
thread_spread
Same as the erl
command line argument
+sbt ts.
processor_spread
Same as the erl
command line argument
+sbt ps.
spread
Same as the erl
command line argument
+sbt s.
no_node_thread_spread
Same as the erl
command line argument
+sbt nnts.
no_node_processor_spread
Same as the erl
command line argument
+sbt nnps.
thread_no_node_processor_spread
Same as the erl
command line argument
+sbt tnnps.
default_bind
Same as the erl
command line argument
+sbt db.
The value returned equals How
before the
scheduler_bind_type
flag was changed.
Failure:
notsup
If binding of schedulers is not supported.
badarg
If How
isn't one of the documented alternatives.
badarg
If no CPU topology information is available.
The scheduler bind type can also be set by passing
the +sbt command
line argument to erl
.
For more information, see
erlang:system_info(scheduler_bind_type),
erlang:system_info(scheduler_bindings),
the erl
+sbt
and +sct command line
flags.
erlang:system_flag(schedulers_online, SchedulersOnline)
Sets the amount of schedulers online. Valid range is 1 <= SchedulerId <= erlang:system_info(schedulers).
For more information see, erlang:system_info(schedulers), and erlang:system_info(schedulers_online).
erlang:system_flag(trace_control_word, TCW)
Sets the value of the node's trace control word to
TCW
. TCW
should be an unsigned integer. For
more information see documentation of the
set_tcw
function in the match specification documentation in the
ERTS User's Guide.
Note!
The schedulers
option has been removed as
of erts version 5.5.3. The number of scheduler
threads is determined at emulator boot time, and
cannot be changed after that.
erlang:system_info(Type) -> Res
Type, Res -- see below
Returns various information about the current system
(emulator) as specified by Type
:
allocated_areas
Returns a list of tuples with information about miscellaneous allocated memory areas.
Each tuple contains an atom describing type of memory as first element and amount of allocated memory in bytes as second element. In those cases when there is information present about allocated and used memory, a third element is present. This third element contains the amount of used memory in bytes.
erlang:system_info(allocated_areas)
is intended
for debugging, and the content is highly implementation
dependent. The content of the results will therefore
change when needed without prior notice.
Note: The sum of these values is not the total amount of memory allocated by the emulator. Some values are part of other values, and some memory areas are not part of the result. If you are interested in the total amount of memory allocated by the emulator see erlang:memory/0,1.
allocator
Returns {Allocator, Version, Features, Settings}.
Types:
Allocator = undefined | glibc
Version = [integer()]
Features = [atom()]
Settings = [{Subsystem, [{Parameter, Value}]}]
Subsystem = atom()
Parameter = atom()
Value = term()
Explanation:
-
Allocator
corresponds to themalloc()
implementation used. IfAllocator
equalsundefined
, themalloc()
implementation used could not be identified. Currentlyglibc
can be identified. -
Version
is a list of integers (but not a string) representing the version of themalloc()
implementation used. -
Features
is a list of atoms representing allocation features used. -
Settings
is a list of subsystems, their configurable parameters, and used values. Settings may differ between different combinations of platforms, allocators, and allocation features. Memory sizes are given in bytes.
See also "System Flags Effecting erts_alloc" in erts_alloc(3).
alloc_util_allocators
Returns a list of the names of all allocators
using the ERTS internal alloc_util
framework
as atoms. For more information see the
"the
alloc_util framework" section in the
erts_alloc(3) documentation.
{allocator, Alloc}
Returns information about the specified allocator.
As of erts version 5.6.1 the return value is a list
of {instance, InstanceNo, InstanceInfo}
tuples
where InstanceInfo
contains information about
a specific instance of the allocator.
If Alloc
is not a recognized allocator,
undefined
is returned. If Alloc
is disabled,
false
is returned.
Note: The information returned is highly implementation dependent and may be changed, or removed at any time without prior notice. It was initially intended as a tool when developing new allocators, but since it might be of interest for others it has been briefly documented.
The recognized allocators are listed in
erts_alloc(3).
After reading the erts_alloc(3)
documentation,
the returned information
should more or less speak for itself. But it can be worth
explaining some things. Call counts are presented by two
values. The first value is giga calls, and the second
value is calls. mbcs
, and sbcs
are
abbreviations for, respectively, multi-block carriers, and
single-block carriers. Sizes are presented in bytes. When
it is not a size that is presented, it is the amount of
something. Sizes and amounts are often presented by three
values, the first is current value, the second is maximum
value since the last call to
erlang:system_info({allocator, Alloc})
, and
the third is maximum value since the emulator was started.
If only one value is present, it is the current value.
fix_alloc
memory block types are presented by two
values. The first value is memory pool size and
the second value used memory size.
{allocator_sizes, Alloc}
Returns various size information for the specified allocator. The information returned is a subset of the information returned by erlang:system_info({allocator, Alloc}).
build_type
Returns an atom describing the build type of the runtime
system. This is normally the atom opt
for optimized.
Other possible return values are debug
, purify
,
quantify
, purecov
, gcov
, valgrind
,
gprof
, and lcnt
. Possible return values
may be added and/or removed at any time without prior notice.
c_compiler_used
Returns a two-tuple describing the C compiler used when
compiling the runtime system. The first element is an
atom describing the name of the compiler, or undefined
if unknown. The second element is a term describing the
version of the compiler, or undefined
if unknown.
check_io
Returns a list containing miscellaneous information regarding the emulators internal I/O checking. Note, the content of the returned list may vary between platforms and over time. The only thing guaranteed is that a list is returned.
compat_rel
Returns the compatibility mode of the local node as
an integer. The integer returned represents the
Erlang/OTP release which the current emulator has been
set to be backward compatible with. The compatibility
mode can be configured at startup by using the command
line flag +R
, see
erl(1).
cpu_topology
Returns the CpuTopology
which currently is used by the
emulator. The CPU topology is used when binding schedulers
to logical processors. The CPU topology used is the
user
defined CPU topology if such exists; otherwise, the
automatically
detected CPU topology if such exists. If no CPU topology
exists, undefined
is returned.
Types:
CpuTopology = LevelEntryList | undefined
LevelEntryList = [LevelEntry]
(allLevelEntry
s of aLevelEntryList
must contain the sameLevelTag
, except on the top level where bothnode
andprocessor
LevelTag
s may co-exist)LevelEntry = {LevelTag, SubLevel} | {LevelTag, InfoList, SubLevel}
({LevelTag, SubLevel} == {LevelTag, [], SubLevel}
)LevelTag = node|processor|core|thread
(moreLevelTag
s may be introduced in the future)SubLevel = [LevelEntry] | LogicalCpuId
LogicalCpuId = {logical, integer()}
InfoList = []
(theInfoList
may be extended in the future)
node
refers to NUMA (non-uniform memory access)
nodes, and thread
refers to hardware threads
(e.g. Intels hyper-threads).
A level in the CpuTopology
term can be omitted if
only one entry exists and the InfoList
is empty.
thread
can only be a sub level to core
.
core
can be a sub level to either processor
or node
. processor
can either be on the
top level or a sub level to node
. node
can either be on the top level or a sub level 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
and only one NUMA node. Cache hierarchy is not part of
the CpuTopology
type yet, but will be in the
future. Other things may also make it into the CPU
topology in the future. In other words, expect the
CpuTopology
type to change.
{cpu_topology, defined}
Returns the user defined CpuTopology
. For more
information see the documentation of
the erl
+sct command
line flag, and the documentation of the
cpu_topology
argument.
{cpu_topology, detected}
Returns the automatically detected CpuTopology
. The
emulator currently only detects the CPU topology on some newer
Linux, Solaris, FreeBSD, and Windows systems. On Windows system with
more than 32 logical processors the CPU topology is not detected.
For more information see the documentation of the cpu_topology argument.
{cpu_topology, used}
Returns the CpuTopology
which is used by the
emulator. For more information see the
documentation of the
cpu_topology
argument.
creation
Returns the creation of the local node as an integer. The creation is changed when a node is restarted. The creation of a node is stored in process identifiers, port identifiers, and references. This makes it (to some extent) possible to distinguish between identifiers from different incarnations of a node. Currently valid creations are integers in the range 1..3, but this may (probably will) change in the future. If the node is not alive, 0 is returned.
debug_compiled
Returns true
if the emulator has been debug
compiled; otherwise, false
.
dist
Returns a binary containing a string of distribution information formatted as in Erlang crash dumps. For more information see the "How to interpret the Erlang crash dumps" chapter in the ERTS User's Guide.
dist_ctrl
Returns a list of tuples
{Node, ControllingEntity}
, one entry for each
connected remote node. The Node
is the name of the
node and the ControllingEntity
is the port or pid
responsible for the communication to that node. More
specifically, the ControllingEntity
for nodes
connected via TCP/IP (the normal case) is the socket
actually used in communication with the specific node.
driver_version
Returns a string containing the erlang driver version used by the runtime system. It will be on the form "<major ver>.<minor ver>".
elib_malloc
This option will be removed in a future release.
The return value will always be false
since
the elib_malloc allocator has been removed.
dist_buf_busy_limit
Returns the value of the distribution buffer busy limit
in bytes. This limit can be set on startup by passing the
+zdbbl command line
flag to erl
.
fullsweep_after
Returns {fullsweep_after, integer()}
which is the
fullsweep_after
garbage collection setting used
by default. For more information see
garbage_collection
described below.
garbage_collection
Returns a list describing the default garbage collection
settings. A process spawned on the local node by a
spawn
or spawn_link
will use these
garbage collection settings. The default settings can be
changed by use of
system_flag/2.
spawn_opt/4
can spawn a process that does not use the default
settings.
global_heaps_size
Returns the current size of the shared (global) heap.
heap_sizes
Returns a list of integers representing valid heap sizes in words. All Erlang heaps are sized from sizes in this list.
heap_type
Returns the heap type used by the current emulator. Currently the following heap types exist:
private
Each process has a heap reserved for its use and no references between heaps of different processes are allowed. Messages passed between processes are copied between heaps.
shared
One heap for use by all processes. Messages passed between processes are passed by reference.
hybrid
A hybrid of the private
and shared
heap
types. A shared heap as well as private heaps are
used.
info
Returns a binary containing a string of miscellaneous system information formatted as in Erlang crash dumps. For more information see the "How to interpret the Erlang crash dumps" chapter in the ERTS User's Guide.
kernel_poll
Returns true
if the emulator uses some kind of
kernel-poll implementation; otherwise, false
.
loaded
Returns a binary containing a string of loaded module information formatted as in Erlang crash dumps. For more information see the "How to interpret the Erlang crash dumps" chapter in the ERTS User's Guide.
logical_processors
Returns the detected number of logical processors configured
on the system. The return value is either an integer, or
the atom unknown
if the emulator wasn't able to
detect logical processors configured.
logical_processors_available
Returns the detected number of logical processors available to
the Erlang runtime system. The return value is either an
integer, or the atom unknown
if the emulator wasn't
able to detect logical processors available. The number
of logical processors available is less than or equal to
the number of logical
processors online.
logical_processors_online
Returns the detected number of logical processors online on
the system. The return value is either an integer,
or the atom unknown
if the emulator wasn't able to
detect logical processors online. The number of logical
processors online is less than or equal to the number of
logical processors
configured.
machine
Returns a string containing the Erlang machine name.
min_heap_size
Returns {min_heap_size, MinHeapSize}
where MinHeapSize
is the current system wide
minimum heap size for spawned processes.
min_bin_vheap_size
Returns {min_bin_vheap_size, MinBinVHeapSize}
where MinBinVHeapSize
is the current system wide
minimum binary virtual heap size for spawned processes.
modified_timing_level
Returns the modified timing level (an integer) if
modified timing has been enabled; otherwise,
undefined
. See the +T
command line flag
in the documentation of the
erl(1)
command for more information on modified timing.
multi_scheduling
Returns disabled
, blocked
, or enabled
.
A description of the return values:
disabled
The emulator has only one scheduler thread. The emulator does not have SMP support, or have been started with only one scheduler thread.
blocked
The emulator has more than one scheduler thread, but all scheduler threads but one have been blocked, i.e., only one scheduler thread will schedule Erlang processes and execute Erlang code.
enabled
The emulator has more than one scheduler thread, and no scheduler threads have been blocked, i.e., all available scheduler threads will schedule Erlang processes and execute Erlang code.
See also erlang:system_flag(multi_scheduling, BlockState), erlang:system_info(multi_scheduling_blockers), and erlang:system_info(schedulers).
multi_scheduling_blockers
Returns a list of PID
s when multi-scheduling
is blocked; otherwise, the empty list. The PID
s
in the list is PID
s of the processes currently
blocking multi-scheduling. A PID
will only be
present once in the list, even if the corresponding
process has blocked multiple times.
See also erlang:system_flag(multi_scheduling, BlockState), erlang:system_info(multi_scheduling), and erlang:system_info(schedulers).
otp_release
Returns a string containing the OTP release number.
process_count
Returns the number of processes currently existing at
the local node as an integer. The same value as
length(processes())
returns.
process_limit
Returns the maximum number of concurrently existing
processes at the local node as an integer. This limit
can be configured at startup by using the command line
flag +P
, see
erl(1).
procs
Returns a binary containing a string of process and port information formatted as in Erlang crash dumps. For more information see the "How to interpret the Erlang crash dumps" chapter in the ERTS User's Guide.
scheduler_bind_type
Returns information on how user has requested schedulers to be bound or not bound.
NOTE: Even though user has requested schedulers to be bound, they might have silently failed to bind. In order to inspect actual scheduler bindings call erlang:system_info(scheduler_bindings).
For more information, see
the erl
+sbt
command line argument, and
erlang:system_info(scheduler_bindings).
scheduler_bindings
Returns information on currently used scheduler bindings.
A tuple of a size equal to
erlang:system_info(schedulers) is returned. The elements of the tuple are integers
or the atom unbound
. Logical processor identifiers
are represented as integers. The N
th
element of the tuple equals the current binding for
the scheduler with the scheduler identifier equal to
N
. E.g., if the schedulers have been bound,
element(erlang:system_info(scheduler_id),
erlang:system_info(scheduler_bindings))
will return
the identifier of the logical processor that the calling
process is executing on.
Note that only schedulers online can be bound to logical processors.
For more information, see
the erl
+sbt
command line argument,
erlang:system_info(schedulers_online).
scheduler_id
Returns the scheduler id (SchedulerId
) of the
scheduler thread that the calling process is executing
on. SchedulerId
is a positive integer; where
1 <= SchedulerId <= erlang:system_info(schedulers)
. See also
erlang:system_info(schedulers).
schedulers
Returns the number of scheduler threads used by the emulator. Scheduler threads online schedules Erlang processes and Erlang ports, and execute Erlang code and Erlang linked in driver code.
The number of scheduler threads is determined at emulator boot time and cannot be changed after that. The amount of schedulers online can however be changed at any time.
See also erlang:system_flag(schedulers_online, SchedulersOnline), erlang:system_info(schedulers_online), erlang:system_info(scheduler_id), erlang:system_flag(multi_scheduling, BlockState), erlang:system_info(multi_scheduling), and and erlang:system_info(multi_scheduling_blockers).
schedulers_online
Returns the amount of schedulers online. The scheduler
identifiers of schedulers online satisfy the following
relationship:
1 <= SchedulerId <= erlang:system_info(schedulers_online)
.
For more information, see erlang:system_info(schedulers), and erlang:system_flag(schedulers_online, SchedulersOnline).
smp_support
Returns true
if the emulator has been compiled
with smp support; otherwise, false
.
system_version
Returns a string containing version number and some important properties such as the number of schedulers.
system_architecture
Returns a string containing the processor and OS architecture the emulator is built for.
threads
Returns true
if the emulator has been compiled
with thread support; otherwise, false
is
returned.
thread_pool_size
Returns the number of async threads in the async thread pool used for asynchronous driver calls (driver_async()) as an integer.
trace_control_word
Returns the value of the node's trace control word.
For more information see documentation of the function
get_tcw
in "Match Specifications in Erlang",
ERTS User's Guide.
update_cpu_info
The runtime system rereads the CPU information available and
updates its internally stored information about the
detected CPU
topology and the amount of logical processors
configured,
online, and
available.
If the CPU information has changed since the last time it was read,
the atom changed
is returned; otherwise, the atom
unchanged
is returned. If the CPU information has changed
you probably want to
adjust the amount
of schedulers online. You typically want to have as
many schedulers online as
logical processors
available.
version
Returns a string containing the version number of the emulator.
wordsize
Same as {wordsize, internal}.
{wordsize, internal}
Returns the size of Erlang term words in bytes as an integer, i.e. on a 32-bit architecture 4 is returned, and on a pure 64-bit architecture 8 is returned. On a halfword 64-bit emulator, 4 is returned, as the Erlang terms are stored using a virtual wordsize of half the system's wordsize.
{wordsize, external}
Returns the true wordsize of the emulator, i.e. the size of a pointer, in bytes as an integer. On a pure 32-bit architecture 4 is returned, on both a halfword and pure 64-bit architecture, 8 is returned.
Note!
The scheduler
argument has changed name to
scheduler_id
. This in order to avoid mixup with
the schedulers
argument. The scheduler
argument was introduced in ERTS version 5.5 and renamed
in ERTS version 5.5.1.
erlang:system_monitor() -> MonSettings
MonSettings -> {MonitorPid, Options} | undefined
MonitorPid = pid()
Options = [Option]
Option = {long_gc, Time} | {large_heap, Size} | busy_port | busy_dist_port
Time = Size = integer()
Returns the current system monitoring settings set by
erlang:system_monitor/2
as {MonitorPid, Options}
, or undefined
if there
are no settings. The order of the options may be different
from the one that was set.
erlang:system_monitor(undefined | {MonitorPid, Options}) -> MonSettings
MonitorPid, Options, MonSettings -- see below
When called with the 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.
erlang:system_monitor(MonitorPid, [Option]) -> MonSettings
MonitorPid = pid()
Option = {long_gc, Time} | {large_heap, Size} | busy_port | busy_dist_port
Time = Size = integer()
MonSettings = {OldMonitorPid, [Option]}
OldMonitorPid = pid()
Sets system performance monitoring options. MonitorPid
is a local pid that will receive system monitor messages, and
the second argument is a list of monitoring options:
{long_gc, Time}
If a garbage collection in the system takes at least
Time
wallclock milliseconds, a message
{monitor, GcPid, long_gc, Info}
is sent to
MonitorPid
. GcPid
is the pid that was
garbage collected and Info
is a list of two-element
tuples describing the result of the garbage collection.
One of the tuples is {timeout, GcTime}
where
GcTime
is the actual time for the garbage
collection in milliseconds. The other tuples are
tagged with heap_size
, heap_block_size
,
stack_size
, mbuf_size
, old_heap_size
,
and old_heap_block_size
. These tuples are
explained in the documentation of the
gc_start
trace message (see
erlang:trace/3).
New tuples may be added, and the order of the tuples in
the Info
list may be changed at any time without prior
notice.
{large_heap, Size}
If a garbage collection in the system results in
the allocated size of a heap being at least Size
words, a message {monitor, GcPid, large_heap, Info}
is sent to MonitorPid
. GcPid
and Info
are the same as for long_gc
above, except that
the tuple tagged with timeout
is not present.
Note: As of erts version 5.6 the monitor message
is sent if the sum of the sizes of all memory blocks allocated
for all heap generations is equal to or larger than Size
.
Previously the monitor message was sent if the memory block
allocated for the youngest generation was equal to or larger
than Size
.
busy_port
If a process in the system gets suspended because it
sends to a busy port, a message
{monitor, SusPid, busy_port, Port}
is sent to
MonitorPid
. SusPid
is the pid that got
suspended when sending to Port
.
busy_dist_port
If a process in the system gets suspended because it
sends to a process on a remote node whose inter-node
communication was handled by a busy port, a message
{monitor, SusPid, busy_dist_port, Port}
is sent to
MonitorPid
. SusPid
is the pid that got
suspended when sending through the inter-node
communication port Port
.
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 will enlarge the process's message queue and probably make the problem worse.
Keep the monitoring process neat and do not set the system monitor limits too tight.
Failure: badarg
if MonitorPid
does not exist.
erlang:system_profile() -> ProfilerSettings
ProfilerSettings -> {ProfilerPid, Options} | undefined
ProfilerPid = pid() | port()
Options = [Option]
Option = runnable_procs | runnable_ports | scheduler | exclusive
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 may be different
from the one that was set.
erlang:system_profile(ProfilerPid, Options) -> ProfilerSettings
ProfilerSettings -> {ProfilerPid, Options} | undefined
ProfilerPid = pid() | port()
Options = [Option]
Option = runnable_procs | runnable_ports | scheduler | exclusive
Sets system profiler options. ProfilerPid
is a local pid or port that will receive profiling messages. The
receiver is excluded from all profiling.
The second argument is a list of profiling options:
runnable_procs
If a process is put into or removed from the run queue a message,
{profile, Pid, State, Mfa, Ts}
, is sent to
ProfilerPid
. Running processes that is reinserted into the
run queue after having been preemptively scheduled out will not trigger this
message.
runnable_ports
If a port is put into or removed from the run queue a message,
{profile, Port, State, 0, Ts}
, is sent to
ProfilerPid
.
scheduler
If a scheduler is put to sleep or awoken a message,
{profile, scheduler, Id, State, NoScheds, Ts}
, is sent
to ProfilerPid
.
exclusive
If a synchronous call to a port from a process is done, the
calling process is considered not runnable during the call
runtime to the port. The calling process is notified as
inactive
and subsequently active
when the port
callback returns.
Note!
erlang:system_profile
is considered experimental and
its behaviour may change in the future.
term_to_binary(Term) -> ext_binary()
Term = term()
Returns a binary data object which is the result of encoding
Term
according to the Erlang external term format.
This can be used for a variety of purposes, for example writing a term to a file in an efficient way, or sending an Erlang term to some type of communications channel not supported by distributed Erlang.
See also binary_to_term/1.
term_to_binary(Term, [Option]) -> ext_binary()
Term = term()
Option = compressed | {compressed,Level} | {minor_version,Version}
Returns a binary data object which is the result of encoding
Term
according to the Erlang external term format.
If the option compressed
is provided, the external
term format will be compressed. The compressed format is
automatically recognized by binary_to_term/1
in R7B and later.
It is also possible to specify a compression level by giving
the option {compressed,Level}
, where Level
is an
integer from 0 through 9. 0
means that no compression
will be done (it is the same as not giving any compressed
option);
1
will take the least time but may not compress as well as
the higher levels; 9
will take the most time and may produce
a smaller result. Note the "mays" in the preceding sentence; depending
on the input term, level 9 compression may or may not produce a smaller
result than level 1 compression.
Currently, compressed
gives the same result as
{compressed,6}
.
The option {minor_version,Version}
can be use to control
some details of the encoding. This option was
introduced in R11B-4. Currently, the allowed values for Version
are 0
and 1
.
{minor_version,1}
forces any floats in the term to be encoded
in a more space-efficient and exact way (namely in the 64-bit IEEE format,
rather than converted to a textual representation). binary_to_term/1
in R11B-4 and later is able decode the new representation.
{minor_version,0}
is currently the default, meaning that floats
will be encoded using a textual representation; this option is useful if
you want to ensure that releases prior to R11B-4 can decode resulting
binary.
See also binary_to_term/1.
throw(Any)
Any = term()
A non-local return from a function. If evaluated within a
catch
, catch
will return the value Any
.
> catch throw({hello, there}).
{hello,there}
Failure: nocatch
if not evaluated within a catch.
time() -> {Hour, Minute, Second}
Hour = Minute = Second = integer() >= 0
Returns the current time as {Hour, Minute, Second}
.
The time zone and daylight saving time correction depend on the underlying OS.
> time().
{9,42,44}
tl(List1) -> List2
List1 = List2 = [term()]
Returns the tail of List1
, that is, the list minus
the first element.
> tl([geesties, guilies, beasties]).
[guilies, beasties]
Allowed in guard tests.
Failure: badarg
if List
is the empty list [].
erlang:trace(PidSpec, How, FlagList) -> integer() >= 0
PidSpec = pid() | existing | new | all
How = boolean()
FlagList = [Flag]
Flag -- see below
Turns on (if How == true
) or off (if
How == false
) the trace flags in FlagList
for
the process or processes represented by PidSpec
.
PidSpec
is either a pid for a local process, or one of
the following atoms:
existing
All processes currently existing.
new
All processes that will be created in the future.
all
All currently existing processes and all processes that will be created in the future.
FlagList
can contain any number of the following
flags (the "message tags" refers to the list of messages
following below):
all
Set all trace flags except {tracer, Tracer}
and
cpu_timestamp
that are in their nature different
than the others.
send
Trace sending of messages.
Message tags: send
,
send_to_non_existing_process
.
'receive'
Trace receiving of messages.
Message tags: 'receive'
.
procs
Trace process related events.
Message tags: spawn
, exit
,
register
, unregister
, link
,
unlink
, getting_linked
,
getting_unlinked
.
call
Trace certain function calls. Specify which function calls to trace by calling erlang:trace_pattern/3.
Message tags: call
, return_from
.
silent
Used in conjunction with the call
trace flag.
The call
, return_from
and return_to
trace messages are inhibited if this flag is set,
but if there are match specs they are executed as normal.
Silent mode is inhibited by executing
erlang:trace(_, false, [silent|_])
,
or by a match spec executing the {silent, false}
function.
The silent
trace flag facilitates setting up
a trace on many or even all processes in the system.
Then the interesting trace can be activated and
deactivated using the {silent,Bool}
match spec function, giving a high degree
of control of which functions with which
arguments that triggers the trace.
Message tags: call
, return_from
,
return_to
. Or rather, the absence of.
return_to
Used in conjunction with the call
trace flag.
Trace the actual return from a traced function back to
its caller. Only works for functions traced with
the local
option to
erlang:trace_pattern/3.
The semantics is that a trace message is sent when a
call traced function actually returns, that is, when a
chain of tail recursive calls is ended. There will be
only one trace message sent per chain of tail recursive
calls, why the properties of tail recursiveness for
function calls are kept while tracing with this flag.
Using call
and return_to
trace together
makes it possible to know exactly in which function a
process executes at any time.
To get trace messages containing return values from
functions, use the {return_trace}
match_spec
action instead.
Message tags: return_to
.
running
Trace scheduling of processes.
Message tags: in
, and out
.
exiting
Trace scheduling of an exiting processes.
Message tags: in_exiting
, out_exiting
, and
out_exited
.
garbage_collection
Trace garbage collections of processes.
Message tags: gc_start
, gc_end
.
timestamp
Include a time stamp in all trace messages. The time
stamp (Ts) is of the same form as returned by
erlang:now()
.
cpu_timestamp
A global trace flag for the Erlang node that makes all
trace timestamps be in CPU time, not wallclock. It is
only allowed with PidSpec==all
. If the host
machine operating system does not support high resolution
CPU time measurements, trace/3
exits with
badarg
.
arity
Used in conjunction with the call
trace flag.
{M, F, Arity}
will be specified instead of
{M, F, Args}
in call trace messages.
set_on_spawn
Makes any process created by a traced process inherit
its trace flags, including the set_on_spawn
flag.
set_on_first_spawn
Makes the first process created by a traced process
inherit its trace flags, excluding
the set_on_first_spawn
flag.
set_on_link
Makes any process linked by a traced process inherit its
trace flags, including the set_on_link
flag.
set_on_first_link
Makes the first process linked to by a traced process
inherit its trace flags, excluding
the set_on_first_link
flag.
{tracer, Tracer}
Specify where to send the trace messages. Tracer
must be the pid of a local process or the port identifier
of a local port. If this flag is not given, trace
messages will be sent to the process that called
erlang:trace/3
.
The effect of combining set_on_first_link
with
set_on_link
is the same as having
set_on_first_link
alone. Likewise for
set_on_spawn
and set_on_first_spawn
.
If the timestamp
flag is not given, the tracing
process will receive the trace messages described below.
Pid
is the pid of the traced process in which
the traced event has occurred. The third element of the tuple
is the message tag.
If the timestamp
flag is given, the first element of
the tuple will be trace_ts
instead and the timestamp
is added last in the tuple.
{trace, Pid, 'receive', Msg}
When Pid
receives the message Msg
.
{trace, Pid, send, Msg, To}
When Pid
sends the message Msg
to
the process To
.
{trace, Pid, send_to_non_existing_process, Msg, To}
When Pid
sends the message Msg
to
the non-existing process To
.
{trace, Pid, call, {M, F, Args}}
When Pid
calls a traced function. The return
values of calls are never supplied, only the call and its
arguments.
Note that the trace flag arity
can be used to
change the contents of this message, so that Arity
is specified instead of Args
.
{trace, Pid, return_to, {M, F, Arity}}
When Pid
returns to the specified
function. This trace message is sent if both
the call
and the return_to
flags are set,
and the function is set to be traced on local
function calls. The message is only sent when returning
from a chain of tail recursive function calls where at
least one call generated a call
trace message
(that is, the functions match specification matched and
{message, false}
was not an action).
{trace, Pid, return_from, {M, F, Arity}, ReturnValue}
When Pid
returns from the specified
function. This trace message is sent if the call
flag is set, and the function has a match specification
with a return_trace
or exception_trace
action.
{trace, Pid, exception_from, {M, F, Arity}, {Class, Value}}
When Pid
exits from the specified
function due to an exception. This trace message is sent
if the call
flag is set, and the function has
a match specification with an exception_trace
action.
{trace, Pid, spawn, Pid2, {M, F, Args}}
When Pid
spawns a new process Pid2
with
the specified function call as entry point.
Note that Args
is supposed to be the argument
list, but may be any term in the case of an erroneous
spawn.
{trace, Pid, exit, Reason}
When Pid
exits with reason Reason
.
{trace, Pid, link, Pid2}
When Pid
links to a process Pid2
.
{trace, Pid, unlink, Pid2}
When Pid
removes the link from a process
Pid2
.
{trace, Pid, getting_linked, Pid2}
When Pid
gets linked to a process Pid2
.
{trace, Pid, getting_unlinked, Pid2}
When Pid
gets unlinked from a process Pid2
.
{trace, Pid, register, RegName}
When Pid
gets the name RegName
registered.
{trace, Pid, unregister, RegName}
When Pid
gets the name RegName
unregistered.
Note that this is done automatically when a registered
process exits.
{trace, Pid, in, {M, F, Arity} | 0}
When Pid
is scheduled to run. The process will
run in function {M, F, Arity}
. On some rare
occasions the current function cannot be determined, then
the last element Arity
is 0.
{trace, Pid, out, {M, F, Arity} | 0}
When Pid
is scheduled out. The process was
running in function {M, F, Arity}. On some rare occasions
the current function cannot be determined, then the last
element Arity
is 0.
{trace, Pid, gc_start, Info}
Sent when garbage collection is about to be started.
Info
is a list of two-element tuples, where
the first element is a key, and the second is the value.
You should not depend on the tuples have any defined
order. Currently, the following keys are defined:
heap_size
heap_block_size
old_heap_size
old_heap_block_size
stack_size
recent_size
mbuf_size
bin_vheap_size
bin_vheap_block_size
bin_old_vheap_size
bin_vheap_block_size
All sizes are in words.
{trace, Pid, gc_end, Info}
Sent when garbage collection is finished. Info
contains the same kind of list as in the gc_start
message, but the sizes reflect the new sizes after
garbage collection.
If the tracing process dies, the flags will be silently removed.
Only one process can trace a particular process. For this reason, attempts to trace an already traced process will fail.
Returns: A number indicating the number of processes that
matched PidSpec
. If PidSpec
is a pid,
the return value will be 1
. If PidSpec
is
all
or existing
the return value will be
the number of processes running, excluding tracer processes.
If PidSpec
is new
, the return value will be
0
.
Failure: If specified arguments are not supported. For
example cpu_timestamp
is not supported on all
platforms.
erlang:trace_delivered(Tracee) -> Ref
Tracee = pid() | all
Ref = reference()
The delivery of trace messages is dislocated on the time-line
compared to other events in the system. If you know that the
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
you can use erlang:trace_delivered(Tracee)
. A
{trace_delivered, Tracee, Ref}
message is sent to
the caller of erlang:trace_delivered(Tracee)
when it
is guaranteed that all trace messages have been delivered to
the tracer up to the point that the Tracee
had reached
at the time of the call to
erlang:trace_delivered(Tracee)
.
Note that the trace_delivered
message does not
imply that trace messages have been delivered; instead, it implies
that all trace messages that should be delivered have
been delivered. It is not an error if Tracee
isn't, and
hasn't been traced by someone, but if this is the case,
no trace messages will have been delivered when the
trace_delivered
message arrives.
Note that Tracee
has to 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.
An 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. C
can ensure that the trace isn't truncated by calling
erlang:trace_delivered(A)
when A
exits and wait
for the {trace_delivered, A, Ref}
message 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.
erlang:trace_info(PidOrFunc, Item) -> Res
PidOrFunc = pid() | new | {Module, Function, Arity} | on_load
Module = Function = atom()
Arity = arity()
Item, Res -- see below
Returns trace information about a process or function.
To get information about a process, PidOrFunc
should
be a pid or the atom new
. The atom new
means
that the default trace state for processes to be created will
be returned. Item
must have one of the following
values:
flags
Return a list of atoms indicating what kind of traces is
enabled for the process. The list will be empty if no
traces are enabled, and one or more of the followings
atoms if traces are enabled: send
,
'receive'
, set_on_spawn
, call
,
return_to
, procs
, set_on_first_spawn
,
set_on_link
, running
,
garbage_collection
, timestamp
, and
arity
. The order is arbitrary.
tracer
Return the identifier for process or port tracing this
process. If this process is not being traced, the return
value will be []
.
To get information about a function, PidOrFunc
should
be a three-element tuple: {Module, Function, Arity}
or
the atom on_load
. No wildcards are allowed. Returns
undefined
if the function does not exist or
false
if the function is not traced at all. Item
must have one of the following values:
traced
Return global
if this function is traced on
global function calls, local
if this function is
traced on local function calls (i.e local and global
function calls), and false
if neither local nor
global function calls are traced.
match_spec
Return the match specification for this function, if it
has one. If the function is locally or globally traced but
has no match specification defined, the returned value
is []
.
meta
Return the meta trace tracer process or port for this
function, if it has one. If the function is not meta
traced the returned value is false
, and if
the function is meta traced but has once detected that
the tracer proc is invalid, the returned value is [].
meta_match_spec
Return the meta trace match specification for this
function, if it has one. If the function is meta traced
but has no match specification defined, the returned
value is []
.
call_count
Return the call count value for this function or
true
for the pseudo function on_load
if call
count tracing is active. Return false
otherwise.
See also
erlang:trace_pattern/3.
call_time
Return the call time values for this function or
true
for the pseudo function on_load
if call
time tracing is active. Returns false
otherwise.
The call time values returned, [{Pid, Count, S, Us}]
,
is a list of each process that has executed the function and its specific counters.
See also
erlang:trace_pattern/3.
all
Return a list containing the {Item, Value}
tuples
for all other items, or return false
if no tracing
is active for this function.
The actual return value will be {Item, Value}
, where
Value
is the requested information as described above.
If a pid for a dead process was given, or the name of a
non-existing function, Value
will be undefined
.
If PidOrFunc
is the on_load
, the information
returned refers to the default value for code that will be
loaded.
erlang:trace_pattern(MFA, MatchSpec) -> integer() >= 0
The same as erlang:trace_pattern(MFA, MatchSpec, []), retained for backward compatibility.
erlang:trace_pattern(MFA, MatchSpec, FlagList) -> integer() >= 0
MFA, MatchSpec, FlagList -- see below
This BIF is used to enable or disable call tracing for
exported functions. It must be combined with
erlang:trace/3
to set the call
trace flag for one or more processes.
Conceptually, call tracing works like this: Inside the Erlang virtual machine there is a set of processes to be traced and a set of functions to be traced. Tracing will be enabled on the intersection of the set. That is, if a process included in the traced process set calls a function included in the traced function set, the trace action will be taken. Otherwise, nothing will happen.
Use
erlang:trace/3 to
add or remove one or more processes to the set of traced
processes. Use erlang:trace_pattern/2
to add or remove
exported functions to the set of traced functions.
The erlang:trace_pattern/3
BIF can also add match
specifications to an exported function. A match specification
comprises a pattern that the arguments to the function must
match, a guard expression which must evaluate to true
and an action to be performed. The default action is to send a
trace message. If the pattern does not match or the guard
fails, the action will not be executed.
The MFA
argument should be a tuple like
{Module, Function, Arity}
or the atom on_load
(described below). It can be the module, function, and arity
for an exported function (or a BIF in any module).
The '_'
atom can be used to mean any of that kind.
Wildcards can be used in any of the following ways:
{Module,Function,'_'}
All exported functions of any arity named Function
in module Module
.
{Module,'_','_'}
All exported functions in module Module
.
{'_','_','_'}
All exported functions in all loaded modules.
Other combinations, such as {Module,'_',Arity}
, are
not allowed. Local functions will match wildcards only if
the local
option is in the FlagList
.
If the MFA
argument is the atom on_load
,
the match specification and flag list will be used on all
modules that are newly loaded.
The MatchSpec
argument can take any of the following
forms:
false
Disable tracing for the matching function(s). Any match specification will be removed.
true
Enable tracing for the matching function(s).
MatchSpecList
A list of match specifications. An empty list is
equivalent to true
. See the ERTS User's Guide
for a description of match specifications.
restart
For the FlagList
option call_count
and call_time
:
restart the existing counters. The behaviour is undefined
for other FlagList
options.
pause
For the FlagList
option call_count
and call_time
: pause
the existing counters. The behaviour is undefined for
other FlagList
options.
The FlagList
parameter is a list of options.
The following options are allowed:
global
Turn on or off call tracing for global function calls (that is, calls specifying the module explicitly). Only exported functions will match and only global calls will generate trace messages. This is the default.
local
Turn on or off call tracing for all types of function
calls. Trace messages will be sent whenever any of
the specified functions are called, regardless of how they
are called. If the return_to
flag is set for
the process, a return_to
message will also be sent
when this function returns to its caller.
meta | {meta, Pid}
Turn on or off meta tracing for all types of function
calls. Trace messages will be sent to the tracer process
or port Pid
whenever any of the specified
functions are called, regardless of how they are called.
If no Pid
is specified, self()
is used as a
default tracer process.
Meta tracing traces all processes and does not care
about the process trace flags set by trace/3
,
the trace flags are instead fixed to
[call, timestamp]
.
The match spec function {return_trace}
works with
meta trace and send its trace message to the same tracer
process.
call_count
Starts (MatchSpec == true
) or stops
(MatchSpec == false
) call count tracing for all
types of function calls. For every function a counter is
incremented when the function is called, in any process.
No process trace flags need to be activated.
If call count tracing is started while already running,
the count is restarted from zero. Running counters can be
paused with MatchSpec == pause
. Paused and running
counters can be restarted from zero with
MatchSpec == restart
.
The counter value can be read with erlang:trace_info/2.
call_time
Starts (MatchSpec == true
) or stops
(MatchSpec == false
) call time tracing for all
types of function calls. For every function a counter is
incremented when the function is called. Time spent in the function
is accumulated in two other counters, seconds and micro-seconds.
The counters are stored for each call traced process.
If call time tracing is started while already running,
the count and time is restarted from zero. Running counters can be
paused with MatchSpec == pause
. Paused and running
counters can be restarted from zero with
MatchSpec == restart
.
The counter value can be read with erlang:trace_info/2.
The global
and local
options are mutually
exclusive and global
is the default (if no options are
specified). The call_count
and meta
options
perform a kind of local tracing, and can also not be combined
with global
. A function can be either globally or
locally traced. If global tracing is specified for a
specified set of functions; local, meta, call time and call count
tracing for the matching set of local functions will be
disabled, and vice versa.
When disabling trace, the option must match the type of trace
that is set on the function, so that local tracing must be
disabled with the local
option and global tracing with
the global
option (or no option at all), and so forth.
There is no way to directly change part of a match specification list. If a function has a match specification, you can replace it with a completely new one. If you need to change an existing match specification, use the erlang:trace_info/2 BIF to retrieve the existing match specification.
Returns the number of exported functions that matched
the MFA
argument. This will be zero if none matched at
all.
trunc(Number) -> integer()
Number = number()
Returns an integer by the truncating Number
.
> trunc(5.5).
5
Allowed in guard tests.
tuple_size(Tuple) -> integer() >= 0
Tuple = tuple()
Returns an integer which is the number of elements in Tuple
.
> tuple_size({morni, mulle, bwange}).
3
Allowed in guard tests.
tuple_to_list(Tuple) -> [term()]
Tuple = tuple()
Returns a list which corresponds to Tuple
.
Tuple
may contain any Erlang terms.
> tuple_to_list({share, {'Ericsson_B', 163}}).
[share,{'Ericsson_B',163}]
erlang:universaltime() -> DateTime
DateTime = calendar:datetime()
Returns the current date and time according to Universal
Time Coordinated (UTC), also called GMT, in the form
{{Year, Month, Day}, {Hour, Minute, Second}}
if
supported by the underlying operating system. If not,
erlang:universaltime()
is equivalent to
erlang:localtime()
.
> erlang:universaltime().
{{1996,11,6},{14,18,43}}
erlang:universaltime_to_localtime({Date1, Time1}) -> {Date2, Time2}
Date1 = Date2 = calendar:date()
Time1 = Time2 = calendar:time()
Converts Universal Time Coordinated (UTC) date and time to
local date and time, if this is supported by the underlying
OS. Otherwise, no conversion is done, and
{Date1, Time1}
is returned.
> erlang:universaltime_to_localtime({{1996,11,6},{14,18,43}}).
{{1996,11,7},{15,18,43}}
Failure: badarg
if Date1
or Time1
do
not denote a valid date or time.
unlink(Id) -> true
Id = pid() | port()
Removes the link, if there is one, between the calling
process and the process or port referred to by Id
.
Returns true
and does not fail, even if there is no
link to Id
, or if Id
does not exist.
Once unlink(Id)
has returned it is guaranteed that
the link between the caller and the entity referred to by
Id
has no effect on the caller in the future (unless
the link is setup again). If caller is trapping exits, an
{'EXIT', Id, _}
message due to the link might have
been placed in the callers message queue prior to the call,
though. Note, the {'EXIT', Id, _}
message can be the
result of the link, but can also be the result of Id
calling exit/2
. Therefore, it may be
appropriate to cleanup the message queue when trapping exits
after the call to unlink(Id)
, as follow:
unlink(Id), receive {'EXIT', Id, _} -> true after 0 -> true end
Note!
Prior to OTP release R11B (erts version 5.5) unlink/1
behaved completely asynchronous, i.e., the link was active
until the "unlink signal" reached the linked entity. This
had one undesirable effect, though. You could never know when
you were guaranteed not to be effected by the link.
Current behavior can be viewed as two combined operations: asynchronously send an "unlink signal" to the linked entity and ignore any future results of the link.
unregister(RegName) -> true
RegName = atom()
Removes the registered name RegName
, associated with a
pid or a port identifier.
> unregister(db).
true
Users are advised not to unregister system processes.
Failure: badarg
if RegName
is not a registered
name.
whereis(RegName) -> pid() | port() | undefined
Returns the pid or port identifier with the registered name
RegName
. Returns undefined
if the name is not
registered.
> whereis(db).
<0.43.0>
yield/0
Voluntarily let other processes (if any) get a chance to
execute. Using erlang:yield()
is similar to
receive after 1 -> ok end
, except that yield()
is faster.
Warning!
There is seldom or never any need to use this BIF, especially in the SMP-emulator as other processes will have a chance to run in another scheduler thread anyway. Using this BIF without a thorough grasp of how the scheduler works may cause performance degradation.
- abs/1
- adler32/1
- adler32/2
- adler32_combine/3
- append_element/2
- apply
- apply-1
- atom_to_binary/2
- atom_to_list/1
- binary_part/2
- binary_part/3
- binary_to_atom/2
- binary_to_existing_atom/2
- binary_to_list/1
- binary_to_list/3
- bitstring_to_list/1
- binary_to_term/1
- binary_to_term/2
- bit_size/1
- bump_reductions/1
- byte_size/1
- cancel_timer/1
- check_old_code/1
- check_process_code/2
- crc32/1
- crc32/2
- crc32_combine/3
- date/0
- decode_packet/3
- delete_module/1
- demonitor/1
- demonitor/2
- disconnect_node
- display/1
- element/2
- erase/0
- erase/1
- error/1
- error/2
- exit/1
- exit/2
- external_size/1
- external_size/2
- float/1
- float_to_list/1
- fun_info
- fun_info/2
- fun_to_list/1
- function_exported/3
- garbage_collect/0
- garbage_collect/1
- get/0
- get/1
- get_cookie
- get_keys/1
- get_stacktrace/0
- group_leader/0
- group_leader/2
- halt/0
- halt/1
- hash/2
- hd/1
- hibernate/3
- integer_to_list/1
- integer_to_list
- iolist_to_binary/1
- iolist_size/1
- is_alive/0
- is_atom/1
- is_binary/1
- is_bitstring/1
- is_boolean/1
- is_builtin/3
- is_float/1
- is_function/1
- is_function/2
- is_integer/1
- is_list/1
- is_number/1
- is_pid/1
- is_port/1
- is_process_alive/1
- is_record/2
- is_record/3
- is_reference/1
- is_tuple/1
- length/1
- link/1
- list_to_atom/1
- list_to_binary/1
- list_to_bitstring/1
- list_to_existing_atom/1
- list_to_float/1
- list_to_integer/1
- list_to_integer
- list_to_pid/1
- list_to_tuple/1
- load_module/2
- load_nif/2
- loaded/0
- localtime/0
- localtime_to_universaltime
- localtime_to_universaltime/3
- make_ref/0
- make_tuple/2
- make_tuple/3
- max
- md5/1
- md5_final/1
- md5_init/0
- md5_update/2
- memory/0
- memory/1
- min
- module_loaded/1
- monitor/2
- monitor_node/2
- monitor_node/3
- nif_error/1
- nif_error/2
- node/0
- node/1
- nodes
- nodes/1
- now/0
- open_port/2
- phash/2
- phash2/2
- pid_to_list/1
- port_close/1
- port_command/2
- port_command/3
- port_connect/2
- port_control/3
- port_call/3
- port_info/1
- port_info/2
- port_to_list/1
- ports/0
- pre_loaded/0
- process_display/2
- process_flag/2
- process_flag/3
- process_info/1
- process_info/2
- processes/0
- purge_module/1
- put/2
- raise/3
- read_timer/1
- ref_to_list/1
- register/2
- registered/0
- resume_process/1
- round/1
- self/0
- send/2
- send/3
- send_after/3
- send_nosuspend
- send_nosuspend-1
- set_cookie
- setelement/3
- size/1
- spawn
- spawn-1
- spawn/3
- spawn-2
- spawn_link
- spawn_link-1
- spawn_link/3
- spawn_link-2
- spawn_monitor
- spawn_monitor-1
- spawn_opt
- spawn_opt-1
- spawn_opt-2
- spawn_opt-3
- split_binary/2
- start_timer/3
- statistics/1
- suspend_process/2
- suspend_process
- system_flag/2
- system_info/1
- system_monitor/0
- system_monitor/2
- system_monitor/2-1
- system_profile/0
- system_profile/2
- term_to_binary/1
- term_to_binary/2
- throw/1
- time/0
- tl/1
- trace/3
- trace_delivered/1
- trace_info/2
- trace_pattern/2
- trace_pattern/3
- trunc/1
- tuple_size/1
- tuple_to_list/1
- universaltime/0
- universaltime_to_localtime/2
- unlink/1
- unregister/1
- whereis/1
- yield