By convention, Built In Functions (BIFs) are seen as being in the module
erlang
. Thus, both the calls atom_to_list(Erlang)
and erlang:atom_to_list(Erlang)
are identical.
BIFs may fail for a variety of reasons. All BIFs fail if they
are called with arguments of an incorrect type. For example,
atom_to_list/1
will fail if it is called with an argument
which is not an atom. If this type of failure is not within the
scope of a catch (and the BIF is not called within a guard; see
below), the process making the call will exit, and an
EXIT signal with the associated reason badarg
will be sent
to all linked processes. The other reasons that may make BIFs fail
are described in connection with the description of each
individual BIF.
A few BIFs may be used in guard tests, for example:
tuple_5(Something) when size(Something) == 5 -> is_tuple_size_5; tuple_5(_) -> is_something_else.
Here the BIF size/1
is used in a guard. If size/1
is called with a tuple, it will return the size of the tuple
(i.e., how many elements there are in the tuple). In the above example,
size/1
is used in a guard which tests if its
argument Something
is a tuple and, if it is, whether it is
of size 5. In this case, calling size with an argument other than
a tuple will cause the guard to fail and execution will continue
with the next clause. Suppose tuple_5/1
is written as
follows:
tuple_5(Something) -> case size(Something) of 5 -> is_tuple_size_5; _ -> is_something_else end.
In this case, size/1
is not in a guard. If Something
is not a tuple, size/1
will fail and cause the process to
exit with the associated reason badarg
(see above).
Some of the BIFs in this chapter are optional in Erlang implementations, and not all implementations will include them.
The following descriptions indicate which BIFs can be used in guards and which BIFs are optional.
Returns an integer or float which is the arithmetical
absolute value of the argument Number
(integer or
float).
> abs(-3.33). 3.33000 > abs(-3). 3
This BIF is allowed in guard tests.
Failure: badarg
if the argument is not an integer or
a float.
erlang:append_element(Tuple, Term)
Returns a new tuple which has one element more than Tuple
,
and contains the elements in Tuple followed by Term as the last
element. Semantically equvivalent to
list_to_tuple(tuple_to_list(Tuple ++ [Term])
,
but much faster.
Failure: badarg
if Tuple
is not a tuple.
apply({Module, Function}, ArgumentList)
This is equivalent to apply(Module, Function,
ArgumentList)
.
apply(Module, Function, ArgumentList)
Returns the result of applying Function
in
Module
on ArgumentList
. The applied function
must have been exported from Module
. The arity of the
function is the length of ArgumentList
.
> 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"
Failure: error_handler:undefined_function/3
is called
if Module
has not exported Function/Arity
. The
error handler can be redefined (see the BIF
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
will be generated.
Returns a list of integers (Latin-1 codes), which
corresponds to the text representation of the argument
Atom
.
>atom_to_list('Erlang'). "Erlang"
Failure: badarg
if the argument is not an atom.
erlang:binary_to_float(Binary)
Returns a float corresponding to the big-endian IEEE representation
in Binary
. The size of Binary
must be 4 or 8 bytes.
This is an internal BIF, only to be used by OTP code. |
Failure: badarg
if the argument is not a binary or not
the representation of a number.
Returns a list of integers which correspond to the bytes of
Binary
.
binary_to_list(Binary, Start, Stop)
As binary_to_list/1
, but it only returns the list from
position Start
to position Stop
. Start
and
Stop
are integers. Positions in the binary are
numbered starting from 1.
Returns an Erlang term which is the result of decoding the
binary Binary
. Binary
is encoded in the Erlang
external binary representation. See term_to_binary/1
.
This implementation-dependent function increments the reduction counter for the current 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 1000.
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. If you think that you must use it, encapsulate it your own wrapper module, and/or wrap it in a catch. |
cancel_timer(Ref)
cancels a timer, where Ref
was
returned by either send_after/3
or
start_timer/3
. If the timer was there to be removed,
cancel_timer/1
returns the time in ms left until the
timer would have expired, otherwise false
(which may
mean that Ref
was never a timer, or that it had already been
cancelled, or that it had already delivered its message).
Note: usually, cancelling a timer does not guarantee that the message has not already been delivered to the message queue. However, in the special case of a process P cancelling a timer which would have sent a message to P itself, attempting to read the timeout message from the queue is guaranteed to remove the timeout in that situation:
cancel_timer(Ref), receive {timeout, Ref, _} -> ok after 0 -> ok end
Failure: badarg
if Ref
is not a reference.
erlang:check_process_code(Pid, Module)
Returns true
if the process Pid
is executing an
old version of Module, if the current call of the process
executes code for an old version of the module, if the
process has references to an old version of the module,
or if the process contains funs that references the old version
of the module.
Otherwise, it returns false
.
> erlang:check_process_code(Pid, lists). false
This is an optional BIF.
Failure: badarg
, if the process argument is not a Pid,
or the module argument is not an atom.
Concatenates a list of binaries ListOfBinaries
into
one binary.
Returns the current date as {Year, Month, Day}
> date(). {1995, 2, 19}
Moves the current version of the code of Module
to
the old version and deletes all export references of
Module
. Returns undefined
if the module does not
exist, otherwise true
.
> delete_module(test). true
This is an optional BIF.
Failure: badarg
if there is already an old version of
the module (see BIF purge_module/1
).
In normal Erlang implementations code handling - which includes loading, deleting, and replacing modules - is performed in the module |
If Ref
is a reference which the current process obtained by
calling erlang:monitor/2
, the monitoring is turned off.
No action is performed if the monitoring already is turned of before
the call. Returns true
.
After the call to erlang:monitor/2
the monitoring process
will not get any new 'DOWN'
message from this monitor into
the receive queue.
It is an error if Ref
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 Ref
is a
remote reference).
Forces the disconnection of a node. This will appear to the
node Node
as if the current node has crashed. This BIF
is mainly used in the Erlang network authentication
protocols. Returns true
if disconnection succeeds,
otherwise false
.
Failure: badarg
if Node
is not an atom.
Prints a text representation Term
on the standard output.
Useful for debugging (especially startup problems) and
strongly discouraged for other purposes.
Returns the N
th element (numbering from 1) of Tuple
.
> element(2, {a, b, c}). b
Failure: badarg
if N
< 1
, or N
> size(Tuple)
, or if the argument Tuple
is
not a tuple. Allowed in guard tests.
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]}]
Returns the value associated with Key
and deletes it
from the process dictionary. Returns undefined
if no
value is associated with Key
. Key
can be any
Erlang term.
> put(key1, {merry, lambs, are, playing}), X = erase(key1), {X, erase(key1)}. {{merry, lambs, are, playing}, undefined}
Stops the execution of the current process with the reason
Reason
. Can be caught. Reason
is any Erlang
term. Since evaluating this function causes the process to
terminate, it has no return value.
> exit(foobar). ** exited: foobar ** > catch exit(foobar). {'EXIT', foobar}
Sends an EXIT message to the process Pid
. Returns
true
.
> exit(Pid, goodbye). true
The above is not necessarily the same as: Pid ! {'EXIT', self(), goodbye} |
The above two alternatives are the
same if the process with the process identity Pid
is
trapping exits. However, if Pid
is not trapping exits, the
Pid
itself will exit and propagate EXIT signals in
turn to its linked processes.
If the reason is the atom kill
, for example
exit(Pid, kill)
, an untrappable EXIT signal will be
sent to the process Pid
. In other words, the process
Pid
will be unconditionally killed.
Returns true
.
Failure: badarg
if Pid
is not a Pid.
Stops the execution of the current process with the reason
Reason
, where Reason
is any Erlang term.
The actual EXIT term 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.
Stops the execution of the current process with the reason
Reason
, where Reason
is any Erlang term.
The actual EXIT term will be {Reason, Where}
,
where Where
is a list of the functions most recently
called (the current function first).
The Args
is expected to be the 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.
Returns a float by converting Number
to a float.
> float(55). 55.0000
-module(t). f(F) when float(F) -> float; f(F) -> not_a_float. 1> t:f(1). not_a_float 2> t:f(1.0). float 3> |
Failure: badarg
if the argument is not a float or an
integer.
erlang:float_to_binary(Float, Size)
Returns a binary containing the big-endian IEEE representation
of Float
. Size
is the size in bits, and must be
either 32 or 64.
This is an internal BIF, only to be used by OTP code. |
Failure: badarg
if the argument is not a float.
Returns a list of integers (ASCII codes) which corresponds to
Float
.
> float_to_list(7.0). "7.00000000000000000000e+00"
Failure: badarg
if the argument is not a float.
Returns a list containing information about the fun Fun
.
This BIF is only intended for debugging.
The list returned contains the following tuples, not necessarily in
the order listed here (i.e. you should not depend on the order).
{pid,Pid}
Pid
is the pid of the process that originally created the fun.
It will be the atom undefined
if the fun is given in
the tuple representation.
{module,Module}
Module
(an atom) is the module in which the fun is defined.
{index,Index}
Index
(an integer) is an index into the module's fun table.
{uniq,Uniq}
Uniq
(an integer) is a unique value for this fun.
{env,Env}
Env
(a list) is the environment or free variables for the fun.
erlang:function_exported(Module, Function, Arity)
Returns true
if the module Module
is loaded
and it contains an exported function Function/Arity
;
otherwise returns false
.
Returns false
for any BIF (functions implemented in C
rather than in Erlang).
This function is retained mainly for backwards compatibility. It is not clear why you really would want to use it.
Returns information about the Fun
as specified by
Item
, in the form {Item, Info}
.
Item can be any of the atoms id
, module
,
index
, uniq
, or env
.
See the erlang:fun_info/1
BIF.
Returns a textual representation of the fun Fun
.
Forces an immediate garbage collection of the currently executing
process. You should not use erlang:garbage_collect()
unless
you have noticed or have good reasons to suspect that the spontaneous
garbage collection will occur too late or not at all.
Improper use may seriously degrade system performance.
Compatability 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.
Works like erlang:garbage_collect() but on any process.
The same caveats apply. Returns false
if Pid
refers to a dead process; true
otherwise.
Returns the process dictionary as a list of {Key, Value}
tuples.
> put(key1, merry), put(key2, lambs), put(key3, {are, playing}), get(). [{key1, merry}, {key2, lambs}, {key3, {are, playing}}]
Returns the value associated with Key
in the process
dictionary, and undefined
if no value is
associated with Key
. Key
can be any Erlang
term.
> put(key1, merry), put(key2, lambs), put({any, [valid, term]}, {are, playing}), get({any, [valid, term]}). {are, playing}
Returns the "magic cookie" of the current node, if the node is
alive; otherwise the atom nocookie
.
Returns a list of keys which corresponds to Value
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]
Every process is a member of some process group and all groups have a leader.
This BIF returns the process identifier Pid
of the group
leader for the process which evaluates the BIF. When a process
is spawned, the group leader of the spawned process is the
same as that of the process which spawned it. Initially, at
system start-up, init
is both its own group leader and
the group leader of all processes.
Sets the group leader of Pid
to
Leader
. Typically, this is used when a processes
started from a certain shell should have another group
leader than init
. The process Leader
is normally
a process with an I/O protocol. All I/O from this group of
processes are thus channeled to the same place.
Halts the Erlang runtime system and indicates normal exit to the calling environment. Has no return value.
> halt(). unix_prompt%
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.
Returns a hash value for Term
within the range 1..Range
.
The allowed range is 1..2^27-1.
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 the
BIF |
Returns the first item of List
.
> hd([1,2,3,4,5]). 1
Allowed in guard tests.
Failure: badarg
if List
is the empty list
[]
, or is not a list.
This BIF is now equvivalent to erlang:system_info/1.
Returns a list of integers (ASCII codes) which correspond
to Integer
.
> integer_to_list(77). "77"
Failure: badarg
if the argument is not an integer.
Returns the atom true
if the current node is alive;
i.e., if the node can be part of a
distributed system. Otherwise, it returns the atom
false
.
erlang:is_builtin(Module, Function, 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.
Pid
must refer to a process on the current node.
Returns the atom true
if the process is alive, i.e., has
not exited.
Otherwise, it returns the atom false
.
This is the preferred way to check whether a process exists.
Unlike process_info/[1,2]
, is_process_alive/1
does not report zombie processes as alive.
Returns the length of List
.
> length([1,2,3,4,5,6,7,8,9]). 9
Allowed in guard tests.
Failure: badarg
if the argument is not a proper list.
Creates a link to the 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
.
Failure: badarg
if the argument is not a Pid or port.
Sends the EXIT signal noproc
to the process which evaluates
link
if the argument is the Pid of a process which
does not exist.
Returns an atom whose text representation is the integers
(Latin-1 codes) in CharIntegerList
.
> list_to_atom([69, 114, 108, 97, 110, 103]). 'Erlang'
Failure: badarg
if the argument is not a list of
integers, or if any integer in the list is not an integer
in the range [0, 255].
Returns a binary which is made from the integers and
binaries in List
. List
may be deep and may contain
any combination of integers and binaries.
Example: list_to_binary([Bin1,1,[2,3,Bin2],4|Bin3])
Failure: badarg
if the argument is not a list,
or if the list or any sublist contains anything else than
binaries or integers in the range [0, 255].
list_to_float(AsciiIntegerList)
Returns a float whose text representation is the integers
(ASCII-values) in AsciiIntegerList
.
> list_to_float([50,46,50,48,49,55,55,54,52,101,43,48]). 2.20178
Failure: badarg
if the argument is not a list of
integers, or if AsciiIntegerList
contains a bad
representation of a float.
list_to_integer(AsciiIntegerList)
Returns an integer whose text representation is the
integers (ASCII-values) in AsciiIntegerList
.
> list_to_integer([49, 50, 51]). 123
Failure: badarg
if the argument is not a list of
integers, or if AsciiIntegerList
contains a bad
representation of an integer.
Returns a Pid whose text representation is the integers
(ASCII-values) in AsciiIntegerList
. This BIF
is intended for debugging, and 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 the argument is not a list of
integers, or AsciiIntegerList
contains a bad
representation of a Pid.
Returns a tuple which corresponds to List
. List
can contain any Erlang terms.
> list_to_tuple([mary, had, a, little, {dog, cat, lamb}]). {mary, had, a, little, {dog, cat, lamb}}
Failure: badarg
if List
is not a proper list.
erlang:load_module(Module, Binary)
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}
, where Module
is the name of the module
which has been loaded, or {error, Reason}
if
load
fails. Reason
is one of the following:
badfile
Binary
has an incorrect format.
not_purged
Binary
contains a module which cannot be
loaded because old code for this module already exists (see
the BIFs purge_module
and delete_module
).
badfile
Module
Code handling - which includes
loading, deleting, and replacing of modules - is done by
the module |
This is an optional BIF.
Failure: badarg
if the first argument is not an atom,
or the second argument is not a binary.
Returns a list of all loaded Erlang modules, including preloaded modules. A module will be included in the list if it has either current code or old code or both loaded.
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}}
erlang:localtime_to_universaltime(DateTime)
Converts local date and time in DateTime
to
Universal Time Coordinated (UTC), if this is supported by
the underlying OS. Otherwise, no conversion is done and
DateTime
is returned. The return value is of the form
{{Year, Month, Day}, {Hour, Minute, Second}}
.
Failure: badarg
if the argument is not a valid date and
time tuple {{Year, Month, Day}, {Hour, Minute, Second}}
.
> erlang:localtime_to_universaltime({{1996,11,6},{14,45,17}}). {{1996,11,6},{13,45,17}}
Returns an almost unique reference.
The returned reference will reoccur after approximately 2^82 calls; therefore it is unique enough for most practical purposes.
> make_ref(). #Ref<0.0.0.135>
make_tuple(Arity, InitialValue)
Returns a new tuple of the given Arity
,
where all elements are InitialValue
.
> erlang:make_tuple(4, []). {[],[],[],[]}
Data = iolist() | binary()
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.
Failure: badarg
if the Data
argument is not a list,
or if the list or any sublist contains anything else than
binaries or integers in the range [0, 255].
Context = binary()
Creates an MD5 context, to be used in subsequent calls to
md5_update/2
.
erlang:md5_update(Context, Data) -> NewContext
Data = iolist() | binary()
Context = NewContext = binary()
Updates an MD5 Context
with Data
, and returns
a NewContext
.
erlang:md5_final(Context) -> Digest
Context = Digest = binary()
Finishes the update of an MD5 Context
and returns
the computed MD5
message digest.
Returns the atom true
if the module contained in atom
Module
is loaded, otherwise it returns the atom
false
. It does not attempt to load the module.
This BIF is intended for the implementation of the
module named |
> erlang:module_loaded(lists). true
This is an optional BIF.
Failure: badarg
if the argument is not an atom.
The current process starts monitoring Item
, and will be notified
when Item
dies, with a message
{'DOWN', Ref, Type, Object, Info}
,
where Ref
is the value
returned by the call to erlang:monitor/2
, and Info
gives
additional information.
The message is also sent if Item
is already dead.
Object
refers to the same entity as Item
, but sometimes
with a different format e.g when Item
is a process name
Object
may be the pid.
The value returned can be used for disabling the monitor
(see erlang:demonitor/1
).
The currently allowed value for Type
is the atom process
.
Item
may then be a pid, an atom Name
or a tuple
{Name, Node}
where Node also is an atom;
Info
in the message is the exit reason
of the process (or noproc
or noconnection
,
when the process does not exist or the remote node goes down, respectively,
in analogy with link/1
).
Object
in the message is the pid that Item
refers to,
but if Name
is not registered on the referred node
or if Node
is not alive then Object
is equal to Name
,
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 erlang:monitor/2
for the same item is not an
error; it results in several completely independent monitorings.
Monitors the status of the node Node
. If Flag
is true
, monitoring is turned on; if Flag
is
false
, monitoring is turned off. Calls to the BIF are
accumulated. This is shown in the following example, where a process
is already monitoring the node Node
and a
library function is called:
monitor_node(Node, true), ... some operations monitor_node(Node, false),
After the call, the process is still monitoring the node.
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.
Returns true
.
Failure: badarg
if Flag
is not true
or
false
,
and badarg
if Node
is not an atom indicating a
remote node, or if the local node is not alive.
Returns the name of the current node. If it is not a
networked node but a local Erlang runtime system, the atom
nonode@nohost
is returned.
Allowed in guard tests.
Returns the node where Arg
is located. Arg
can
be a Pid, a reference, or a port.
Allowed in guard tests.
Failure: badarg
if Arg
is not a Pid, reference, or port.
Returns a list of all known nodes in the system, excluding the current node.
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. 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)
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}
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.
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.
Atom
file
module instead.
The atom is assumed to be the name of an
external resource. A transparent connection is
established between Erlang and the resource named by the
atom Atom
. The characteristics of the port depend
on the type of resource. If Atom
represents a
normal file, the entire contents of the file is sent to
the Erlang process as one or more messages. When
messages are sent to the port, it causes data to be
written to the file.
{fd, In, Out}
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 values are:
{packet, N}
N
bytes, with the most significant byte first. Valid
values for N
are 1, 2, or 4.
stream
{line, N}
{Flag, Line}
, where Flag
is either
eol
or noeol
and Line
is the actual data
delivered (without the newline sequence).N
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 anywere 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
.{packet, N}
and {line, N}
settings are mutually
exclusive.
{cd, Dir}
{spawn, Command}
.
The external program starts using Dir as its working directory.
Dir must be a string. Not available on VxWorks.
{env, Environment}
{spawn, Command}
.
The environment of the started process is extended using the
environment specifications in Environment
.
Environment
should be a list of tuples {Name
,
Value
}, where Name
is the name of an
environment variable, and Value
is the value it is to
have in the spawned port process. Both Name
and
Value
must be strings. The one exception is Value
being the atom false
(in analogy with
os:getenv/1
), which removes the environment variable.
Not available on VxWorks.
exit_status
{spawn, Command}
where Command
refers to an external program.
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
{spawn, Command}
. It
allows the standard input and output (file
descriptors 0 and 1) of the spawned (UNIX) process for
communication with Erlang.
nouse_stdio
stderr_to_stdout
stderr_to_stdout
and nouse_stdio
are mutually exclusive.
in
out
binary
eof
{Port, eof}
message will be sent to the process
holding the port.
The default is stream
for all types of port and
use_stdio
for spawned ports.
Failure: badarg
if the format of PortName
or
PortSettings
is incorrect. If the port cannot be
opened, the exit reason is the Posix error code which most
closely describes the error, or einval
if no Posix code
is appropriate. The following Posix error codes
may appear:
enomem
eagain
enametoolong
emfile
enfile
During use of a port opened using {spawn, Name}
, errors arising
when sending messages to it are reported to the owning process using
exit signals of the form {'EXIT', Port, PosixCode}
. Posix codes
are listed in the documentation for the file
module.
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
.
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 should always be used instead of the old
deprecated erlang:hash/2
BIF, as it calculates
better hashes for all datatypes.
Returns a list which corresponds to the process Pid
.
This BIF is intended for debugging and for use in the Erlang operating system. It should not be used in application programs. |
> pid_to_list(whereis(init)). "<0.0.0>"
Failure: badarg
if the argument is not a Pid.
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).
Returns: true
.
Failure: badarg
if Port
is not an open port.
For comparision: 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 current 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 current 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}
.
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).
Returns: true
.
Failure: badarg
if Port
is not an open port
or if Data
is not an I/O list. An I/O list is
a binary or a (possibly) deep list of binaries or integers
in the range 0 through 255.
For comparision: 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 current process is not the port owner,
the port owner fails with badsig
.
The port owner fails withbadsig
also if
Data
is not a legal I/O 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}}
.
Sets the port owner (the connected port) to Pid
.
Roughly the same as
Port ! {self(), {connect, Pid}}
except for the following:
{Port,connected}
.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
.
Returns: true
.
Failure: badarg
if Port
is not an open port
or if Pid
is not a valid local pid.
For comparision: 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 current 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 current process is not the port owner
the port owner fails with badsig
.
The port owner fails with badsig
also
if Pid
is not a valid 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}}
.
port_control(Port, Operation, Data)
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,
if Operation
cannot fit in a 32-bit integer,
if the port driver does not support synchronous control operations,
if Data
is not a valid I/O list
(see port_command/2),
or if the port driver so decides for any reason
(probably something wrong with
Operation
or Data
).
Returns information about the port Port
as specified by
Item
, which can be any one of the atoms
id
, connected
,
links
, name
, input
, or output
.
{id, Index}
Index
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, ListOfPids}
ListOfPids
is a list of Pids with processes to
which the port has a link.
{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.
All implementations may not support all of the above
Items
. Returns undefined
if the port does not
exist.
Failure: badarg
if Port
is not a process
identifier, or if Port
is a port identifier of a
remote process.
Returns a list of all ports on the current node.
Returns a list which corresponds to the port identifier Port
.
This BIF is intended for debugging and for use in the Erlang operating system. It should not be used in application programs. |
> erlang:port_to_list(open_port({spawn,ls}, [])). "#Port<0.15>"
Failure: badarg
if the argument is not a port.
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)
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 stack,
including information about the call chain, with
the most recent data printed last. The format
of the output is not further defined. Pid
may be a zombie
process.
Sets certain flags for the process which calls this function. Returns the old value of the flag.
process_flag(trap_exit, Boolean)
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.
process_flag(error_handler, Module)
process_flag(priority, Level)
Level
is an
atom. All implementations support three priority levels,
low
, normal
, and high
. The default
is 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.
Whenever the size of the call saving list is set, its contents
are reset.
Failure: badarg
if Flag
is not an atom, or is
not a recognized flag value, or if Option
is not a
recognized term for Flag
.
process_flag(Pid, Flag, Option)
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 process on the
local node, or if
Flag
is not an atom, or is
not a recognized flag value, or if Option
is not a
recognized term for Flag
.
Returns a long list which contains information about the
process Pid
. This BIF is only intended for
debugging. It should not be used for any other purpose. The list returned contains the following tuples. The order in which these tuples are returned is not defined, nor are all the tuples mandatory.
{current_function, {Module, Function,
Arguments}}
Module
,
Function
, Arguments
is the current function
call of the process.
{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).
{group_leader, Groupleader}
Groupleader
is group leader for the I/O of
the process.
{heap_size, Size}
Size
is the heap size of the process in heap
words.
{initial_call, {Module, Function,
Arity}}
Module
, Function
,
Arity
is the initial function call with which the
process was spawned.
{links, ListOfPids}
ListOfPids
is a list of Pids, with processes to
which the process has a link.
{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.
{priority, Level}
Level
is the current priority level for the
process. Only low
and normal
are always
supported.
{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.
{stack_size, Size}
Size
is the stack size of the process in stack
words.
{status, Status}
Status
is the status of the process.
Status
is waiting
(waiting for a message),
running
, runnable
(ready to run, but another
process is running), suspended
(suspended on a "busy"
port or by the erlang:suspend_process/1
BIF), or
exiting
(if the process has exited, but remains as a zombie).
{trap_exit, Boolean}
Boolean
is true
if the process is trapping
exits, otherwise it is false
.
Failure: badarg
if the argument is not a Pid, or
if Pid
is a Pid of a remote process.
Returns information about the process Pid
as specified by
Item
, in the form
{Item, Info}
. Item
can be any one of the atoms
backtrace
,
current_function
, dictionary
, error_handler
,
exit
,
group_leader
, heap_size
, initial_call
,
last_calls
,
links
, memory
, message_queue_len
,
messages
, monitored_by
, monitors
,
priority
, reductions
,
registered_name
, stack_size
, status
or trap_exit
.
Returns undefined
if no information is
known about the process.
process_info
can be used to
obtain information about processes which have exited but whose
data are still kept, so called zombie processes. To determine
whether to keep information about dead processes, use the BIF
erlang:system_flag/2
. Since process_info
does not
necessarily return undefined
for a dead process, use
is_process_alive/1
to check whether a process is alive.
Item exit
returns []
if the process is alive,
or {exit, Reason}
if the process has exited,
where Reason
is the exit reason.
Item registered_name
returns []
if
the process has no registered name. If the process is a zombie,
the registered name it had when it died is returned.
Item memory
returns {memory, Size}, where Size
is the size of the process in bytes. This includes stack, heap and
internal structures.
Item backtrace
returns a binary, which 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.
Item last_calls
returns 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.
Item links
returns a list of pids to which the
process is linked.
Item monitors
returns a list of monitors
(started by erlang: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, {Name, Node}}.
Item monitored_by
returns a list of pids
that are monitoring the process (with erlang:monitor/2).
Not all implementations support every one of the above
Items
.
Failure: badarg
if Pid
is not a process
identifier, or if Pid
is a process identifier of a
remote process.
Returns a list of all processes on the current node, including zombie processes. See system_flag/2.
> processes(). [<0.0.1>, <0.1.1>, <0.2.1>, <0.3.1>, <0.4.1>, <0.6.1>]
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 this module.
In normal Erlang implementations, code handling - which is
loading, deleting and replacing modules - is evaluated
by the module |
This is an optional BIF.
Failure: badarg
if Module
does not exist.
Adds a new Value
to the process dictionary and
associates it with Key
. If a value is already
associated with Key
, that value is deleted and replaced
by the new value Value
. It returns any value
previously associated with Key
, or undefined
if
no value was associated with Key
. Key
and
Value
can be any valid Erlang terms.
The values stored when |
> X = put(name, walrus), Y = put(name, carpenter), Z = get(name), {X, Y, Z}. {undefined, walrus, carpenter}
returns_timer(Ref)
returns the number of milliseconds
remaining for a timer, where Ref
was
returned by either send_after/3
or
start_timer/3
. If the timer was active,
read_timer/1
returns the time in milliseconds left until the
timer will expire, otherwise false
(which may
mean that Ref
was never a timer, or that it has been
cancelled, or that it has already delivered its message).
Failure: badarg
if Ref
is not a reference.
Returns a list which corresponds to the reference Ref
.
This BIF is intended for debugging and for use in the Erlang operating system. It should not be used in application programs. |
> erlang:ref_to_list(make_ref()). "#Ref<0.0.0.134>"
Failure: badarg
if the argument is not a reference.
Associates the name Name
with the process identity
Pid
.
Name
, which must be an atom, can be used instead of a pid
in the send operator (Name ! Message
).
Returns true
.
Failure: badarg
if Pid
is not an active
process, or if Pid
is a process on another node,
or if the name Name
is already in use,
or if the process is already registered (it already has a name),
or if the name Name
is not an atom, or if Name
is the atom undefined
.
Returns a list of names which have been registered using
register/2
.
> registered(). [code_server, file_server, init, user, my_db]
Resume a suspended process. This should be used for debugging purposes only, not in production code.
Returns an integer by rounding the number Number
.
Allowed in guard tests.
> round(5.5). 6
Failure: badarg
if the argument is not a float (or an
integer).
Returns the process identity of the calling process. Allowed in guard tests.
> self(). <0.16.1>
erlang:send_after(Time, Pid, Msg)
Time
is a non-negative integer, Pid
is
either a pid or an atom, and Msg
is any Erlang term.
The function returns a reference.
After Time
ms, send_after/3
sends Msg
to Pid
.
If Pid
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. See also
start_timer/3
and cancel_timer/1
.
Limitations: Pid
must be a process on the
local node. The timeout value must fit in 32 bits.
Failure: badarg
if any arguments are of the
wrong type, or do not obey the limitations noted above.
erlang:set_cookie(Node, Cookie)
Sets the "magic cookie" of Node
to the atom Cookie
.
If Node
is the current node, the BIF also sets the
cookie of all other unknown nodes to Cookie
(see
auth(3)).
setelement(Index, Tuple, Value)
Returns a tuple which is a copy of the argument Tuple
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}
Failure: badarg
if Index
is not an integer, or
Tuple
is not a tuple, or if Index
is less than 1
or greater than the size of Tuple
.
Returns an integer which is the size of the argument
Item
, where Item
must be either a tuple or a
binary.
> size({morni, mulle, bwange}). 3
Allowed in guard tests.
Failure: badarg
if Item
is not a tuple or a
binary.
Returns the Pid of a new process started by the application
of Fun
to the empty argument list []
. Otherwise
works like spawn/3
.
Returns the Pid of a new process started by the application
of Fun
to the empty argument list []
on node
Node
.
Otherwise works like spawn/4
.
spawn(Module, Function, ArgumentList)
Returns the Pid of a new process started by the application
of Module:Function
to ArgumentList
. Note:
The new process created will be placed in the system
scheduler queue and will be run some time later.
error_handler:undefined_function(Module, Function,
ArgumentList)
is evaluated by the new process if
Module:Function/Arity
does not exist (where Arity
is the length of ArgumentList).
The error handler can be redefined (see BIF
process_flag/2)
). Arity
is the length of the
ArgumentList
. If error_handler
is undefined,
or the user has redefined the default error_handler
so its replacement is undefined, a failure with the reason
undef
will occur.
> spawn(speed, regulator, [high_speed, thin_cut]). <0.13.1>
Failure: badarg
if Module
and/or Function
is not an atom, or if ArgumentList
is not a list.
spawn(Node, Module, Function, ArgumentList)
Works like spawn/3
, with the exception that
the process is spawned at Node
. If Node
does not
exist, a useless Pid is returned.
Failure: badarg
if Node
, Module
, or
Function
are not atoms, or ArgumentList
is not a list.
Works like spawn/1
except that a link is made from the
current process to the newly created one, atomically.
Works like spawn/2
except that a link is made from the
current process to the newly created one, atomically.
spawn_link(Module, Function, ArgumentList)
This BIF is identical to the following code being evaluated in an atomic operation:
> Pid = spawn(Module, Function, ArgumentList), link(Pid), Pid.
This BIF is necessary since the process created might run
immediately and fail before link/1
is called.
Failure: See spawn/3
.
spawn_link(Node, Module, Function, ArgumentList)
Works like spawn_link/3
, except that the
process is spawned at Node
. If an attempt is made to
spawn a process on a node which does not exist, a useless
Pid is returned, and an EXIT signal will be received.
spawn_opt(Module, Function, ArgumentList, Options)
Works exactly like spawn/3, except that an extra option list can be given when creating the process.
This BIF is only useful for performance tuning. Random tweaking of the parameters without measuring execution times and memory consumption may actually make things worse. Furthermore, most of the options are inherently implementation-dependent, and they can be changed or removed in future versions of OTP. |
link
spawn_link/3
does).
{priority, Level}
process_flag(priority, Level)
in the start function
of the new process, except that the priority will be set before the
process is scheduled in the first time.
{fullsweep_after, Number}
fullsweep_after
option, you can 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.
fullsweep_after
.
Firstly, if you want binaries that are no longer used to be thrown
away as soon as possible. (Set Number
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 Number
to a suitable
value such as 10 or 20. Thirdly, in embedded systems with limited
amount of RAM and no virtual memory, you might want to preserve
memory by setting Number
to zero. (You probably want to the
set the value globally. See
system_flag/2.)
{min_heap_size, Size}
Size
values.
Returns a tuple which contains two binaries which are the
result of splitting Binary
into two parts at
position Pos
. This is not a destructive
operation. After this operation, there are three
binaries altogether. Returns a tuple consisting of the two new
binaries. For example:
1> B = list_to_binary("0123456789"). #Bin 2> size(B). 10 3> {B1, B2} = split_binary(B,3). {#Bin, #Bin} 4> size(B1). 3 5> size(B2). 7
Failure: badarg
if Binary
is not a binary, or
Pos
is not an integer or is out of range.
erlang:start_timer(Time, Pid, Msg)
Time
is a non-negative integer, Pid
is
either a pid or an atom, and Msg
is any Erlang term.
The function returns a reference.
After Time
ms, start_timer/3
sends the
tuple {timeout, Ref, Msg}
to Pid
, where
Ref
is the reference returned by
start_timer/3
.
If Pid
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. See also
send_after/3
and cancel_timer/1
.
Limitations: Pid
must be a process on the
local node. The timeout value must fit in 32 bits.
Failure: badarg
if any arguments are of the
wrong type, or do not obey the limitations noted above.
Returns information about the system. Type
is an atom
which is one of:
run_queue
runtime
{Total_Run_Time, Time_Since_Last_Call}
.
wall_clock
{Total_Wallclock_Time,
Wallclock_Time_Since_Last_Call}
. wall_clock
can be used in the same manner as the atom
runtime
, except that real time is measured as
opposed to runtime or CPU time.
reductions
{Total_Reductions, Reductions_Since_Last_Call}
.
garbage_collection
{Number_of_GCs, Words_Reclaimed, 0}
. This
information may not be valid for all implementations.
All times are in milliseconds.
> statistics(runtime). {1690, 1620} > statistics(reductions). {2046, 11} > statistics(garbage_collection). {85, 23961, 0}
Failure: badarg
if Type
is not one of the atoms
shown above.
Suspend a process. This should be used for debugging purposes only, not in production code.
erlang:system_flag(Flag, Value)
This BIF sets various system properties of the Erlang node.
If Flag
is a valid name of a system flag, its value is
set to Value
, and the old value is returned.
The following values for Flag
are currently allowed:
keep_zombies
, fullsweep_after
, and
backtrace_depth
.
The value of the keep_zombies
flag
is an integer which indicates how many processes to keep in
memory when they exit, so that they can be inspected with
process_info
. Originally, the number is 0.
Setting it to 0 disables the keeping of zombies.
A negative number -N
means to keep the N
latest zombies; a positive value N
means to keep the
N
first zombies. Setting the flag always clears away
any already saved zombies.
The maximum number of zombies which can be saved is 100.
Resources owned by a zombie process are cleared away immediately
when the process dies, for example ets tables and ports, and
cannot be inspected.
The value of the fullsweep_after
is an non-negative
integer which indicates how many times generational garbages
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 zero can help to conserve memory.
An alternative way to set this value is through
the (operating system) environment variable ERL_FULLSWEEP_AFTER
.
What
can be any of the
atoms info
, procs
, loaded
, dist
,
thread_pool_size
or allocated_areas
.
The BIF returns information of the different `topics' as
binary data objects (except for thread_pool_size and
allocated_areas, see below).
erlang:system_info(thread_pool_size)
erlang:system_info(allocated_areas)
(i)nfo
alternative under the BREAK
menu. The
BREAK
menu can be reached by typing Control C
in the Erlang shell.
Failure: badarg
if What
is not one of the atoms
shown above.
This BIF returns the encoded value of any Erlang term and turns it into the Erlang external term format. It 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.
Returns a binary data object which corresponds
to an external representation of the Erlang term Term
.
This BIF returns the encoded value of any Erlang term and
turns it into the Erlang external term format.
If the Options
list contains the atom compressed
,
the external term format will be compressed.
The compressed format is automatically recognised by
binary_to_term/1
in R7.
Returns a binary data object which corresponds
to an external representation of the Erlang term Term
.
Failure: badarg
if Options
is not a list or
if contains something else than the supported flags (currently
only the atom compressed
).
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.
Returns the tuple {Hour, Minute, Second}
of the
current system time. The time zone correction is
implementation-dependent.
> time(). {9, 42, 44}
Returns List
stripped of its first element.
> tl([geesties, guilies, beasties]). [guilies, beasties]
Failure: badarg
if List
is the empty list
[]
, or is not a list. Allowed in guard tests.
erlang:trace(PidSpec, How, Flaglist)
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
new
all
Flaglist
can contain any number of the following
atoms (the "message tags" refers to the list of message following
below):
send
Pid
sends. Message tags: send
,
send_to_non_existing_process
.
'receive'
Pid
receives. Message tags: 'receive'
.
procs
spawn
,
link
, exit
. Message tags: spawn
,
exit
, link
, unlink
,
getting_linked
.
call
call
, return_from
.
return_to
local
option to
erlang:trace_pattern/3
. The semantics is that a message is sent when a call
traced function actually returns, i.e. 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.
{return_trace}
match_spec action instead.
return_to
.
running
in
, out
.
garbage_collection
gc_start
, gc_end
.
timestamp
erlang:now()
.
arity
{Mod, Fun, Args}
in call traces,
there will be {Mod, Fun, Arity}
.
set_on_spawn
Pid
inherit the
flags of Pid
, including the set_on_spawn
flag.
set_on_first_spawn
Pid
inherit the flags of Pid
That process does not
inherit the set_on_first_spawn
flag.
set_on_link
Pid
inherit
the flags of Pid
, including the set_on_link
flag.
set_on_first_link
Pid
inherit the flags of Pid
. That process does not
inherit the set_on_first_link
flag.
{tracer, Tracer}
Tracer
should be the pid for a local process or
the port identifier for a local port. All trace
messages will be sent to the given process or 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. If
the timestamp
flag is given, the first element of the
tuple will be trace_ts
and the timestamp will be in
the last element of the tuple.
{trace, Pid, 'receive', Message}
Pid
receives something.
{trace, Pid, send, Msg, To}
Pid
sends a message.
{trace, Pid, send_to_non_existing_process, Msg, To}
Pid
sends a message to a non existing process.
{trace, Pid, call, {M,F,A}}
{trace, Pid, return_to, {M,F,A}}
{M,F,A}
. This message will be sent if both
the call
and the return_to
flags are present
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 (i.e. the
functions match specification matched and
{message,false}
was not an action).
{trace, Pid, return_from, {M,F,A}, ReturnValue}
{M,F,A}
This trace message is sent when the
call
flag has been specified, and the function
has a match specification with a return_trace
action.
{trace, Pid, spawn, Pid2}
Pid2
.
{trace, Pid, exit, Reason}
Reason
.
{trace, Pid, link, Pid2}
Pid2
.
{trace, Pid, unlink, Pid2}
Pid2
.
{trace, Pid, getting_linked, Pid2}
Pid2
.
{trace, Pid, in, {M,F,A}}
{trace, Pid, out, {M,F,A}}
{trace, Pid, gc_start, Info}
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
old_heap_size
stack_size
recent_size
mbuf_size
{trace, Pid, gc_end, Info}
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 PidSped
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: badarg
if bad arguments are given.
erlang:trace_info(PidOrFunc, Item)
Returns trace information about a process or exported 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
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
[]
.
To get information about an exported function,
PidOrFunc
should be a three-element tuple: {Module,
Function, Arity}
or the atom on_load
.
No wildcards are allowed.
Item
must have one of the following values:
traced
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 this function is not traced at all.
match_spec
false
and if the function is traced but
has no match specification defined, the returned value
is []
.
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)
The same as erlang:trace_pattern(MFA, MatchSpec, []), retained for backward compatibility.
erlang:trace_pattern(MFA, MatchSpec, FlagList)
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 spefication
comprises a pattern that the arguments to the function must
match, a guard expression which must evaluate to true
and 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:
{Mod,Func,'_'}
Func
in module Mod
.
{Mod,'_','_'}
Mod
.
{'_','_','_'}
Other combinations, such as {Mod,'_',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
true
MatchSpecList
true
. See the ERTS User's Guide
for a description of match specifications.
The FlagList
parameter is a list of options. The
following options are allowed:
global
local
return_to
flag is set for the
process, a return_to
message will also be sent
when this function returns to its caller.
The options are mutually exclusive and global
is the
default (if no options are specified). A function can be
either globally or locally traced. If global trace is
specified for a specified set of functions, local trace 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).
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.
Failure: badarg
for invalid MFA
or MatchSpec
.
Returns an integer by the truncation of Number
.
Allowed in guard tests.
> trunc(5.5). 5
Failure: badarg
if the argument is not a float, or an integer.
Returns a list which corresponds to
Tuple
. Tuple
may contain any valid Erlang terms.
> tuple_to_list({share, {'Ericsson_B', 163}}). [share, {'Ericsson_B', 163}]
Failure: badarg
if the argument is not a tuple.
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(DateTime)
Converts UTC date and time in DateTime
to
local date and time if supported by the underlying operating system.
Otherwise, no conversion is done, and
DateTime
is returned. The return value is of the form
{{Year, Month, Day}, {Hour, Minute, Second}}
.
Failure: badarg
if the argument is not a valid date and
time tuple {{Year, Month, Day}, {Hour, Minute, Second}}
.
> erlang:universaltime_to_localtime({{1996,11,6},{14,18,43}}). {{1996,11,7},{15,18,43}}
Removes a link, if there is one, from the calling process
to another process given by the argument Pid
.
Returns true
. Will not fail if not linked to
Pid
, or if Pid
does not exist.
Failure: badarg
if the argument is not a valid Pid.
Removes the registered name for a process, given by the atom argument Name
.
Returns the atom true
.
> unregister(db). true
Failure: badarg
if Name
is not the name of a
registered process.
Users are advised not to unregister system processes.
Returns the Pid for the process registered under Name
(see
register/2
). Returns undefined
if no such process
is registered.
> whereis(user). <0.3.1>
Failure: badarg
if the argument is not an atom.
Voluntarily let other processes (if any) get a chance to execute.
Using yield()
is similar to receive after 1 -> ok end
,
except that yield()
is faster.