Process
Conveniences for working with processes and the process dictionary.
Besides the functions available in this module, the Kernel module exposes and auto-imports some basic functionality related to processes available through the functions:
-
Kernel.spawn/1andKernel.spawn/3 -
Kernel.spawn_link/1andKernel.spawn_link/3 -
Kernel.spawn_monitor/1andKernel.spawn_monitor/3 -
Kernel.self/0 -
Kernel.send/2
Summary
Types
Functions
- alive?(pid)
-
Returns
trueif the process exists and is alive (i.e. it is not exiting and has not exited yet). Otherwise, returnsfalse - cancel_timer(timer_ref)
-
Cancels a timer created by
send_after/3 - delete(key)
-
Deletes the given
keyfrom the process dictionary - demonitor(monitor_ref, options \\ [])
-
If
monitor_refis a reference which the calling process obtained by callingmonitor/1, this monitoring is turned off. If the monitoring is already turned off, nothing happens - exit(pid, reason)
-
Sends an exit signal with the given
reasonto thepid - flag(flag, value)
-
Sets certain flags for the process which calls this function. Returns the old value of the
flag - flag(pid, flag, value)
-
Sets certain flags for the process
pid, in the same manner asflag/2. Returns the old value of theflag. The allowed values forflagare only a subset of those allowed inflag/2, namely:save_calls - get()
-
Returns all key-value pairs in the process dictionary
- get(key, default \\ nil)
-
Returns the value for the given
keyordefaultifkeyis not set - get_keys()
-
Returns all keys in the process dictionary
- get_keys(value)
-
Returns all keys that have the given
value - group_leader()
-
Returns the PID of the group leader for the process which evaluates the function
- group_leader(pid, leader)
-
Sets the group leader of
pidtoleader. Typically, this is used when a processes started from a certain shell should have a group leader other than:init - hibernate(mod, fun, args)
-
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
- info(pid)
-
Returns information about the process identified by
pid, or returnsnilif the process is not alive. Use this only for debugging information - info(pid, spec)
-
Returns information about the process identified by
pid, or returnsnilif the process is not alive - link(pid)
-
Creates a link between the calling process and another process (or port)
pid, if there is not such a link already - list()
-
Returns a list of process identifiers corresponding to all the processes currently existing on the local node
- monitor(item)
-
The calling process starts monitoring the given
item. It returns the monitor reference - put(key, value)
-
Stores the given
key-valuepair in the process dictionary - read_timer(timer_ref)
-
Reads a timer created by
send_after/3 - register(pid_or_port, name)
-
Registers the given
pid_or_portunder the givenname - registered()
-
Returns a list of names which have been registered using
register/2 - send(dest, msg, options)
-
Sends a message to the given process
- send_after(dest, msg, time, opts \\ [])
-
Sends
msgtodestaftertimemilliseconds - sleep(timeout)
-
Sleeps the current process by
timeout - spawn(fun, opts)
-
Spawns the given function according to the given options
- spawn(mod, fun, args, opts)
-
Spawns the given function from module
mod, passing the givenargsaccording to the given options - unlink(pid)
-
Removes the link, if there is one, between the calling process and the process or port referred to by
pid. Returnstrueand does not fail, even if there is no link oriddoes not exist - unregister(name)
-
Removes the registered
name, associated with a PID or a port identifier - whereis(name)
-
Returns the PID or port identifier with the registered
name. Returnsnilif the name is not registered
Types
spawn_opt()
spawn_opt() ::
:link |
:monitor |
{:priority, :low | :normal | :high} |
{:fullsweep_after, non_neg_integer()} |
{:min_heap_size, non_neg_integer()} |
{:min_bin_vheap_size, non_neg_integer()} spawn_opts()
spawn_opts() :: [spawn_opt()]
Functions
alive?(pid)
alive?(pid()) :: boolean()
Returns true if the process exists and is alive (i.e. it is not exiting and has not exited yet). Otherwise, returns false.
pid must refer to a process at the local node.
Inlined by the compiler.
cancel_timer(timer_ref)
cancel_timer(reference()) :: non_neg_integer() | false
Cancels a timer created by send_after/3.
When the result is an integer, it represents the time in milliseconds left until the timer would have expired.
When the result is false, a timer corresponding to timer_ref could not be found. This can be either because the timer expired, already has been canceled, or because timer_ref never corresponded to a timer.
If the timer has expired, the timeout message has been sent, but it does not tell you whether or not it has arrived at its destination yet.
Inlined by the compiler.
delete(key)
delete(term()) :: term() | nil
Deletes the given key from the process dictionary.
demonitor(monitor_ref, options \\ [])
demonitor(reference(), options :: [:flush | :info]) :: boolean()
If monitor_ref is a reference which the calling process obtained by calling monitor/1, this monitoring is turned off. If the monitoring is already turned off, nothing happens.
See :erlang.demonitor/2 for more info.
Inlined by the compiler.
exit(pid, reason)
exit(pid(), term()) :: true
Sends an exit signal with the given reason to the pid.
The following behaviour applies if reason is any term except :normal or :kill:
-
If
pidis not trapping exits,pidwill exit with the givenreason. -
If
pidis trapping exits, the exit signal is transformed into a message{:EXIT, from, reason}and delivered to the message queue ofpid.
If reason is the atom :normal, pid will not exit (unless pid is the calling process, in which case it will exit with the reason :normal). 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 reason :killed.
Inlined by the compiler.
Examples
Process.exit(pid, :kill)
flag(flag, value)
flag(process_flag(), term()) :: term()
Sets certain flags for the process which calls this function. Returns the old value of the flag.
See :erlang.process_flag/2 for more info.
flag(pid, flag, value)
flag(pid(), :save_calls, non_neg_integer()) :: non_neg_integer()
Sets certain flags for the process pid, in the same manner as flag/2. Returns the old value of the flag. The allowed values for flag are only a subset of those allowed in flag/2, namely :save_calls.
See :erlang.process_flag/3 for more info.
get()
get() :: [{term(), term()}] Returns all key-value pairs in the process dictionary.
Inlined by the compiler.
get(key, default \\ nil)
get(term(), default :: term()) :: term()
Returns the value for the given key or default if key is not set.
get_keys()
get_keys() :: [term()]
Returns all keys in the process dictionary.
Inlined by the compiler.
get_keys(value)
get_keys(term()) :: [term()]
Returns all keys that have the given value.
Inlined by the compiler.
group_leader()
group_leader() :: pid()
Returns the PID of the group leader for the process which evaluates the function.
group_leader(pid, leader)
group_leader(pid(), leader :: pid()) :: true
Sets the group leader of pid to leader. Typically, this is used when a processes started from a certain shell should have a group leader other than :init.
hibernate(mod, fun, args)
hibernate(module(), atom(), list()) :: no_return()
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.
See :erlang.hibernate/3 for more info.
Inlined by the compiler.
info(pid)
info(pid()) :: Keyword.t()
Returns information about the process identified by pid, or returns nil if the process is not alive. Use this only for debugging information.
See :erlang.process_info/1 for more info.
info(pid, spec)
info(pid(), atom() | [atom()]) ::
{atom(), term()} |
[{atom(), term()}] |
nil Returns information about the process identified by pid, or returns nil if the process is not alive.
See :erlang.process_info/2 for more info.
link(pid)
link(pid() | port()) :: true
Creates a link between the calling process and another process (or port) pid, if there is not such a link already.
See :erlang.link/1 for more info.
Inlined by the compiler.
list()
list() :: [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., alive?/1 will return false for a process that is exiting, but its process identifier will be part of the result returned.
See :erlang.processes/0 for more info.
monitor(item)
monitor(pid() | {reg_name :: atom(), node :: atom()} | reg_name() :: atom()) :: reference() The calling process starts monitoring the given item. It returns the monitor reference.
See the need for monitoring for an example. See :erlang.monitor/2 for more info.
Inlined by the compiler.
put(key, value)
put(term(), term()) :: term() | nil
Stores the given key-value pair in the process dictionary.
The return value is the value that was previously stored under the key key (or nil in case no value was stored under key).
read_timer(timer_ref)
read_timer(reference()) :: non_neg_integer() | false
Reads a timer created by send_after/3.
When the result is an integer, it represents the time in milliseconds left until the timer will expire.
When the result is false, a timer corresponding to timer_ref could not be found. This can be either because the timer expired, already has been canceled, or because timer_ref never corresponded to a timer.
If the timer has expired, the timeout message has been sent, but it does not tell you whether or not it has arrived at its destination yet.
Inlined by the compiler.
register(pid_or_port, name)
register(pid() | port(), atom()) :: true
Registers the given pid_or_port under the given name.
name must be an atom and can then be used instead of the PID/port identifier when sending messages with Kernel.send/2.
register/2 will fail with ArgumentError if the PID/Port is not existing locally and alive, if the name is already registered or if the pid_or_port is already registered to a different name.
The following names are reserved and cannot be assigned to processes nor ports: nil, false, true or :undefined.
registered()
registered() :: [atom()]
Returns a list of names which have been registered using register/2.
send(dest, msg, options)
send(dest, msg, [option]) ::
:ok |
:noconnect |
:nosuspend when dest: pid() | port() | atom() | {atom(), node()}, msg: any(), option: :noconnect | :nosuspend Sends a message to the given process.
If the option :noconnect is used and sending the message would require an auto-connection to another node the message is not sent and :noconnect is returned.
If the option :nosuspend is used and sending the message would cause the sender to be suspended the message is not sent and :nosuspend is returned.
Otherwise the message is sent and :ok is returned.
Examples
iex> Process.send({:name, :node_does_not_exist}, :hi, [:noconnect])
:noconnect send_after(dest, msg, time, opts \\ [])
send_after(pid() | atom(), term(), non_neg_integer(), [option]) :: reference() when option: {:abs, boolean()} Sends msg to dest after time milliseconds.
If dest is a PID, it must be the PID of a local process, dead or alive. If dest is an atom, it must be the name of a registered process which is looked up at the time of delivery. No error is given if the name does not refer to a process.
This function returns a timer reference, which can be read or canceled with read_timer/1 and cancel_timer/1.
Finally, the timer will be automatically canceled if the given dest is a PID which is not alive or when the given PID exits. Note that timers will not be automatically canceled when dest is an atom (as the atom resolution is done on delivery).
Options
-
:abs- (boolean) whenfalse,timeis treated as relative to the current monotonic time. Whentrue,timeis the absolute value of the Erlang monotonic time at whichmsgshould be delivered todest. To read more about Erlang monotonic time and other time-related concepts, look at the documentation for theSystemmodule. Defaults tofalse.
sleep(timeout)
Sleeps the current process by timeout.
timeout is either the number of milliseconds to sleep as an integer or the atom :infinity. When :infinity is given, the current process will suspend forever.
Use this function with extreme care. For almost all situations where you would use sleep/1 in Elixir, there is likely a more correct, faster and precise way of achieving it with message passing.
For example, if you are waiting a process to perform some action, it is better to communicate.
In other words, do not:
Task.start_link fn -> do_something() ... end # Wait until work is done Process.sleep(2000)
But do:
parent = self() Task.start_link fn -> do_something() send parent, :work_is_done ... end receive do :work_is_done -> :ok after 30_000 -> :timeout # Optional timeout end
Or even use Task.async/1 and Task.await/2 in the example above.
Similarly, if you are waiting for a process to terminate, use monitor instead of sleep. Do not:
Task.start_link fn -> ... end # Wait until task terminates Process.sleep(2000)
Instead do:
{:ok, pid} =
Task.start_link fn ->
...
end
ref = Process.monitor(pid)
receive do
{:DOWN, ^ref, _, _, _} -> :task_is_down
after
30_000 -> :timeout # Optional timeout
end spawn(fun, opts)
spawn((() -> any()), spawn_opts()) :: pid() | {pid(), reference()} Spawns the given function according to the given options.
The result depends on the given options. In particular, if :monitor is given as an option, it will return a tuple containing the PID and the monitoring reference, otherwise just the spawned process PID.
It also accepts extra options, for the list of available options check :erlang.spawn_opt/4.
Inlined by the compiler.
spawn(mod, fun, args, opts)
spawn(module(), atom(), list(), spawn_opts()) ::
pid() |
{pid(), reference()} Spawns the given function from module mod, passing the given args according to the given options.
The result depends on the given options. In particular, if :monitor is given as an option, it will return a tuple containing the PID and the monitoring reference, otherwise just the spawned process PID.
It also accepts extra options, for the list of available options check :erlang.spawn_opt/4.
Inlined by the compiler.
unlink(pid)
unlink(pid() | port()) :: true
Removes the link, if there is one, between the calling process and the process or port referred to by pid. Returns true and does not fail, even if there is no link or id does not exist
See :erlang.unlink/1 for more info.
Inlined by the compiler.
unregister(name)
unregister(atom()) :: true
Removes the registered name, associated with a PID or a port identifier.
Fails with ArgumentError if the name is not registered to any PID or port.
whereis(name)
whereis(atom()) :: pid() | port() | nil
Returns the PID or port identifier with the registered name. Returns nil if the name is not registered.
See :erlang.whereis/1 for more info.
© 2012 Plataformatec
Licensed under the Apache License, Version 2.0.
https://hexdocs.pm/elixir/1.4.5/Process.html