Erlang -- Processes

Erlang Reference Manual

User's Guide

Version 9.3

- User's Guide
- PDF
- Top

- Expand All
- Contract All

### Chapters

- Introduction
  - Top of chapter
  - Purpose
  - Prerequisites
  - Document Conventions
  - Complete List of BIFs
  - Reserved Words
- Character Set and Source File Encoding
  - Top of chapter
  - Character Set
  - Source File Encoding
- Data Types
  - Top of chapter
  - Terms
  - Number
  - Atom
  - Bit Strings and Binaries
  - Reference
  - Fun
  - Port Identifier
  - Pid
  - Tuple
  - Map
  - List
  - String
  - Record
  - Boolean
  - Escape Sequences
  - Type Conversions
- Pattern Matching
  - Top of chapter
  - Pattern Matching
- Modules
  - Top of chapter
  - Module Syntax
  - Module Attributes
  - Comments
  - module_info/0 and module_info/1 functions
- Functions
  - Top of chapter
  - Function Declaration Syntax
  - Function Evaluation
  - Tail recursion
  - Built-In Functions (BIFs)
- Types and Function Specifications
  - Top of chapter
  - The Erlang Type Language
  - Types and their Syntax
  - Type Declarations of User-Defined Types
  - Type Information in Record Declarations
  - Specifications for Functions
- Expressions
  - Top of chapter
  - Expression Evaluation
  - Terms
  - Variables
  - Patterns
  - Match
  - Function Calls
  - If
  - Case
  - Send
  - Receive
  - Term Comparisons
  - Arithmetic Expressions
  - Boolean Expressions
  - Short-Circuit Expressions
  - List Operations
  - Map Expressions
  - Bit Syntax Expressions
  - Fun Expressions
  - Catch and Throw
  - Try
  - Parenthesized Expressions
  - Block Expressions
  - List Comprehensions
  - Bit String Comprehensions
  - Guard Sequences
  - Operator Precedence
- Preprocessor
  - Top of chapter
  - File Inclusion
  - Defining and Using Macros
  - Predefined Macros
  - Macros Overloading
  - Flow Control in Macros
  - -error() and -warning() directives
  - Stringifying Macro Arguments
- Records
  - Top of chapter
  - Defining Records
  - Creating Records
  - Accessing Record Fields
  - Updating Records
  - Records in Guards
  - Records in Patterns
  - Nested Records
  - Internal Representation of Records
- Errors and Error Handling
  - Top of chapter
  - Terminology
  - Exceptions
  - Handling of Run-time Errors in Erlang
  - Exit Reasons
- Processes
  - Top of chapter
  - Processes
  - Process Creation
  - Registered Processes
  - Process Termination
  - Message Sending
  - Links
  - Error Handling
  - Monitors
  - Process Dictionary
- Distributed Erlang
  - Top of chapter
  - Distributed Erlang System
  - Nodes
  - Node Connections
  - epmd
  - Hidden Nodes
  - C Nodes
  - Security
  - Distribution BIFs
  - Distribution Command-Line Flags
  - Distribution Modules
- Compilation and Code Loading
  - Top of chapter
  - Compilation
  - Code Loading
  - Code Replacement
  - Running a Function When a Module is Loaded
- Ports and Port Drivers
  - Top of chapter
  - Ports
  - Port Drivers
  - Port BIFs

# 12 Processes

### 12.1 Processes

Erlang is designed for massive concurrency. Erlang processes are lightweight (grow and shrink dynamically) with small memory footprint, fast to create and terminate, and the scheduling overhead is low.

### 12.2 Process Creation

A process is created by calling spawn:

    spawn(Module, Name, Args) -> pid()
      Module = Name = atom()
      Args = [Arg1,...,ArgN]
        ArgI = term()

spawn creates a new process and returns the pid.

The new process starts executing in Module:Name(Arg1,...,ArgN) where the arguments are the elements of the (possible empty) Args argument list.

There exist a number of other spawn BIFs, for example, spawn/4 for spawning a process at another node.

### 12.3 Registered Processes

Besides addressing a process by using its pid, there are also BIFs for registering a process under a name. The name must be an atom and is automatically unregistered if the process terminates:

BIF | Description
register(Name, Pid) | Associates the name Name, an atom, with the process Pid.
registered() | Returns a list of names that have been registered using register/2.
whereis(Name) | Returns the pid registered under Name, or undefined if the name is not registered.

Table 12.1: Name Registration BIFs

### 12.4 Process Termination

When a process terminates, it always terminates with an exit reason. The reason can be any term.

A process is said to terminate normally, if the exit reason is the atom normal. A process with no more code to execute terminates normally.

A process terminates with an exit reason {Reason,Stack} when a run-time error occurs. See Exit Reasons.

A process can terminate itself by calling one of the following BIFs:

- exit(Reason)
- erlang:error(Reason)
- erlang:error(Reason, Args)

The process then terminates with reason Reason for exit/1 or {Reason,Stack} for the others.

A process can also be terminated if it receives an exit signal with another exit reason than normal, see Error Handling.

### 12.5 Message Sending

Processes communicate by sending and receiving messages. Messages are sent by using the send operator ! and received by calling receive.

Message sending is asynchronous and safe, the message is guaranteed to eventually reach the recipient, provided that the recipient exists.

### 12.6 Links

Two processes can be linked to each other. A link between two processes Pid1 and Pid2 is created by Pid1 calling the BIF link(Pid2) (or conversely). There also exist a number of spawn_link BIFs, which spawn and link to a process in one operation.

Links are bidirectional and there can only be one link between two processes. Repeated calls to link(Pid) have no effect.

A link can be removed by calling the BIF unlink(Pid).

Links are used to monitor the behaviour of other processes, see Error Handling.

### 12.7 Error Handling

Erlang has a built-in feature for error handling between processes. Terminating processes emit exit signals to all linked processes, which can terminate as well or handle the exit in some way. This feature can be used to build hierarchical program structures where some processes are supervising other processes, for example, restarting them if they terminate abnormally.

See OTP Design Principles for more information about OTP supervision trees, which use this feature.

#### Emitting Exit Signals

When a process terminates, it terminates with an exit reason as explained in Process Termination. This exit reason is emitted in an exit signal to all linked processes.

A process can also call the function exit(Pid,Reason). This results in an exit signal with exit reason Reason being emitted to Pid, but does not affect the calling process.

#### Receiving Exit Signals

The default behaviour when a process receives an exit signal with an exit reason other than normal, is to terminate and in turn emit exit signals with the same exit reason to its linked processes. An exit signal with reason normal is ignored.

A process can be set to trap exit signals by calling:

    process_flag(trap_exit, true)

When a process is trapping exits, it does not terminate when an exit signal is received. Instead, the signal is transformed into a message {'EXIT',FromPid,Reason}, which is put into the mailbox of the process, just like a regular message.

An exception to the above is if the exit reason is kill, that is if exit(Pid,kill) has been called. This unconditionally terminates the process, regardless of if it is trapping exit signals.

### 12.8 Monitors

An alternative to links are monitors. A process Pid1 can create a monitor for Pid2 by calling the BIF erlang:monitor(process, Pid2). The function returns a reference Ref.

If Pid2 terminates with exit reason Reason, a 'DOWN' message is sent to Pid1:

    {'DOWN', Ref, process, Pid2, Reason}

If Pid2 does not exist, the 'DOWN' message is sent immediately with Reason set to noproc.

Monitors are unidirectional. Repeated calls to erlang:monitor(process, Pid) creates several independent monitors, and each one sends a 'DOWN' message when Pid terminates.

A monitor can be removed by calling erlang:demonitor(Ref).

Monitors can be created for processes with registered names, also at other nodes.

### 12.9 Process Dictionary

Each process has its own process dictionary, accessed by calling the following BIFs:

    put(Key, Value)
    get(Key)
    get()
    get_keys(Value)
    erase(Key)
    erase()