From 3d70cee4034e4da37d125679345aa2a10c58cb34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Gustavsson?= Date: Tue, 14 Apr 2015 23:21:36 +0200 Subject: Update Kernel documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Language cleaned up by technical writers from Combitech. Proofreading and corrections by Björn Gustavsson and Hans Bolinder. --- lib/kernel/doc/src/app.xml | 168 +-- lib/kernel/doc/src/application.xml | 457 ++++---- lib/kernel/doc/src/auth.xml | 56 +- lib/kernel/doc/src/code.xml | 573 ++++----- lib/kernel/doc/src/config.xml | 89 +- lib/kernel/doc/src/disk_log.xml | 989 ++++++++-------- lib/kernel/doc/src/erl_boot_server.xml | 67 +- lib/kernel/doc/src/erl_ddll.xml | 1342 ++++++++++++---------- lib/kernel/doc/src/erl_prim_loader_stub.xml | 2 +- lib/kernel/doc/src/erlang_stub.xml | 2 +- lib/kernel/doc/src/error_handler.xml | 78 +- lib/kernel/doc/src/error_logger.xml | 381 +++--- lib/kernel/doc/src/file.xml | 1493 +++++++++++++----------- lib/kernel/doc/src/gen_sctp.xml | 1468 ++++++++++++------------ lib/kernel/doc/src/gen_tcp.xml | 487 ++++---- lib/kernel/doc/src/gen_udp.xml | 223 ++-- lib/kernel/doc/src/global.xml | 296 +++-- lib/kernel/doc/src/global_group.xml | 175 +-- lib/kernel/doc/src/heart.xml | 166 ++- lib/kernel/doc/src/inet.xml | 1659 +++++++++++++-------------- lib/kernel/doc/src/inet_res.xml | 300 +++-- lib/kernel/doc/src/init_stub.xml | 14 +- lib/kernel/doc/src/kernel_app.xml | 342 +++--- lib/kernel/doc/src/net_adm.xml | 85 +- lib/kernel/doc/src/net_kernel.xml | 277 ++--- lib/kernel/doc/src/os.xml | 234 ++-- lib/kernel/doc/src/pg2.xml | 123 +- lib/kernel/doc/src/ref_man.xml | 6 +- lib/kernel/doc/src/rpc.xml | 441 ++++--- lib/kernel/doc/src/seq_trace.xml | 219 ++-- lib/kernel/doc/src/user.xml | 6 +- lib/kernel/doc/src/wrap_log_reader.xml | 154 +-- lib/kernel/doc/src/zlib_stub.xml | 14 +- 33 files changed, 6364 insertions(+), 6022 deletions(-) (limited to 'lib/kernel/doc') diff --git a/lib/kernel/doc/src/app.xml b/lib/kernel/doc/src/app.xml index 35feec144e..3740f1cff9 100644 --- a/lib/kernel/doc/src/app.xml +++ b/lib/kernel/doc/src/app.xml @@ -42,12 +42,12 @@
- FILE SYNTAX -

The application resource file should be called - Application.app where Application is the name of - the application. The file should be located in the ebin - directory for the application.

-

It must contain one single Erlang term, which is called an + File Syntax +

The application resource file is to be called + Application.app, where Application is the + application name. The file is to be located in directory ebin + for the application.

+

The file must contain a single Erlang term, which is called an application specification:

{application, Application, @@ -80,19 +80,26 @@ Env [{Par,Val}] [] Start {Module,StartArgs} [] Phases [{Phase,PhaseArgs}] undefined RTDeps [ApplicationVersion] [] - Module = Name = App = Par = Phase = atom() - Val = StartArgs = PhaseArgs = term() - ApplicationVersion = string() -

Application is the name of the application.

+ +Module = Name = App = Par = Phase = atom() +Val = StartArgs = PhaseArgs = term() +ApplicationVersion = string() + + Application + Application name. +

For the application controller, all keys are optional. The respective default values are used for any omitted keys.

The functions in systools require more information. If - they are used, the following keys are mandatory: - description, vsn, modules, registered - and applications. The other keys are ignored by - systools.

-

The RTDeps type was introduced in OTP 17.0 and - might be subject to changes during the OTP 17 release.

+ they are used, the following keys are mandatory:

+ + description + vsn + modules + registered + applications + +

The other keys are ignored by systools.

description @@ -104,7 +111,7 @@ RTDeps [ApplicationVersion] [] vsn -

The version of the application.

+

Version of the application.

modules @@ -114,15 +121,14 @@ RTDeps [ApplicationVersion] [] maxP -

Deprecated - will be ignored

- - The maximum number of processes allowed in the application.

+

Deprecated - is ignored

+

Maximum number of processes allowed in the application.

maxT -

The maximum time in milliseconds that the application is - allowed to run. After the specified time the application will - automatically terminate.

+

Maximum time, in milliseconds, that the application is + allowed to run. After the specified time, the application + terminates automatically.

registered @@ -132,20 +138,20 @@ RTDeps [ApplicationVersion] [] included_applications -

All applications which are included by this application. - When this application is started, all included application - will automatically be loaded, but not started, by - the application controller. It is assumed that the topmost +

All applications included by this application. + When this application is started, all included applications + are loaded automatically, but not started, by + the application controller. It is assumed that the top-most supervisor of the included application is started by a supervisor of this application.

applications -

All applications which must be started before this +

All applications that must be started before this application is allowed to be started. systools uses this list to generate correct start scripts. Defaults to - the empty list, but note that all applications have - dependencies to (at least) kernel and stdlib.

+ the empty list, but notice that all applications have + dependencies to (at least) Kernel and STDLIB.

env @@ -153,78 +159,84 @@ RTDeps [ApplicationVersion] [] of a configuration parameter is retrieved by calling application:get_env/1,2. The values in the application resource file can be overridden by values in a configuration - file (see config(4)) or by command line flags (see - erl(1)).

+ file (see config(4)) + or by command-line flags (see + erts:erl(1)).

mod -

Specifies the application callback module and a start - argument, see application(3).

-

The mod key is necessary for an application - implemented as a supervision tree, or the application - controller will not know how to start it. The mod key +

Specifies the application callback module and a start argument, see + application(3).

+

Key mod is necessary for an application + implemented as a supervision tree, otherwise the application + controller does not know how to start it. mod can be omitted for applications without processes, typically - code libraries such as the application STDLIB.

+ code libraries, for example, STDLIB.

start_phases

A list of start phases and corresponding start arguments for the application. If this key is present, the application - master will - in addition to the usual call to - Module:start/2 - also call + master, in addition to the usual call to + Module:start/2, also calls Module:start_phase(Phase,Type,PhaseArgs) for each - start phase defined by the start_phases key, and only - after this extended start procedure will - application:start(Application) return.

-

Start phases may be used to synchronize startup of an + start phase defined by key start_phases. Only + after this extended start procedure, + application:start(Application) returns.

+

Start phases can be used to synchronize startup of an application and its included applications. In this case, - the mod key must be specified as:

+ key mod must be specified as follows:

{mod, {application_starter,[Module,StartArgs]}} -

The application master will then call Module:start/2 +

The application master then calls Module:start/2 for the primary application, followed by calls to Module:start_phase/3 for each start phase (as defined - for the primary application) both for the primary application - and for each of its included application, for which the start + for the primary application), both for the primary application + and for each of its included applications, for which the start phase is defined.

This implies that for an included application, the set of start phases must be a subset of the set of phases defined - for the primary application. Refer to OTP Design Principles for more information.

+ for the primary application. For more information, see + OTP Design Principles. +

- runtime_dependencies -

A list of application versions that the application - depends on. An example of such an application version is - "kernel-3.0". Application versions specified as runtime - dependencies are minimum requirements. That is, a larger - application version than the one specified in the - dependency satisfies the requirement. For information on - how to compare application versions see - the - documentation of versions in the system principles - guide. Note that the application version - specifies a source code version. An additional indirect - requirement is that installed binary application of - the specified version has been built so that it is - compatible with the rest of the system.

-

Some dependencies might only be required in specific runtime - scenarios. In the case such optional dependencies exist, these are - specified and documented in the corresponding "App" documentation - of the specific application.

-

The runtime_dependencies key was introduced in - OTP 17.0. The type of its value might be subject to changes during - the OTP 17 release.

-

All runtime dependencies specified in OTP applications - during the OTP 17 release may not be completely correct. This - is actively being worked on. Declared runtime dependencies in OTP - applications are expected to be correct in OTP 18.

+ + + runtime_dependencies + +

A list of application versions that the application + depends on. An example of such an application version is + "kernel-3.0". Application versions specified as runtime + dependencies are minimum requirements. That is, a larger + application version than the one specified in the + dependency satisfies the requirement. For information about + how to compare application versions, see section + Versions + in the System Principles User's Guide.

+

Notice that the application version + specifies a source code version. One more, indirect, + requirement is that the installed binary application of + the specified version is built so that it is + compatible with the rest of the system.

+

Some dependencies can only be required in specific runtime + scenarios. When such optional dependencies exist, these are + specified and documented in the corresponding "App" documentation + of the specific application.

+

The runtime_dependencies key was introduced in + OTP 17.0. The type of its value might be subject to changes during + the OTP 17 release.

+

All runtime dependencies specified in OTP applications + during the OTP 17 release may not be completely correct. This + is actively being worked on. Declared runtime dependencies in OTP + applications are expected to be correct in OTP 18.

- SEE ALSO -

application(3), - systools(3)

+ See Also +

application(3), + sasl:systools(3)

diff --git a/lib/kernel/doc/src/application.xml b/lib/kernel/doc/src/application.xml index 4d8e6ce94b..16de17c901 100644 --- a/lib/kernel/doc/src/application.xml +++ b/lib/kernel/doc/src/application.xml @@ -33,23 +33,25 @@

In OTP, application denotes a component implementing some specific functionality, that can be started and stopped as a - unit, and which can be re-used in other systems as well. This - module interfaces the application controller, a process - started at every Erlang runtime system, and contains functions - for controlling applications (for example starting and stopping + unit, and that can be reused in other systems. This + module interacts with application controller, a process + started at every Erlang runtime system. This module contains functions + for controlling applications (for example, starting and stopping applications), and functions to access information about - applications (for example configuration parameters).

-

An application is defined by an application specification. The specification is normally located in an - application resource file called Application.app, - where Application is the name of the application. Refer to - app(4) for more information about - the application specification.

+ applications (for example, configuration parameters).

+

An application is defined by an application specification. + The specification is normally located in an + application resource file named Application.app, + where Application is the application name. For details + about the application specification, see + app(4).

This module can also be viewed as a behaviour for an application implemented according to the OTP design principles as a supervision tree. The definition of how to start and stop - the tree should be located in an application callback module exporting a pre-defined set of functions.

-

Refer to OTP Design Principles for more information about - applications and behaviours.

+ the tree is to be located in an application callback module, + exporting a predefined set of functions.

+

For details about applications and behaviours, see + OTP Design Principles.

@@ -59,17 +61,44 @@ - tuple_of(T)

A tuple where the elements are of type T.

+ + + + Load and start an application and its dependencies, recursively. + +

Equivalent to calling + start/1,2 + repeatedly on all dependencies that are not yet started for an application.

+

Returns {ok, AppNames} for a successful start or for an already started + application (which is, however, omitted from the AppNames list).

+

The function reports {error, {AppName,Reason}} for errors, where + Reason is any possible reason returned by + start/1,2 + when starting a specific dependency.

+

If an error occurs, the applications started by the function are stopped + to bring the set of running applications back to its initial state.

+
+
+ + + + Load and start an application. + +

Equivalent to + start/1,2 + except it returns ok for already started applications.

+
+
- Get the configuration parameters for an application + Get the configuration parameters for an application.

Returns the configuration parameters and their values for Application. If the argument is omitted, it defaults to @@ -82,7 +111,7 @@ - Get the application specification keys + Get the application specification keys.

Returns the application specification keys and their values for Application. If the argument is omitted, it @@ -96,7 +125,7 @@ - Get the name of an application containing a certain process or module + Get the name of an application containing a certain process or module.

Returns the name of the application to which the process Pid or the module Module belongs. Providing no @@ -110,222 +139,212 @@ - Get the value of a configuration parameter + Get the value of a configuration parameter. -

Returns the value of the configuration parameter Par +

Returns the value of configuration parameter Par for Application. If the application argument is omitted, it defaults to the application of the calling process.

-

If the specified application is not loaded, or - the configuration parameter does not exist, or if the process - executing the call does not belong to any application, - the function returns undefined.

+

Returns undefined if any of the following applies:

+ + The specified application is not loaded. + The configuration parameter does not exist. + The process executing the call does not belong to any application. +
- Get the value of a configuration parameter using a default + Get the value of a configuration parameter using a default. -

Works like get_env/2 but returns - Def value when configuration parameter +

Works like get_env/2 but returns + value Def when configuration parameter Par does not exist.

- Get the value of an application specification key + Get the value of an application specification key.

Returns the value of the application specification key Key for Application. If the application argument is omitted, it defaults to the application of the calling process.

-

If the specified application is not loaded, or - the specification key does not exist, or if the process - executing the call does not belong to any application, - the function returns undefined.

+

Returns undefined if any of the following applies:

+ + The specified application is not loaded. + The specification key does not exist. + The process executing the call does not belong to any application. + +
- Load an application + Load an application.

Loads the application specification for an application into - the application controller. It will also load the application - specifications for any included applications. Note that - the function does not load the actual Erlang object code.

-

The application can be given by its name Application. - In this case the application controller will search the code + the application controller. It also loads the application + specifications for any included applications. Notice that + the function does not load the Erlang object code.

+

The application can be specified by its name Application. + In this case, the application controller searches the code path for the application resource file Application.app - and load the specification it contains.

-

The application specification can also be given directly as a - tuple AppSpec. This tuple should have the format and - contents as described in app(4).

+ and loads the specification it contains.

+

The application specification can also be specified directly as a + tuple AppSpec, having the format and + contents as described in + app(4).

If Distributed == {Application,[Time,]Nodes}, - the application will be distributed. The argument overrides - the value for the application in the Kernel configuration + the application becomes distributed. The argument overrides + the value for the application in the Kernel configuration parameter distributed. Application must be - the name of the application (same as in the first argument). - If a node crashes and Time has been specified, then - the application controller will wait for Time + the application name (same as in the first argument). + If a node crashes and Time is specified, + the application controller waits for Time milliseconds before attempting to restart the application on - another node. If Time is not specified, it will - default to 0 and the application will be restarted + another node. If Time is not specified, it + defaults to 0 and the application is restarted immediately.

Nodes is a list of node names where the application - may run, in priority from left to right. Node names can be + can run, in priority from left to right. Node names can be grouped using tuples to indicate that they have the same - priority. Example:

+ priority.

+

Example:

Nodes = [cp1@cave, {cp2@cave, cp3@cave}] -

This means that the application should preferably be started +

This means that the application is preferably to be started at cp1@cave. If cp1@cave is down, - the application should be started at either cp2@cave + the application is to be started at cp2@cave or cp3@cave.

If Distributed == default, the value for - the application in the Kernel configuration parameter - distributed will be used.

+ the application in the Kernel configuration parameter + distributed is used.

- Get the currently loaded applications + Get the currently loaded applications. -

Returns a list with information about the applications which - have been loaded using load/1,2, also included - applications. Application is the application name. - Description and Vsn are the values of its - description and vsn application specification +

Returns a list with information about the applications, and included + applications, which are loaded using load/1,2. + Application is the application name. + Description and Vsn are the values + of their description and vsn application specification keys, respectively.

- Change an application's permission to run on a node. + Change the permission for an application to run at a node.

Changes the permission for Application to run at - the current node. The application must have been loaded using + the current node. The application must be loaded using load/1,2 for the function to have effect.

If the permission of a loaded, but not started, application - is set to false, start will return ok but - the application will not be started until the permission is + is set to false, start returns ok but + the application is not started until the permission is set to true.

If the permission of a running application is set to - false, the application will be stopped. If - the permission later is set to true, it will be + false, the application is stopped. If + the permission later is set to true, it is restarted.

If the application is distributed, setting the permission to false means that the application will be started at, or moved to, another node according to how its distribution is - configured (see load/2 above).

+ configured + (see load/2).

The function does not return until the application is - started, stopped or successfully moved to another node. - However, in some cases where permission is set to true - the function may return ok even though the application - itself has not started. This is true when an application - cannot start because it has dependencies to other - applications which have not yet been started. When they have - been started, Application will be started as well.

+ started, stopped, or successfully moved to another node. + However, in some cases where permission is set to true, + the function returns ok even though the application + is not started. This is true when an application + cannot start because of dependencies to other + applications that are not yet started. When they are + started, Application is started as well.

By default, all applications are loaded with permission - true on all nodes. The permission is configurable by - using the Kernel configuration parameter permissions.

+ true on all nodes. The permission can be configured + using the Kernel configuration parameter permissions.

- Set the value of a configuration parameter + Set the value of a configuration parameter. -

Sets the value of the configuration parameter Par for +

Sets the value of configuration parameter Par for Application.

-

set_env/4 uses the standard gen_server timeout - value (5000 ms). The timeout option can be provided - if another timeout value is useful, for example, in situations +

set_env/4 uses the standard gen_server time-out + value (5000 ms). Option timeout can be specified + if another time-out value is useful, for example, in situations where the application controller is heavily loaded.

If set_env/4 is called before the application is loaded, - the application environment values specified in the Application.app - file will override the ones previously set. This is also true for application + the application environment values specified in file Application.app + override the ones previously set. This is also true for application reloads.

-

The persistent option can be set to true - when there is a need to guarantee parameters set with set_env/4 - will not be overridden by the ones defined in the application resource - file on load. This means persistent values will stick after the application +

Option persistent can be set to true + to guarantee that parameters set with set_env/4 + are not overridden by those defined in the application resource + file on load. This means that persistent values will stick after the application is loaded and also on application reload.

-

Use this function only if you know what you are doing, - that is, on your own applications. It is very application - and configuration parameter dependent when and how often - the value is read by the application, and careless use - of this function may put the application in a - weird, inconsistent, and malfunctioning state.

+

Use this function only if you know what you are doing, + that is, on your own applications. It is very + application-dependent and + configuration parameter-dependent when and how often + the value is read by the application. Careless use + of this function can put the application in a + weird, inconsistent, and malfunctioning state.

- - - - Load and start an application - -

Equivalent to application:start/1,2 except - it returns ok for already started applications.

-
-
- - - - Load and start an application and its dependencies, recursively - -

Equivalent to calling application:start/1,2 - repeatedly on all dependencies that have not yet been started for an application. - The function returns {ok, AppNames} for a successful start or for an already started - application (which are however omitted from the AppNames list), and reports - {error, {AppName,Reason}} for errors, where Reason is any possible reason - returned by application:start/1,2 when starting a - specific dependency. In case of an error, the applications that were started by the - function are stopped to bring the set of running applications back to its initial state.

-
-
- Load and start an application - + Load and start an application. +

Starts Application. If it is not loaded, - the application controller will first load it using - load/1. It will make sure any included applications - are loaded, but will not start them. That is assumed to be + the application controller first loads it using + load/1. It ensures that any included applications + are loaded, but does not start them. That is assumed to be taken care of in the code for Application.

The application controller checks the value of the application specification key applications, to - ensure that all applications that should be started before - this application are running. If not, + ensure that all applications needed to be started before + this application are running. Otherwise, {error,{not_started,App}} is returned, where App is the name of the missing application.

-

The application controller then creates an application master for the application. The application master is +

The application controller then creates an application master + for the application. The application master is the group leader of all the processes in the application. The application master starts the application by calling the application callback function Module:start/2 as defined by the application specification key mod.

-

The Type argument specifies the type of +

Argument Type specifies the type of the application. If omitted, it defaults to temporary.

If a permanent application terminates, all other applications and the entire Erlang node are also terminated. - If a transient application terminates with Reason == normal, this is reported but no other applications are - terminated. If a transient application terminates - abnormally, all other applications and the entire Erlang - node are also terminated. + + + If a transient application terminates with Reason == normal, + this is reported but no other applications are terminated. + If a transient application terminates abnormally, all other + applications and the entire Erlang node are also terminated. + + If a temporary application terminates, this is reported but no other applications are terminated. -

Note that it is always possible to stop an application +

Notice that an application can always be stopped explicitly by calling stop/1. Regardless of the type of - the application, no other applications will be affected.

-

Note also that the transient type is of little practical use, - since when a supervision tree terminates, the reason is set to + the application, no other applications are affected.

+

Notice also that the transient type is of little practical use, + because when a supervision tree terminates, the reason is set to shutdown, not normal.

@@ -334,13 +353,13 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}] Get the start type of an ongoing application startup.

This function is intended to be called by a process belonging - to an application, when the application is being started, to - determine the start type which is either StartType or + to an application, when the application is started, to + determine the start type, which is StartType or local.

-

See Module:start/2 for a description of - StartType.

-

local is returned if only parts of the application is - being restarted (by a supervisor), or if the function is +

For a description of StartType, see + Module:start/2.

+

local is returned if only parts of the application are + restarted (by a supervisor), or if the function is called outside a startup.

If the process executing the call does not belong to any application, the function returns undefined.

@@ -348,103 +367,106 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}] - Stop an application + Stop an application.

Stops Application. The application master calls Module:prep_stop/1, if such a function is defined, and - then tells the top supervisor of the application to shutdown - (see supervisor(3)). This means that the entire + then tells the top supervisor of the application to shut down + (see supervisor(3)). + This means that the entire supervision tree, including included applications, is terminated in reversed start order. After the shutdown, the application master calls Module:stop/1. Module is the callback module as defined by the application specification key mod.

-

Last, the application master itself terminates. Note that all - processes with the application master as group leader, i.e. +

Last, the application master terminates. Notice that all + processes with the application master as group leader, that is, processes spawned from a process belonging to the application, - thus are terminated as well.

+ are also terminated.

When stopped, the application is still loaded.

-

In order to stop a distributed application, stop/1 - has to be called on all nodes where it can execute (that is, +

To stop a distributed application, stop/1 + must be called on all nodes where it can execute (that is, on all nodes where it has been started). The call to stop/1 on the node where the application currently - executes will stop its execution. The application will not be - moved between nodes due to stop/1 being called on + executes stops its execution. The application is not + moved between nodes, as stop/1 is called on the node where the application currently executes before stop/1 is called on the other nodes.

- Take over a distributed application + Take over a distributed application. -

Performs a takeover of the distributed application +

Takes over the distributed application Application, which executes at another node Node. At the current node, the application is restarted by calling Module:start({takeover,Node},StartArgs). Module and StartArgs are retrieved from the loaded application specification. The application at the other node is not - stopped until the startup is completed, i.e. when + stopped until the startup is completed, that is, when Module:start/2 and any calls to Module:start_phase/3 have returned.

-

Thus two instances of the application will run simultaneously - during the takeover, which makes it possible to transfer data - from the old to the new instance. If this is not acceptable - behavior, parts of the old instance may be shut down when - the new instance is started. Note that the application may - not be stopped entirely however, at least the top supervisor +

Thus, two instances of the application run simultaneously + during the takeover, so that data can be transferred + from the old to the new instance. If this is not an acceptable + behavior, parts of the old instance can be shut down when + the new instance is started. However, the application cannot + be stopped entirely, at least the top supervisor must remain alive.

-

See start/1,2 for a description of Type.

+

For a description of Type, see + start/1,2.

- Unload an application + Unload an application.

Unloads the application specification for Application - from the application controller. It will also unload + from the application controller. It also unloads the application specifications for any included applications. - Note that the function does not purge the actual Erlang + Notice that the function does not purge the Erlang object code.

- Unset the value of a configuration parameter + Unset the value of a configuration parameter.

Removes the configuration parameter Par and its value for Application.

unset_env/2 uses the standard gen_server - timeout value (5000 ms). The timeout option can be - provided if another timeout value is useful, for example, in + time-out value (5000 ms). Option timeout can be + specified if another time-out value is useful, for example, in situations where the application controller is heavily loaded.

unset_env/3 also allows the persistent option to be passed - (see set_env/4 above).

- -

Use this function only if you know what you are doing, - that is, on your own applications. It is very application - and configuration parameter dependent when and how often - the value is read by the application, and careless use - of this function may put the application in a - weird, inconsistent, and malfunctioning state.

+ (see set_env/4).

+ +

Use this function only if you know what you are doing, + that is, on your own applications. It is very + application-dependent and configuration + parameter-dependent when and how often + the value is read by the application. Careless use + of this function can put the application in a + weird, inconsistent, and malfunctioning state.

- Get the currently running applications + Get the currently running applications. -

Returns a list with information about the applications which +

Returns a list with information about the applications that are currently running. Application is the application - name. Description and Vsn are the values of its - description and vsn application specification + name. Description and Vsn are the + values of their description and vsn application specification keys, respectively.

which_applications/0 uses the standard - gen_server timeout value (5000 ms). A Timeout - argument can be provided if another timeout value is useful, + gen_server time-out value (5000 ms). A Timeout + argument can be specified if another time-out value is useful, for example, in situations where the application controller is heavily loaded.

@@ -452,81 +474,81 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]
- CALLBACK MODULE -

The following functions should be exported from an + Callback Module +

The following functions are to be exported from an application callback module.

Module:start(StartType, StartArgs) -> {ok, Pid} | {ok, Pid, State} | {error, Reason} - Start an application + Start an application. - StartType = start_type() + StartType = start_type() StartArgs = term() Pid = pid() State = term()

This function is called whenever an application is started - using application:start/1,2, and should start + using start/1,2, and is to start the processes of the application. If the application is structured according to the OTP design principles as a supervision tree, this means starting the top supervisor of the tree.

StartType defines the type of start:

- normal if it's a normal startup. + normal if it is a normal startup. normal also if the application is distributed and - started at the current node due to a failover from another + started at the current node because of a failover from another node, and the application specification key start_phases == undefined. {takeover,Node} if the application is - distributed and started at the current node due to a + distributed and started at the current node because of a takeover from Node, either because - application:takeover/2 has been called or because + takeover/2 has been called or because the current node has higher priority than Node. {failover,Node} if the application is - distributed and started at the current node due to a + distributed and started at the current node because of a failover from Node, and the application specification key start_phases /= undefined.

StartArgs is the StartArgs argument defined by the application specification key mod.

-

The function should return {ok,Pid} or - {ok,Pid,State} where Pid is the pid of the top +

The function is to return {ok,Pid} or + {ok,Pid,State}, where Pid is the pid of the top supervisor and State is any term. If omitted, - State defaults to []. If later the application - is stopped, State is passed to + State defaults to []. If the application + is stopped later, State is passed to Module:prep_stop/1.

Module:start_phase(Phase, StartType, PhaseArgs) -> ok | {error, Reason} - Extended start of an application + Extended start of an application. Phase = atom() - StartType = start_type() + StartType = start_type() PhaseArgs = term() Pid = pid() State = state() -

This function is used to start an application with included - applications, when there is a need for synchronization between +

Starts an application with included + applications, when synchronization is needed between processes in the different applications during startup.

-

The start phases is defined by the application specification +

The start phases are defined by the application specification key start_phases == [{Phase,PhaseArgs}]. For included applications, the set of phases must be a subset of the set of phases defined for the including application.

The function is called for each start phase (as defined for the primary application) for the primary application and all included applications, for which the start phase is defined.

-

See Module:start/2 for a description of - StartType.

+

For a description of StartType, see + Module:start/2.

Module:prep_stop(State) -> NewState - Prepare an application for termination + Prepare an application for termination. State = NewState = term() @@ -536,28 +558,26 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}] the application.

State is the state returned from Module:start/2, or [] if no state was returned. - NewState is any term and will be passed to + NewState is any term and is passed to Module:stop/1.

The function is optional. If it is not defined, the processes - will be terminated and then Module:stop(State) is - called.

+ are terminated and then Module:stop(State) is called.

Module:stop(State) - Clean up after termination of an application + Clean up after termination of an application. State = term()

This function is called whenever an application has stopped. It is intended to be the opposite of Module:start/2 - and should do any necessary cleaning up. The return value is + and is to do any necessary cleaning up. The return value is ignored.

-

State is the return value of - Module:prep_stop/1, if such a function exists. - Otherwise State is taken from the return value of - Module:start/2.

+

State is the return value of Module:prep_stop/1, + if such a function exists. Otherwise State is taken from + the return value of Module:start/2.

@@ -572,19 +592,18 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]

This function is called by an application after a code - replacement, if there are any changes to the configuration - parameters.

-

Changed is a list of parameter-value tuples with all - configuration parameters with changed values, New is - a list of parameter-value tuples with all configuration - parameters that have been added, and Removed is a list - of all parameters that have been removed.

+ replacement, if the configuration parameters have changed.

+

Changed is a list of parameter-value tuples including all + configuration parameters with changed values.

+

New is a list of parameter-value tuples including all + added configuration parameters.

+

Removed is a list of all removed parameters.

- SEE ALSO + See Also

OTP Design Principles, kernel(6), app(4)

diff --git a/lib/kernel/doc/src/auth.xml b/lib/kernel/doc/src/auth.xml index 71b1863e96..dcd784dcfd 100644 --- a/lib/kernel/doc/src/auth.xml +++ b/lib/kernel/doc/src/auth.xml @@ -29,7 +29,7 @@ auth - Erlang Network Authentication Server + Erlang network authentication server.

This module is deprecated. For a description of the Magic Cookie system, refer to @@ -41,61 +41,61 @@ - - - Status of communication authorization (deprecated) - -

Returns yes if communication with Node is - authorized. Note that a connection to Node will - be established in this case. Returns no if Node - does not exist or communication is not authorized (it has - another cookie than auth thinks it has).

-

Use net_adm:ping(Node) - instead.

- - - Magic cookie for local node (deprecated) + Magic cookie for local node (deprecated).

Use - erlang:get_cookie() - instead.

+ erlang:get_cookie() + in ERTS instead.

- Set the magic for the local node (deprecated) + Set the magic for the local node (deprecated). - The cookie may also be given as a list with a single atom element. + The cookie can also be specified as a list with a single atom element.

Use - erlang:set_cookie(node(), Cookie) + erlang:set_cookie(node(), Cookie) + in ERTS instead.

+
+
+ + + Status of communication authorization (deprecated). + +

Returns yes if communication with Node is + authorized. Notice that a connection to Node + is established in this case. Returns no if Node + does not exist or communication is not authorized (it has + another cookie than auth thinks it has).

+

Use net_adm:ping(Node) instead.

node_cookie([Node, Cookie]) -> yes | no - Set the magic cookie for a node and verify authorization (deprecated) + Set the magic cookie for a node and verify authorization (deprecated). Node = node() - Cookie = cookie() + Cookie = cookie()

Equivalent to - node_cookie(Node, Cookie).

+ node_cookie(Node, Cookie).

- Set the magic cookie for a node and verify authorization (deprecated) + Set the magic cookie for a node and verify authorization (deprecated). -

Sets the magic cookie of Node to Cookie, and - verifies the status of the authorization. +

Sets the magic cookie of Node to + Cookie and verifies the status of the authorization. Equivalent to calling - erlang:set_cookie(Node, Cookie), followed by - auth:is_auth(Node).

+ erlang:set_cookie(Node, Cookie), followed by + auth:is_auth(Node).

diff --git a/lib/kernel/doc/src/code.xml b/lib/kernel/doc/src/code.xml index 819da544c3..575f2f0b51 100644 --- a/lib/kernel/doc/src/code.xml +++ b/lib/kernel/doc/src/code.xml @@ -29,238 +29,240 @@ code - Erlang Code Server + Erlang code server.

This module contains the interface to the Erlang code server, which deals with the loading of compiled code into a running Erlang runtime system.

-

The runtime system can be started in either embedded or - interactive mode. Which one is decided by the command - line flag -mode.

+

The runtime system can be started in embedded or + interactive mode. Which one is decided by command-line + flag -mode:

 % erl -mode interactive
-

Default mode is interactive.

+

The modes are as follows:

-

In embedded mode, all code is loaded during system start-up +

In embedded mode, all code is loaded during system startup according to the boot script. (Code can also be loaded later by explicitly ordering the code server to do so).

-

In interactive mode, only some code is loaded during system - startup-up, basically the modules needed by the runtime - system itself. Other code is dynamically loaded when first +

In interactive mode, which is default, only some code is loaded + during system startup, basically the modules needed by the runtime + system. Other code is dynamically loaded when first referenced. When a call to a function in a certain module is made, and the module is not loaded, the code server searches for and tries to load the module.

-

To prevent accidentally reloading modules affecting the Erlang - runtime system itself, the kernel, stdlib and - compiler directories are considered sticky. This +

To prevent accidentally reloading of modules affecting the Erlang + runtime system, directories kernel, stdlib, + and compiler are considered sticky. This means that the system issues a warning and rejects the request if a user tries to reload a module residing in any of them. - The feature can be disabled by using the command line flag + The feature can be disabled by using command-line flag -nostick.

Code Path -

In interactive mode, the code server maintains a search path -- - usually called the code path -- consisting of a list of +

In interactive mode, the code server maintains a search path, + usually called the code path, consisting of a list of directories, which it searches sequentially when trying to load a module.

Initially, the code path consists of the current working - directory and all Erlang object code directories under the library + directory and all Erlang object code directories under library directory $OTPROOT/lib, where $OTPROOT is the installation directory of Erlang/OTP, code:root_dir(). Directories can be named Name[-Vsn] and the code server, by default, chooses the directory with the highest version number - among those which have the same Name. The -Vsn - suffix is optional. If an ebin directory exists under - Name[-Vsn], it is this directory which is added to - the code path.

-

The environment variable ERL_LIBS (defined in the operating - system) can be used to define additional library directories that - will be handled in the same way as the standard OTP library - directory described above, except that directories that do not - have an ebin directory will be ignored.

+ among those having the same Name. Suffix -Vsn + is optional. If an ebin directory exists under + Name[-Vsn], this directory is added to the code path.

+

Environment variable ERL_LIBS (defined in the operating + system) can be used to define more library directories to + be handled in the same way as the standard OTP library + directory described above, except that directories without + an ebin directory are ignored.

All application directories found in the additional directories - will appear before the standard OTP applications, except for the - Kernel and STDLIB applications, which will be placed before any - additional applications. In other words, modules found in any - of the additional library directories will override modules with - the same name in OTP, except for modules in Kernel and - STDLIB.

-

The environment variable ERL_LIBS (if defined) should contain + appears before the standard OTP applications, except for the + Kernel and STDLIB applications, which are placed before + any additional applications. In other words, modules found in any + of the additional library directories override modules with + the same name in OTP, except for modules in Kernel and + STDLIB.

+

Environment variable ERL_LIBS (if defined) is to contain a colon-separated (for Unix-like systems) or semicolon-separated (for Windows) list of additional libraries.

-

Example: On an Unix-like system, ERL_LIBS could be set to - /usr/local/jungerl:/home/some_user/my_erlang_lib. (On Windows, - use semi-colon as separator.)

+

Example:

+

On a Unix-like system, ERL_LIBS can be set to the following

+ +/usr/local/jungerl:/home/some_user/my_erlang_lib +

On Windows, use semi-colon as separator.

Loading of Code From Archive Files -

The support for loading of code from archive files is - experimental. The sole purpose of releasing it before it is ready +

The support for loading code from archive files is + experimental. The purpose of releasing it before it is ready is to obtain early feedback. The file format, semantics, - interfaces etc. may be changed in a future release. The function - lib_dir/2 and the flag -code_path_choice are also + interfaces, and so on, can be changed in a future release. The function + lib_dir/2 + and flag -code_path_choice are also experimental.

-

In the current implementation, Erlang archives are ZIP - files with .ez extension. Erlang archives may also be +

The Erlang archives are ZIP + files with extension .ez. Erlang archives can also be enclosed in escript files whose file extension is arbitrary.

-

Erlang archive files may contain entire Erlang applications or +

Erlang archive files can contain entire Erlang applications or parts of applications. The structure in an archive file is the - same as the directory structure for an application. If you for - example would create an archive of mnesia-4.4.7, the + same as the directory structure for an application. If you, for + example, create an archive of mnesia-4.4.7, the archive file must be named mnesia-4.4.7.ez and it must - contain a top directory with the name mnesia-4.4.7. If the + contain a top directory named mnesia-4.4.7. If the version part of the name is omitted, it must also be omitted in the archive. That is, a mnesia.ez archive must contain a mnesia top directory.

-

An archive file for an application may for example be +

An archive file for an application can, for example, be created like this:

-   zip:create("mnesia-4.4.7.ez", 
-              ["mnesia-4.4.7"], 
-              [{cwd, code:lib_dir()},
-               {compress, all},
-               {uncompress,[".beam",".app"]}]).
- -

Any file in the archive may be compressed, but in order to - speed up the access of frequently read files, it may be a good +zip:create("mnesia-4.4.7.ez", + ["mnesia-4.4.7"], + [{cwd, code:lib_dir()}, + {compress, all}, + {uncompress,[".beam",".app"]}]). + +

Any file in the archive can be compressed, but to + speed up the access of frequently read files, it can be a good idea to store beam and app files uncompressed in the archive.

-

Normally the top directory of an application is located either - in the library directory $OTPROOT/lib or in a directory - referred to by the environment variable ERL_LIBS. At - startup when the initial code path is computed, the code server - will also look for archive files in these directories and - possibly add ebin directories in archives to the code path. The - code path will then contain paths to directories that looks like +

Normally the top directory of an application is located + in library directory $OTPROOT/lib or in a directory + referred to by environment variable ERL_LIBS. At + startup, when the initial code path is computed, the code server + also looks for archive files in these directories and + possibly adds ebin directories in archives to the code path. The + code path then contains paths to directories that look like $OTPROOT/lib/mnesia.ez/mnesia/ebin or $OTPROOT/lib/mnesia-4.4.7.ez/mnesia-4.4.7/ebin.

-

The code server uses the module erl_prim_loader - (possibly via the erl_boot_server) to read code files from - archives. But the functions in erl_prim_loader may also be +

The code server uses module erl_prim_loader in ERTS + (possibly through erl_boot_server) to read code files from + archives. However, the functions in erl_prim_loader can also be used by other applications to read files from archives. For example, the call erl_prim_loader:list_dir( "/otp/root/lib/mnesia-4.4.7.ez/mnesia-4.4.7/examples/bench)" would list the contents of a directory inside an archive. - See erl_prim_loader(3).

+ See erl_prim_loader(3).

An application archive file and a regular application directory - may coexist. This may be useful when there is a need of having + can coexist. This can be useful when it is needed to have parts of the application as regular files. A typical case is the - priv directory which must reside as a regular directory in - order to be able to dynamically link in drivers and start port - programs. For other applications that do not have this need, the - priv directory may reside in the archive and the files - under the priv directory may be read via the + priv directory, which must reside as a regular directory + to link in drivers dynamically and start port programs. + For other applications that do not need this, directory + priv can reside in the archive and the files + under the directory priv can be read through erl_prim_loader.

-

At the time point when a directory is added to the code path as - well as when the entire code path is (re)set, the code server - will decide which subdirectories in an application that shall be - read from the archive and which that shall be read as regular +

When a directory is added to the code path and + when the entire code path is (re)set, the code server + decides which subdirectories in an application that are to be + read from the archive and which that are to be read as regular files. If directories are added or removed afterwards, the file - access may fail if the code path is not updated (possibly to the - same path as before in order to trigger the directory resolution - update). For each directory on the second level (ebin, priv, src - etc.) in the application archive, the code server will firstly - choose the regular directory if it exists and secondly from the - archive. The function - code:lib_dir/2 returns the path to the subdirectory. For - example code:lib_dir(megaco,ebin) may return + access can fail if the code path is not updated (possibly to the + same path as before, to trigger the directory resolution + update).

+ +

For each directory on the second level in the application archive + (ebin, priv, src, and so on), the code server first + chooses the regular directory if it exists and second from the + archive. Function code:lib_dir/2 returns the path to the + subdirectory. For example, code:lib_dir(megaco,ebin) can return /otp/root/lib/megaco-3.9.1.1.ez/megaco-3.9.1.1/ebin while - code:lib_dir(megaco,priv) may return + code:lib_dir(megaco,priv) can return /otp/root/lib/megaco-3.9.1.1/priv.

When an escript file contains an archive, there are - neither restrictions on the name of the escript nor on how - many applications that may be stored in the embedded - archive. Single beam files may also reside on the top - level in the archive. At startup, both the top directory in the - embedded archive as well as all (second level) ebin + no restrictions on the name of the escript and no restrictions + on how many applications that can be stored in the embedded + archive. Single Beam files can also reside on the top + level in the archive. At startup, the top directory in the + embedded archive and all (second level) ebin directories in the embedded archive are added to the code path. - See escript(1)

+ See erts:escript(1).

When the choice of directories in the code path is - strict, the directory that ends up in the code path will - be exactly the stated one. This means that if for example the + strict, the directory that ends up in the code path is + exactly the stated one. This means that if, for example, the directory $OTPROOT/lib/mnesia-4.4.7/ebin is explicitly - added to the code path, the code server will not load files from - $OTPROOT/lib/mnesia-4.4.7.ez/mnesia-4.4.7/ebin and vice - versa.

+ added to the code path, the code server does not load files from + $OTPROOT/lib/mnesia-4.4.7.ez/mnesia-4.4.7/ebin.

-

This behavior can be controlled via the command line flag +

This behavior can be controlled through command-line flag -code_path_choice Choice. If the flag is set to relaxed, - the code server will instead choose a suitable directory - depending on the actual file structure. If there exists a regular - application ebin directory, it will be chosen. But if it does - not exist, the ebin directory in the archive is chosen if it - exists. If neither of them exists the original directory will be + the code server instead chooses a suitable directory + depending on the actual file structure. If a regular + application ebin directory exists, it is chosen. Otherwise, + the directory ebin in the archive is chosen if it + exists. If neither of them exists, the original directory is chosen.

-

The command line flag -code_path_choice Choice does also - affect how init interprets the boot script. The - interpretation of the explicit code paths in the boot - script may be strict or relaxed. It is - particular useful to set the flag to relaxed when you want - to elaborate with code loading from archives without editing the +

Command-line flag -code_path_choice Choice also + affects how module init interprets the boot script. + The interpretation of the explicit code paths in the boot + script can be strict or relaxed. It is + particularly useful to set the flag to relaxed when + elaborating with code loading from archives without editing the boot script. The default is relaxed. See init(3)

+ marker="erts:init">erts:init(3).

Current and Old Code -

The code of a module can exists in two variants in a system: +

The code for a module can exist in two variants in a system: current code and old code. When a module is - loaded into the system for the first time, the code of the module + loaded into the system for the first time, the module code becomes 'current' and the global export table is updated with references to all functions exported from the module.

-

If then a new instance of the module is loaded (perhaps because - of the correction of an error), then the code of the previous +

If then a new instance of the module is loaded (for example, because of + error correction), the code of the previous instance becomes 'old', and all export entries referring to - the previous instance are removed. After that the new instance is - loaded as if it was loaded for the first time, as described above, - and becomes 'current'.

-

Both old and current code for a module are valid, and may even be + the previous instance are removed. After that, the new instance is + loaded as for the first time, and becomes 'current'.

+

Both old and current code for a module are valid, and can even be evaluated concurrently. The difference is that exported functions - in old code are unavailable. Hence there is no way to make a - global call to an exported function in old code, but old code may + in old code are unavailable. Hence, a global call cannot be made + to an exported function in old code, but old code can still be evaluated because of processes lingering in it.

-

If a third instance of the module is loaded, the code server will - remove (purge) the old code and any processes lingering in it will - be terminated. Then the third instance becomes 'current' and +

If a third instance of the module is loaded, the code server + removes (purges) the old code and any processes lingering in it + are terminated. Then the third instance becomes 'current' and the previously current code becomes 'old'.

For more information about old and current code, and how to - make a process switch from old to current code, refer to + make a process switch from old to current code, see section + Compilation and Code Loading in the Erlang Reference Manual.

Argument Types and Invalid Arguments -

Generally, module and application names are atoms, while file and directory +

Module and application names are atoms, while file and directory names are strings. For backward compatibility reasons, some functions accept both strings and atoms, but a future release will probably only allow the arguments that are documented.

-

From the R12B release, functions in this module will generally fail with an - exception if they are passed an incorrect type (for instance, an integer or a tuple - where an atom was expected). An error tuple will be returned if the type of the argument - was correct, but there was some other error (for instance, a non-existing directory - was given to set_path/1).

+

As from Erlang/OTP R12B, functions in this module generally fail with an + exception if they are passed an incorrect type (for example, an integer or a tuple + where an atom is expected). An error tuple is returned if the argument type + is correct, but there are some other errors (for example, a non-existing directory + is specified to set_path/1).

@@ -312,33 +314,38 @@ - An opaque term holding prepared code. +

An opaque term holding prepared code.

- Set the code server search path + Set the code server search path.

Sets the code path to the list of directories Path.

-

Returns true if successful, or - {error, bad_directory} if any Dir is not - the name of a directory, or {error, bad_path} if - the argument is invalid.

+

Returns:

+ + true +

If successful

+ {error, bad_directory} +

If any Dir is not a directory name

+ {error, bad_path} +

If the argument is invalid

+
- Return the code server search path + Return the code server search path. -

Returns the code path

+

Returns the code path.

- Add a directory to the end of the code path + Add a directory to the end of the code path.

Adds Dir to the code path. The directory is added as @@ -351,11 +358,11 @@ - Add a directory to the beginning of the code path + Add a directory to the beginning of the code path.

Adds Dir to the beginning of the code path. If - Dir already exists, it is removed from the old + Dir exists, it is removed from the old position in the code path.

Returns true if successful, or {error, bad_directory} if Dir is not the name @@ -365,69 +372,81 @@ - Add directories to the end of the code path + Add directories to the end of the code path.

Adds the directories in Dirs to the end of the code - path. If a Dir already exists, it is not added. This - function always returns ok, regardless of the validity + path. If a Dir exists, it is not added.

+

Always returns ok, regardless of the validity of each individual Dir.

- Add directories to the beginning of the code path + Add directories to the beginning of the code path.

Adds the directories in Dirs to the beginning of - the code path. If a Dir already exists, it is removed - from the old position in the code path. This function always - returns ok, regardless of the validity of each + the code path. If a Dir exists, it is removed + from the old position in the code path.

+

Always returns ok, regardless of the validity of each individual Dir.

- Delete a directory from the code path + Delete a directory from the code path.

Deletes a directory from the code path. The argument can be an atom Name, in which case the directory with the name .../Name[-Vsn][/ebin] is deleted from the code - path. It is also possible to give the complete directory name - Dir as argument.

-

Returns true if successful, or false if - the directory is not found, or {error, bad_name} if - the argument is invalid.

+ path. Also, the complete directory name Dir can be + specified as argument.

+

Returns:

+ + true +

If successful

+ false +

If the directory is not found

+ {error, bad_name} +

If the argument is invalid

+
- Replace a directory with another in the code path - -

This function replaces an old occurrence of a directory - named .../Name[-Vsn][/ebin], in the code path, with - Dir. If Name does not exist, it adds the new - directory Dir last in the code path. The new directory - must also be named .../Name[-Vsn][/ebin]. This function - should be used if a new version of the directory (library) is + Replace a directory with another in the code path. + +

Replaces an old occurrence of a directory + named .../Name[-Vsn][/ebin] in the code path, with + Dir. If Name does not exist, it adds + the new directory Dir last in the code path. The new + directory must also be named .../Name[-Vsn][/ebin]. + This function is to be used if a new version of the directory (library) is added to a running system.

-

Returns true if successful, or - {error, bad_name} if Name is not found, or - {error, bad_directory} if Dir does not exist, or - {error, {badarg, [Name, Dir]}} if Name or - Dir is invalid.

+

Returns:

+ + true +

If successful

+ {error, bad_name} +

If Name is not found

+ {error, bad_directory} +

If Dir does not exist

+ {error, {badarg, [Name, Dir]}} +

If Name or Dir is invalid

+
- Load a module + Load a module.

Tries to load the Erlang module Module, using the code path. It looks for the object code file with an - extension that corresponds to the Erlang machine used, for - example Module.beam. The loading fails if the module + extension corresponding to the Erlang machine used, for + example, Module.beam. The loading fails if the module name found in the object code differs from the name Module. - load_binary/3 must + load_binary/3 must be used to load object code with a module name that is different from the file name.

Returns {module, Module} if successful, or @@ -437,45 +456,45 @@ - Load a module, residing in a given file + Load a module, residing in a specified file. -

Does the same as load_file(Module), but - Filename is either an absolute file name, or a - relative file name. The code path is not searched. It returns +

Same as load_file(Module), but + Filename is an absolute or + relative filename. The code path is not searched. It returns a value in the same way as - load_file/1. Note - that Filename should not contain the extension (for - example ".beam"); load_abs/1 adds the correct - extension itself.

+ load_file/1. Notice + that Filename must not contain the extension (for + example, .beam) because load_abs/1 adds the correct + extension.

- Ensure that a module is loaded + Ensure that a module is loaded. -

Tries to to load a module in the same way as - load_file/1, +

Tries to load a module in the same way as + load_file/1, unless the module is already loaded. - In embedded mode, however, it does not load a module which is not + However, in embedded mode it does not load a module that is not already loaded, but returns {error, embedded} instead. See Error Reasons for Code-Loading Functions for a description of other possible error reasons.

- Load object code for a module + Load object code for a module.

This function can be used to load object code on remote - Erlang nodes. The argument Binary must contain + Erlang nodes. Argument Binary must contain object code for Module. Filename is only used by the code server to keep a record of from which file the object code for Module - comes. Accordingly, Filename is not opened and read by + comes. Thus, Filename is not opened and read by the code server.

Returns {module, Module} if successful, or {error, Reason} if loading fails. @@ -616,92 +635,94 @@ ok = code:finish_loading(Prepared), - Removes current code for a module + Remove current code for a module.

Removes the current code for Module, that is, the current code for Module is made old. This means that processes can continue to execute the code in the module, - but that no external function calls can be made to it.

+ but no external function calls can be made to it.

Returns true if successful, or false if there - is old code for Module which must be purged first, or + is old code for Module that must be purged first, or if Module is not a (loaded) module.

- Removes old code for a module + Remove old code for a module.

Purges the code for Module, that is, removes code marked as old. If some processes still linger in the old code, these processes are killed before the code is removed.

-

Returns true if successful and any process needed to +

Returns true if successful and any process is needed to be killed, otherwise false.

- Removes old code for a module, unless no process uses it + Remove old code for a module, unless no process uses it.

Purges the code for Module, that is, removes code marked as old, but only if no processes linger in it.

-

Returns false if the module could not be purged due - to processes lingering in old code, otherwise true.

+

Returns false if the module cannot be purged because + of processes lingering in old code, otherwise true.

- Check if a module is loaded + Check if a module is loaded. - Filename is an absolute filename + Filename is an absolute + filename.

Checks if Module is loaded. If it is, {file, Loaded} is returned, otherwise false.

-

Normally, Loaded is the absolute file name - Filename from which the code was obtained. If the module +

Normally, Loaded is the absolute filename + Filename from which the code is obtained. If the module is preloaded (see - script(4)), - Loaded==preloaded. If the module is Cover compiled (see - cover(3)), + sasl:script(4)), + Loaded==preloaded. If the module is Cover-compiled (see + tools:cover(3)), Loaded==cover_compiled.

- Get all loaded modules + Get all loaded modules. - Filename is an absolute filename + Filename is an absolute + filename.

Returns a list of tuples {Module, Loaded} for all - loaded modules. Loaded is normally the absolute file - name, as described for - is_loaded/1.

+ loaded modules. Loaded is normally the absolute filename, + as described for + is_loaded/1.

- The object code file of a module + The object code file of a module.

If the module is not loaded, this function searches the code - path for the first file which contains object code for - Module and returns the absolute file name. If - the module is loaded, it returns the name of the file which - contained the loaded object code. If the module is pre-loaded, - preloaded is returned. If the module is Cover compiled, - cover_compiled is returned. non_existing is - returned if the module cannot be found.

+ path for the first file containing object code for + Module and returns the absolute filename.

+

If the module is loaded, it returns the name of the file + containing the loaded object code.

+

If the module is preloaded, preloaded is returned.

+

If the module is Cover-compiled, cover_compiled is returned.

+

If the module cannot be found, non_existing is returned.

- Get the object code for a module + Gets the object code for a module. -

Searches the code path for the object code of the module - Module. It returns {Module, Binary, Filename} - if successful, and error if not. Binary is a - binary data object which contains the object code for +

Searches the code path for the object code of module + Module. Returns {Module, Binary, Filename} + if successful, otherwise error. Binary is a + binary data object, which contains the object code for the module. This can be useful if code is to be loaded on a remote node in a distributed system. For example, loading module Module on a node Node is done as @@ -715,10 +736,11 @@ rpc:call(Node, code, load_binary, [Module, Filename, Binary]), - Root directory of Erlang/OTP + Root directory of Erlang/OTP.

Returns the root directory of Erlang/OTP, which is the directory where it is installed.

+

Example:

 > code:root_dir().
 "/usr/local/otp"
@@ -726,10 +748,11 @@ rpc:call(Node, code, load_binary, [Module, Filename, Binary]),
- Library directory of Erlang/OTP + Library directory of Erlang/OTP.

Returns the library directory, $OTPROOT/lib, where $OTPROOT is the root directory of Erlang/OTP.

+

Example:

 > code:lib_dir().
 "/usr/local/otp/lib"
@@ -737,50 +760,49 @@ rpc:call(Node, code, load_binary, [Module, Filename, Binary]),
- Library directory for an application + Library directory for an application. -

This function is mainly intended for finding out the path +

Returns the path for the "library directory", the top directory, for an application Name located under $OTPROOT/lib or - on a directory referred to via the ERL_LIBS - environment variable.

-

If there is a regular directory called Name or - Name-Vsn in the code path with an ebin + on a directory referred to with environment variable ERL_LIBS.

+

If a regular directory called Name or + Name-Vsn exists in the code path with an ebin subdirectory, the path to this directory is returned (not - the ebin directory). If the directory refers to a - directory in an archive, the archive name is stripped away - before the path is returned. For example, if the directory + the ebin directory).

+

If the directory refers to a directory in an archive, the + archive name is stripped away before the path is returned. + For example, if directory /usr/local/otp/lib/mnesia-4.2.2.ez/mnesia-4.2.2/ebin is in the path, /usr/local/otp/lib/mnesia-4.2.2/ebin - will be returned. This means that the library directory for - an application is the same, regardless of whether the + is returned. This means that the library directory for + an application is the same, regardless if the application resides in an archive or not.

- +

Example:

 > code:lib_dir(mnesia).
 "/usr/local/otp/lib/mnesia-4.2.2"

Returns {error, bad_name} if Name is not the name of an application under $OTPROOT/lib or - on a directory referred to via the ERL_LIBS - environment variable. Fails with an exception if Name - has the wrong type.

+ on a directory referred to through environment variable ERL_LIBS. + Fails with an exception if Name has the wrong type.

-

For backward compatibility, Name is also allowed to - be a string. That will probably change in a future release.

+

For backward compatibility, Name is also + allowed to be a string. That will probably change in a future release.

- subdirectory for an application + Subdirectory for an application.

Returns the path to a subdirectory directly under the top directory of an application. Normally the subdirectories - resides under the top directory for the application, but when - applications at least partly resides in an archive the - situation is different. Some of the subdirectories may reside - as regular directories while other resides in an archive - file. It is not checked if this directory really exists.

- + reside under the top directory for the application, but when + applications at least partly resides in an archive, the + situation is different. Some of the subdirectories can reside + as regular directories while other reside in an archive + file. It is not checked whether this directory exists.

+

Example:

 > code:lib_dir(megaco, priv).
 "/usr/local/otp/lib/megaco-3.9.1.1/priv"
@@ -791,7 +813,7 @@ rpc:call(Node, code, load_binary, [Module, Filename, Binary]),
- Library directory for the compiler + Library directory for the compiler.

Returns the compiler library directory. Equivalent to code:lib_dir(compiler).

@@ -799,10 +821,10 @@ rpc:call(Node, code, load_binary, [Module, Filename, Binary]),
- Priv directory for an application + Priv directory for an application.

Returns the path to the priv directory in an - application. Equivalent to code:lib_dir(Name, priv)..

+ application. Equivalent to code:lib_dir(Name, priv).

For backward compatibility, Name is also allowed to be a string. That will probably change in a future release.

@@ -810,43 +832,43 @@ rpc:call(Node, code, load_binary, [Module, Filename, Binary]),
- Object code file extension + Object code file extension. -

Returns the object code file extension that corresponds to - the Erlang machine used, namely ".beam".

+

Returns the object code file extension corresponding to + the Erlang machine used, namely .beam.

- Mark a directory as sticky + Mark a directory as sticky. -

This function marks Dir as sticky.

-

Returns ok if successful or error if not.

+

Marks Dir as sticky.

+

Returns ok if successful, otherwise error.

- Remove a sticky directory mark + Remove a sticky directory mark. -

This function unsticks a directory which has been marked as +

Unsticks a directory that is marked as sticky.

-

Returns ok if successful or error if not.

+

Returns ok if successful, otherwise error.

- Test whether a module is sticky + Test if a module is sticky. -

This function returns true if Module is the +

Returns true if Module is the name of a module that has been loaded from a sticky directory - (or in other words: an attempt to reload the module will fail), + (in other words: an attempt to reload the module will fail), or false if Module is not a loaded module or is not sticky.

- Full name of a file located in the code path + Full name of a file located in the code path.

Searches the code path for Filename, a file of arbitrary type. If found, the full name is returned. @@ -859,32 +881,39 @@ rpc:call(Node, code, load_binary, [Module, Filename, Binary]), Search for modules with identical names. -

Searches the entire code space for module names with +

Searches all directories in the code path for module names with identical names and writes a report to stdout.

- Test whether a module has native code + Test if a module has native code. -

This function returns true if Module is - name of a loaded module that has native code loaded, and - false if Module is loaded but does not have - native. If Module is not loaded, this function returns - undefined.

+

Returns:

+ + true +

If Module is the + name of a loaded module that has native code loaded

+ false +

If Module is loaded but does not have + native code

+ undefined +

If Module is not loaded

+
- The code_server's mode. + The mode of the code server. -

This function returns an atom describing the code_server's mode: - interactive or embedded.

+

Returns an atom describing the mode of the code server: + interactive or embedded.

This information is useful when an external entity (for example, - an IDE) provides additional code for a running node. If in interactive - mode, it only needs to add to the code path. If in embedded mode, - the code has to be loaded with load_binary/3

+ an IDE) provides additional code for a running node. If the code server is + in interactive mode, it only has to add the path to the code. If the code server + is in embedded mode, the code must be loaded with + load_binary/3.

diff --git a/lib/kernel/doc/src/config.xml b/lib/kernel/doc/src/config.xml index 0e34549482..ba94fefd25 100644 --- a/lib/kernel/doc/src/config.xml +++ b/lib/kernel/doc/src/config.xml @@ -11,7 +11,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software @@ -19,7 +19,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - + config @@ -33,94 +33,93 @@

A configuration file contains values for configuration parameters for the applications in the system. The erl - command line argument -config Name tells the system to use + command-line argument -config Name tells the system to use data in the system configuration file Name.config.

-

Configuration parameter values in the configuration file will +

Configuration parameter values in the configuration file override the values in the application resource files (see - app(4)). The values in the configuration file can be - overridden by command line flags (see erl(1)).

+ app(4). + The values in the configuration file can be + overridden by command-line flags (see + erts:erl(1).

The value of a configuration parameter is retrieved by calling application:get_env/1,2.

- FILE SYNTAX -

The configuration file should be called Name.config where - Name is an arbitrary name.

-

The .config file contains one single Erlang term. - The file has the following syntax:

+ File Syntax +

The configuration file is to be called Name.config, where + Name is any name.

+

File .config contains a single Erlang term and + has the following syntax:

-[{Application1, [{Par11, Val11}, ..]}, - .. - {ApplicationN, [{ParN1, ValN1}, ..]}]. - - -

Application = atom() is the name of the application.

-
- -

Par = atom() is the name of a configuration parameter.

-
- -

Val = term() is the value of a configuration - parameter.

-
-
+[{Application1, [{Par11, Val11}, ...]}, + ... + {ApplicationN, [{ParN1, ValN1}, ...]}]. + + Application = atom() +

Application name.

+ Par = atom() +

Name of a configuration parameter.

+ Val = term() +

Value of a configuration parameter.

+
sys.config

When starting Erlang in embedded mode, it is assumed that exactly one system configuration file is used, named - sys.config. This file should be located in + sys.config. This file is to be located in $ROOT/releases/Vsn, where $ROOT is the Erlang/OTP root installation directory and Vsn is the release version.

Release handling relies on this assumption. When installing a new release version, the new sys.config is read and used to update the application configurations.

-

This means that specifying another, or additional, .config - files would lead to inconsistent update of application +

This means that specifying another .config file, or more + .config files, leads to inconsistent update of application configurations. Therefore, in Erlang 5.4/OTP R10B, the syntax of sys.config was extended to allow pointing out other .config files:

[{Application, [{Par, Val}]} | File]. - - -

File = string() is the name of another .config - file. The extension .config may be omitted. It is - recommended to use absolute paths. A relative path is - relative the current working directory of the emulator.

-
-
+ + File = string() + Name of another .config file. + Extension .config can be omitted. It is + recommended to use absolute paths. A relative path is + relative the current working directory of the emulator. +

When traversing the contents of sys.config and a filename is encountered, its contents are read and merged with the result so far. When an application configuration tuple {Application, Env} is found, it is merged with the result so far. Merging means that new parameters are added and existing - parameter values overwritten. Example:

+ parameter values overwritten.

+

Example:

sys.config: [{myapp,[{par1,val1},{par2,val2}]}, "/home/user/myconfig"]. - myconfig.config: [{myapp,[{par2,val3},{par3,val4}]}]. -

This will yield the following environment for myapp:

+

This yields the following environment for myapp:

[{par1,val1},{par2,val3},{par3,val4}] -

The behaviour if a file specified in sys.config does not - exist or is erroneous in some other way, is backwards compatible. +

The behavior if a file specified in sys.config does not + exist, or is erroneous, is backwards compatible. Starting the runtime system will fail. Installing a new release - version will not fail, but an error message is given and + version will not fail, but an error message is returned and the erroneous file is ignored.

- SEE ALSO -

app(4), erl(1), OTP Design Principles

+ See Also +

app(4), + erts:erl(1), + OTP Design Principles

diff --git a/lib/kernel/doc/src/disk_log.xml b/lib/kernel/doc/src/disk_log.xml index 7d4a9687ea..0b6ee1e6a5 100644 --- a/lib/kernel/doc/src/disk_log.xml +++ b/lib/kernel/doc/src/disk_log.xml @@ -5,7 +5,7 @@
1997 - 2013 + 2016 Ericsson AB, All Rights Reserved @@ -35,149 +35,174 @@ disk_log.sgml
disk_log - A disk based term logging facility + A disk-based term logging facility. -

disk_log is a disk based term logger which makes - it possible to efficiently log items on files. - Two types of logs are supported, - halt logs and wrap logs. A halt log - appends items to a single file, the size of which may or may - not be limited by the disk log module, whereas a wrap log utilizes - a sequence of wrap log files of limited size. As a wrap log file - has been filled up, further items are logged onto to the next - file in the sequence, starting all over with the first file when - the last file has been filled up. For the sake of efficiency, - items are always written to files as binaries. -

-

Two formats of the log files are supported, the internal format and the external format. The internal - format supports automatic repair of log files that have not been - properly closed, and makes it possible to efficiently read - logged items in chunks using a set of functions defined - in this module. In fact, this is the only way to read internally - formatted logs. The external format leaves it up to the user to - read the logged deep byte lists. The disk log module cannot - repair externally formatted logs. An item logged to an - internally formatted log must not occupy more than 4 GB of disk - space (the size must fit in 4 bytes). -

-

For each open disk log there is one process that handles requests - made to the disk log; the disk log process is created when open/1 +

disk_log is a disk-based term logger that enables + efficient logging of items on files.

+

Two types of logs are supported:

+ + halt logs +

Appends items to a single file, which size can + be limited by the disk log module.

+ wrap logs +

Uses a sequence of wrap log files of limited size. As a + wrap log file is filled up, further items are logged on to the next + file in the sequence, starting all over with the first file when + the last file is filled up.

+
+

For efficiency reasons, items are always written to files as binaries.

+ +

Two formats of the log files are supported:

+ + internal format +

Supports automatic repair of log files that are not + properly closed and enables efficient reading of logged items in + chunks using a set of functions defined in this module. + This is the only way to read internally formatted logs. + An item logged to an internally formatted log must not occupy more + than 4 GB of disk space (the size must fit in 4 bytes).

+ external format +

Leaves it up to the user to read the logged deep byte lists. + The disk log module cannot repair externally formatted logs.

+
+ +

For each open disk log, one process handles requests + made to the disk log. This process is created when + open/1 is called, provided there exists no process handling the disk log. - A process that opens a disk log can either be an owner + A process that opens a disk log can be an owner or an anonymous user of the disk log. Each owner is - linked to the disk log - process, and the disk log is closed by the owner should the - owner terminate. Owners can subscribe to notifications, - messages of the form {disk_log, Node, Log, Info} that are sent + linked to the disk log process, and an owner can close the disk log + either explicitly (by calling close/1 or lclose/1,2) + or by terminating.

+

Owners can subscribe to notifications, + messages of the form {disk_log, Node, Log, Info}, which are sent from the disk log process when certain events occur, see - the commands below and in particular the open/1 option - notify. - There can be several owners of a log, but a process cannot own a - log more than once. One and the same process may, however, - open the log - as a user more than once. For a disk log process to properly close - its file and terminate, it must be closed by its owners and once by - some non-owner process for each time the log was used anonymously; - the users are counted, and there must not be any users left when the - disk log process terminates. + the functions and in particular the open/1 option + notify. + A log can have many owners, but a process cannot own a + log more than once. However, the same process can open the log + as a user more than once.

+

For a disk log process to close its file properly and terminate, + it must be closed by its owners and once by some non-owner process + for each time the log was used anonymously. The users are counted + and there must not be any users left when the disk log process terminates.

-

Items can be logged synchronously by using the functions - log/2, blog/2, log_terms/2 and - blog_terms/2. For each of these functions, the caller is put - on hold until the items have been logged (but not necessarily +

Items can be logged synchronously by using functions + log/2, + blog/2, + log_terms/2, and + blog_terms/2. + For each of these functions, the caller is put + on hold until the items are logged (but not necessarily written, use sync/1 to ensure that). By adding an a - to each of the mentioned function names we get functions that log + to each of the mentioned function names, we get functions that log items asynchronously. Asynchronous functions do not wait for - the disk log process to actually write the items to the file, but + the disk log process to write the items to the file, but return the control to the caller more or less immediately.

-

When using the internal format for logs, the functions - log/2, log_terms/2, alog/2, and - alog_terms/2 should be used. These functions log one or - more Erlang terms. By prefixing each of the functions with - a b (for "binary") we get the corresponding blog - functions for the external format. These functions log one or - more deep lists of bytes or, alternatively, binaries of deep lists - of bytes. - For example, to log the string "hello" in ASCII format, we +

When using the internal format for logs, use functions + log/2, + log_terms/2, + alog/2, and + alog_terms/2. + These functions log one or more Erlang terms. + By prefixing each of the functions with a b (for "binary"), + we get the corresponding blog() functions for the external format. + These functions log one or more deep lists of bytes or, alternatively, + binaries of deep lists of bytes. + For example, to log the string "hello" in ASCII format, you can use disk_log:blog(Log, "hello"), or disk_log:blog(Log, list_to_binary("hello")). The two - alternatives are equally efficient. The blog functions - can be used for internally formatted logs as well, but in - this case they must be called with binaries constructed with - calls to term_to_binary/1. There is no check to ensure + alternatives are equally efficient.

+

The blog() functions can also be used for internally formatted + logs, but in this case they must be called with binaries constructed + with calls to + term_to_binary/1. + There is no check to ensure this, it is entirely the responsibility of the caller. If these functions are called with binaries that do not correspond to - Erlang terms, the chunk/2,3 and automatic repair - functions will fail. The corresponding terms (not the binaries) - will be returned when chunk/2,3 is called. + Erlang terms, the + chunk/2,3 + and automatic repair + functions fail. The corresponding terms (not the binaries) + are returned when chunk/2,3 is called.

A collection of open disk logs with the same name running on - different nodes is said to be a a distributed disk log - if requests made to any one of the logs are automatically made to - the other logs as well. The members of such a collection will be + different nodes is said to be a distributed disk log + if requests made to any of the logs are automatically made to + the other logs as well. The members of such a collection are called individual distributed disk logs, or just distributed disk logs if there is no risk of confusion. There is no order - between the members of such a collection. For instance, logged - terms are not necessarily written onto the node where the - request was made before written onto the other nodes. One could - note here that there are a few functions that do not make - requests to all members of distributed disk logs, namely - info, chunk, bchunk, chunk_step and - lclose. An open disk log that is not a distributed disk + between the members of such a collection. For example, logged + terms are not necessarily written to the node where the + request was made before written to the other nodes. However, + a few functions do not make requests to all + members of distributed disk logs, namely + info/1, + chunk/2,3, + bchunk/2,3, + chunk_step/3, and + lclose/1,2.

+

An open disk log that is not a distributed disk log is said to be a local disk log. A local disk log is - accessible only from the node where the disk log process runs, + only accessible from the node where the disk log process runs, whereas a distributed disk log is accessible from all nodes in - the Erlang system, with exception for those nodes where a local + the Erlang system, except for those nodes where a local disk log with the same name as the distributed disk log exists. All processes on nodes that have access to a local or - distributed disk log can log items or otherwise change, inspect + distributed disk log can log items or otherwise change, inspect, or close the log.

It is not guaranteed that all log files of a distributed disk log - contain the same log items; there is no attempt made to synchronize + contain the same log items. No attempt is made to synchronize the contents of the files. However, as long as at least one of - the involved nodes is alive at each time, all items will be logged. + the involved nodes is alive at each time, all items are logged. When logging items to a distributed log, or otherwise trying to change the log, the replies from individual logs are ignored. If all nodes are down, the disk log functions reply with a nonode error.

-

In some applications it may not be acceptable that +

In some applications, it can be unacceptable that replies from individual logs are ignored. An alternative in such - situations is to use several local disk logs instead of one + situations is to use many local disk logs instead of one distributed disk log, and implement the distribution without use - of the disk log module.

+ of the disk_log module.

Errors are reported differently for asynchronous log attempts - and other uses of the disk log module. When used synchronously - the disk log module replies with an error message, but when called - asynchronously, the disk log module does not know where to send - the error message. Instead owners subscribing to notifications will + and other uses of the disk_log module. When used synchronously, + this module replies with an error message, but when called + asynchronously, this module does not know where to send + the error message. Instead, owners subscribing to notifications receive an error_status message.

-

The disk log module itself does not report errors to the - error_logger module; it is up to the caller to decide - whether the error logger should be employed or not. The function - format_error/1 can be used to produce readable messages - from error replies. Information events are however sent to the - error logger in two situations, namely when a log is repaired, - or when a file is missing while reading chunks. +

The disk_log module does not report errors to the + error_logger + module. It is up to the caller to decide + whether to employ the error logger. Function + format_error/1 + can be used to produce readable messages from error replies. + However, information events are sent to the error logger in two + situations, namely when a log is repaired, or when a file is missing + while reading chunks.

-

The error message no_such_log means that the given - disk log is not currently open. Nothing is said about - whether the disk log files exist or not. +

Error message no_such_log means that the specified + disk log is not open. Nothing is said about whether the disk log + files exist or not.

If an attempt to reopen or truncate a log fails (see - reopen and truncate) the disk log process - immediately terminates. Before the process terminates links to - to owners and blocking processes (see block) are removed. - The effect is that the links work in one direction only; any - process using a disk log has to check for the error message - no_such_log if some other process might truncate or - reopen the log simultaneously.

+ reopen/2,3 + and + truncate/1,2) + the disk log process terminates immediately. Before the process + terminates, links to owners and blocking processes (see + block/1,2) are removed. + The effect is that the links work in one direction only. Any + process using a disk log must check for error message + no_such_log if some other process truncates or + reopens the log simultaneously.

@@ -221,11 +246,10 @@ - Return the accessible disk logs on the current node. + Return the accessible disk logs on the current node. -

The accessible_logs/0 function returns - the names of the disk logs accessible on the current node. - The first list contains local disk logs, and the +

Returns the names of the disk logs accessible on the current node. + The first list contains local disk logs and the second list contains distributed disk logs.

@@ -233,55 +257,55 @@ - Asynchronously log an item onto a disk log. + Asynchronously log an item on to a disk log. -

The alog/2 and balog/2 functions asynchronously - append an item to a disk log. The function alog/2 is - used for internally formatted logs, and the function balog/2 - for externally formatted logs. balog/2 can be used - for internally formatted logs as well provided the binary was - constructed with a call to term_to_binary/1. +

Asynchronously append an item to a disk log. alog/2 is + used for internally formatted logs and balog/2 + for externally formatted logs. balog/2 can also be used + for internally formatted logs if the binary is + constructed with a call to + term_to_binary/1.

-

The owners that subscribe to notifications will receive the - message read_only, blocked_log - or format_external in case the item cannot be written +

Owners subscribing to notifications receive + message read_only, blocked_log, + or format_external if the item cannot be written on the log, and possibly one of the messages wrap, - full and error_status if an item was written - on the log. The message error_status is sent if there - is something wrong with the header function or a file error - occurred. + full, or error_status if an item is written + on the log. Message error_status is sent if + something is wrong with the header function or if a file error + occurs.

- Asynchronously log several items onto a disk log. + Asynchronously log many items on to a disk log. -

The alog_terms/2 and balog_terms/2 functions - asynchronously append a list of items to a disk log. - The function alog_terms/2 is used for internally - formatted logs, and the function balog_terms/2 - for externally formatted logs. balog_terms/2 can be used - for internally formatted logs as well provided the binaries were - constructed with calls to term_to_binary/1. +

Asynchronously append a list of items to a disk log. + alog_terms/2 is used for internally + formatted logs and balog_terms/2 + for externally formatted logs. balog_terms/2 can also be used + for internally formatted logs if the binaries are + constructed with calls to + term_to_binary/1.

-

The owners that subscribe to notifications will receive the - message read_only, blocked_log - or format_external in case the items cannot be written +

Owners subscribing to notifications receive + message read_only, blocked_log, + or format_external if the items cannot be written on the log, and possibly one or more of the messages wrap, - full and error_status if items were written - on the log. The message error_status is sent if there - is something wrong with the header function or a file error - occurred. + full, and error_status if items are written + on the log. Message error_status is sent if + something is wrong with the header function or if a file error + occurs.

@@ -294,76 +318,75 @@

With a call to block/1,2 a process can block a log. If the blocking process is not an owner of the log, a temporary link is created between the disk log process and the blocking - process. The link is used to ensure that the disk log is - unblocked should the blocking process terminate without + process. The link ensures that the disk log is + unblocked if the blocking process terminates without first closing or unblocking the log.

Any process can probe a blocked log with info/1 or close it with close/1. The blocking process can also - use the functions chunk/2,3, bchunk/2,3, + use functions chunk/2,3, bchunk/2,3, chunk_step/3, and unblock/1 without being - affected by the block. Any other attempt than those hitherto - mentioned to update or read a blocked log suspends the - calling process until the log is unblocked or returns an + affected by the block. Any other attempt than those + mentioned so far to update or read a blocked log suspends the + calling process until the log is unblocked or returns error message {blocked_log, Log}, depending on whether the value of QueueLogRecords is true - or false. The default value of QueueLogRecords - is true, which is used by block/1. + or false. QueueLogRecords defaults to + true, which is used by block/1.

- Change the head or head_func option for an owner of a disk log. + Change option head or head_func for an owner of a disk log. -

The change_header/2 function changes the value of - the head or head_func option of a disk log.

+

Changes the value of option head or head_func for an owner of a disk log.

- Change the notify option for an owner of a disk log. + Change option notify for an owner of a disk log. -

The change_notify/3 function changes the value of the - notify option for an owner of a disk log.

+

Changes the value of option notify for an owner of a disk log.

Change the size of an open disk log. -

The change_size/2 function changes the size of an open log. - For a halt log it is always possible to increase the size, - but it is not possible to decrease the size to something less than - the current size of the file. +

Changes the size of an open log. + For a halt log, the size can always be increased, + but it cannot be decreased to something less than + the current file size.

-

For a wrap log it is always possible to increase both the - size and number of files, as long as the number of files does not +

For a wrap log, both the size and the number of files can always + be increased, as long as the number of files does not exceed 65000. If the maximum number of files is decreased, the - change will not be valid until the current file is full and the + change is not valid until the current file is full and the log wraps to the next file. - The redundant files will be removed next time the log wraps around, - i.e. starts to log to file number 1. + The redundant files are removed the next time the log wraps around, + that is, starts to log to file number 1.

As an example, assume that the old maximum number of files is 10 and that the new maximum number of files is 6. If the current file number is not greater than the new maximum number - of files, the files 7 to 10 will be removed when file number 6 + of files, files 7-10 are removed when file 6 is full and the log starts to write to file number 1 again. - Otherwise the files greater than the current - file will be removed when the current file is full (e.g. if - the current file is 8, the files 9 and 10); the files between - new maximum number of files and the current - file (i.e. files 7 and 8) will be removed next time file number 6 + Otherwise, the files greater than the current + file are removed when the current file is full (for example, if + the current file is 8, files 9 and 10 are removed). The files between + the new maximum number of files and the current + file (that is, files 7 and 8) are removed the next time file 6 is full.

-

If the size of the files is decreased the change will immediately - affect the current log. It will not of course change the - size of log files already full until next time they are used. +

If the size of the files is decreased, the change immediately + affects the current log. It does not change the + size of log files already full until the next time they are used.

-

If the log size is decreased for instance to save space, - the function inc_wrap_file/1 can be used to force the log - to wrap. +

If the log size is decreased, for example, to save space, + function + inc_wrap_file/1 + can be used to force the log to wrap.

@@ -380,93 +403,85 @@ -

The chunk/2,3 and bchunk/2,3 functions make - it possible to efficiently read the terms which have been - appended to an internally formatted log. It minimizes disk - I/O by reading 64 kilobyte chunks from the file. The - bchunk/2,3 functions return the binaries read from - the file; they do not call binary_to_term. Otherwise - the work just like chunk/2,3. +

Efficiently reads the terms that are appended + to an internally formatted log. It minimizes disk + I/O by reading 64 kilobyte chunks from the file. Functions + bchunk/2,3 return the binaries read from + the file, they do not call binary_to_term(). Apart from that, + they work just like chunk/2,3.

-

The first time chunk (or bchunk) is called, +

The first time chunk() (or bchunk()) is called, an initial continuation, the atom start, must be - provided. If there is a disk log process running on the - current node, terms are read from that log, otherwise an + provided. If a disk log process is running on the + current node, terms are read from that log. Otherwise, an individual distributed log on some other node is chosen, if such a log exists.

When chunk/3 is called, N controls the maximum number of terms that are read from the log in each - chunk. Default is infinity, which means that all the + chunk. Defaults to infinity, which means that all the terms contained in the 64 kilobyte chunk are read. If less than N terms are returned, this does not necessarily mean - that the end of the file has been reached. + that the end of the file is reached.

-

The chunk function returns a tuple - {Continuation2, Terms}, where Terms is a list +

chunk() returns a tuple + {Continuation2, Terms}, where + Terms is a list of terms found in the log. Continuation2 is yet - another continuation which must be passed on to any - subsequent calls to chunk. With a series of calls to - chunk it is possible to extract all terms from a log. + another continuation, which must be passed on to any + subsequent calls to chunk(). With a series of calls to + chunk(), all terms from a log can be extracted.

-

The chunk function returns a tuple - {Continuation2, Terms, Badbytes} if the log is opened - in read-only mode and the read chunk is corrupt. Badbytes - is the number of bytes in the file which were found not to be - Erlang terms in the chunk. Note also that the log is not repaired. +

chunk() returns a tuple + {Continuation2, Terms, Badbytes} + if the log is opened in read-only mode and the read chunk is corrupt. + Badbytes is the number of bytes in the file found not to be + Erlang terms in the chunk. Notice that the log is not repaired. When trying to read chunks from a log opened in read-write mode, - the tuple {corrupt_log_file, FileName} is returned if the + tuple {corrupt_log_file, FileName} is returned if the read chunk is corrupt.

-

chunk returns eof when the end of the log is - reached, or {error, Reason} if an error occurs. Should - a wrap log file be missing, a message is output on the error log. +

chunk() returns eof when the end of the log is + reached, or {error, Reason} if an error occurs. If + a wrap log file is missing, a message is output on the error log.

When chunk/2,3 is used with wrap logs, the returned - continuation may or may not be valid in the next call to - chunk. This is because the log may wrap and delete - the file into which the continuation points. To make sure - this does not happen, the log can be blocked during the - search. + continuation might not be valid in the next call to + chunk(). This is because the log can wrap and delete + the file into which the continuation points. To prevent this, + the log can be blocked during the search.

- Return information about a chunk continuation of a disk log. + Return information about a chunk continuation of a disk log. -

The chunk_info/1 function returns the following pair +

Returns the pair {node, Node}, describing the chunk continuation returned by - chunk/2,3, bchunk/2,3, or chunk_step/3: -

- - -

{node, Node}. Terms are read from - the disk log running on Node.

-
-
+ chunk/2,3, bchunk/2,3, or chunk_step/3.

+

Terms are read from the disk log running on Node.

- Step forward or backward among the wrap log files of a disk log. + Step forward or backward among the wrap log files of a disk log. -

The function chunk_step can be used in conjunction - with chunk/2,3 and bchunk/2,3 to search - through an internally formatted wrap log. It takes as +

Can be used with chunk/2,3 and bchunk/2,3 + to search through an internally formatted wrap log. It takes as argument a continuation as returned by chunk/2,3, bchunk/2,3, or chunk_step/3, and steps forward (or backward) Step files in the wrap log. The - continuation returned points to the first log item in the + continuation returned, points to the first log item in the new current file.

-

If the atom start is given as continuation, a disk log +

If atom start is specified as continuation, a disk log to read terms from is chosen. A local or distributed disk log on the current node is preferred to an individual distributed log on some other node.

-

If the wrap log is not full because all files have not been - used yet, {error, end_of_log} is returned if trying to +

If the wrap log is not full because all files are not yet + used, {error, end_of_log} is returned if trying to step outside the log.

@@ -476,21 +491,20 @@ Close a disk log. -

The function close/1 closes a +

Closes a local or distributed disk log properly. An internally formatted log must be closed before the Erlang system is - stopped, otherwise the log is regarded as unclosed and the - automatic repair procedure will be activated next time the + stopped. Otherwise, the log is regarded as unclosed and the + automatic repair procedure is activated next time the log is opened.

-

The disk log process in not terminated as long as there are - owners or users of the log. It should be stressed that each - and every owner must close the log, possibly by terminating, - and that any other process - not only the processes that have - opened the log anonymously - can decrement the users +

The disk log process is not terminated as long as there are + owners or users of the log. All owners must close the log, + possibly by terminating. Also, any other process, not only the processes + that have opened the log anonymously, can decrement the users counter by closing the log. Attempts to close a log by a process that is - not an owner are simply ignored if there are no users. + not an owner are ignored if there are no users.

If the log is blocked by the closing process, the log is also unblocked. @@ -499,12 +513,14 @@ - Return an English description of a disk log error reply. + Return an English description of a disk log error reply.

Given the error returned by any function in this module, - the function format_error returns a descriptive string - of the error in English. For file errors, the function - format_error/1 in the file module is called.

+ this function returns a descriptive string + of the error in English. For file errors, function + format_error/1 in module + file + is called.

@@ -513,16 +529,15 @@ -

The inc_wrap_file/1 function forces the internally formatted - disk log to start logging to the - next log file. It can be used, for instance, in conjunction with +

Forces the internally formatted disk log to start logging to the + next log file. It can be used, for example, with change_size/2 to reduce the amount of disk space allocated by the disk log.

-

The owners that subscribe to notifications will normally - receive a wrap message, but in case of - an error with a reason tag of invalid_header or - file_error an error_status message will be sent.

+

Owners subscribing to notifications normally + receive a wrap message, but if + an error occurs with a reason tag of invalid_header or + file_error, an error_status message is sent.

@@ -530,132 +545,148 @@ Return information about a disk log. -

The info/1 function returns a list of {Tag, Value} - pairs describing the log. If there is a disk log process running - on the current node, that log is used as source of information, - otherwise an individual distributed log on - some other node is chosen, if such a log exists. +

Returns a list of {Tag, Value} pairs describing the log. + If a disk log process is running on the current node, + that log is used as source of information, otherwise an individual + distributed log on some other node is chosen, if such a log exists.

The following pairs are returned for all logs:

- + + {name, Log} -

{name, Log}, where Log is the name of - the log as given by the open/1 option name.

+

Log is the log name + as specified by the open/1 option name.

+ {file, File} -

{file, File}. For halt logs File is the +

For halt logs File is the filename, and for wrap logs File is the base name.

+ {type, Type} -

{type, Type}, where Type is the type of - the log as given by the open/1 option type.

+

Type is the log type + as specified by the open/1 option type.

+ {format, Format} -

{format, Format}, where Format is the format - of the log as given by the open/1 option format.

+

Format is the log format + as specified by the open/1 option format.

+ {size, Size} -

{size, Size}, where Size is the size - of the log as given by the open/1 option size, +

Size is the log size + as specified by the open/1 option size, or the size set by change_size/2. The value set by change_size/2 is reflected immediately.

+ {mode, Mode} -

{mode, Mode}, where Mode is the mode - of the log as given by the open/1 option mode.

+

Mode is the log mode + as specified by the open/1 option mode.

+ {owners, [{pid(), Notify}]} -

{owners, [{pid(), Notify}]} where Notify +

Notify is the value set by the open/1 option notify - or the function change_notify/3 for the owners of + or function change_notify/3 for the owners of the log.

+ {users, Users} -

{users, Users} where Users is the number +

Users is the number of anonymous users of the log, see the open/1 option - linkto.

+ linkto.

+ {status, Status} -

{status, Status}, where Status is ok - or {blocked, QueueLogRecords} as set by the functions +

Status is ok + or {blocked, QueueLogRecords} as set by functions block/1,2 and unblock/1.

+ {node, Node} -

{node, Node}. The information returned by the - current invocation of the info/1 function has been +

The information returned by the + current invocation of function info/1 is gathered from the disk log process running on Node.

+ {distributed, Dist} -

{distributed, Dist}. If the log is local on - the current node, then Dist has the value local, +

If the log is local on + the current node, Dist has the value local, otherwise all nodes where the log is distributed are returned as a list.

-
+

The following pairs are returned for all logs opened in read_write mode:

- + + {head, Head} -

{head, Head}. Depending of the value of - the open/1 options head and head_func - or set by the function change_header/2, the value +

Depending on the value of + the open/1 options head and head_func, + or set by function change_header/2, the value of Head is none (default), - {head, H} (head option) or {M,F,A} + {head, H} (head option), or {M,F,A} (head_func option).

+ {no_written_items, NoWrittenItems} -

{no_written_items, NoWrittenItems}, where - NoWrittenItems is the number of items +

NoWrittenItems is the number of items written to the log since the disk log process was created.

-
+

The following pair is returned for halt logs opened in read_write mode:

- + + {full, Full} -

{full, Full}, where Full is true or +

Full is true or false depending on whether the halt log is full or not.

-
+

The following pairs are returned for wrap logs opened in read_write mode:

- + + {no_current_bytes, integer() >= 0} -

{no_current_bytes, integer() >= 0} is the number +

The number of bytes written to the current wrap log file.

+ {no_current_items, integer() >= 0} -

{no_current_items, integer() >= 0} is the number +

The number of items written to the current wrap log file, header inclusive.

+ {no_items, integer() >= 0} -

{no_items, integer() >= 0} is the total number +

The total number of items in all wrap log files.

+ {current_file, integer()} -

{current_file, integer()} is the ordinal for +

The ordinal for the current wrap log file in the range 1..MaxNoFiles, - where MaxNoFiles is given by the open/1 option + where MaxNoFiles is specified by the open/1 option size or set by change_size/2.

+ {no_overflows, {SinceLogWasOpened, SinceLastInfo}} -

{no_overflows, {SinceLogWasOpened, SinceLastInfo}}, - where SinceLogWasOpened (SinceLastInfo) is - the number of times a wrap log file has been filled up and a - new one opened or inc_wrap_file/1 has been called since +

SinceLogWasOpened (SinceLastInfo) + is the number of times a wrap log file has been filled up and a + new one is opened or inc_wrap_file/1 has been called since the disk log was last opened (info/1 was last called). The first time info/2 is called after a log was (re)opened or truncated, the two values are equal.

-
-

Note that the chunk/2,3, bchunk/2,3, and - chunk_step/3 functions do not affect any value + +

Notice that functions chunk/2,3, bchunk/2,3, and + chunk_step/3 do not affect any value returned by info/1.

@@ -666,17 +697,16 @@ Close a disk log on one node. -

The function lclose/1 closes a local log or an - individual distributed log on the current node. - The function lclose/2 closes an individual - distributed log on the specified node if the node - is not the current one. - lclose(Log) is equivalent to +

lclose/1 closes a local log or an individual distributed + log on the current node.

+

lclose/2 closes an individual distributed log on the + specified node if the node is not the current one.

+

lclose(Log) is equivalent to lclose(Log, node()). - See also close/1. + See also close/1.

-

If there is no log with the given name - on the specified node, no_such_log is returned. +

If no log with the specified name exist on the specified node, + no_such_log is returned.

@@ -689,25 +719,27 @@ -

The log/2 and blog/2 functions synchronously - append a term to a disk log. They return ok or - {error, Reason} when the term has been written to - disk. If the log is distributed, ok is always - returned, unless all nodes are down. Terms are written by - means of the ordinary write() function of the - operating system. Hence, there is no guarantee that the term - has actually been written to the disk, it might linger in - the operating system kernel for a while. To make sure the - item is actually written to disk, the sync/1 function +

Synchronously + appends a term to a disk log. Returns ok or + {error, Reason} when the term is written to + disk. If the log is distributed, ok is returned, + unless all nodes are down. Terms are written by + the ordinary write() function of the + operating system. Hence, it is not guaranteed that the term + is written to disk, it can linger in + the operating system kernel for a while. To ensure that the + item is written to disk, function + sync/1 must be called.

-

The log/2 function is used for internally formatted logs, +

log/2 is used for internally formatted logs, and blog/2 for externally formatted logs. - blog/2 can be used - for internally formatted logs as well provided the binary was - constructed with a call to term_to_binary/1. -

-

The owners that subscribe to notifications will be notified + blog/2 can also be used + for internally formatted logs if the binary is + constructed with a call to + + term_to_binary/1.

+

Owners subscribing to notifications are notified of an error with an error_status message if the error reason tag is invalid_header or file_error.

@@ -716,27 +748,27 @@ - Log several items onto a disk log. + Log many items onto a disk log. -

The log_terms/2 and blog_terms/2 functions - synchronously append a list of items to the log. The benefit - of using these functions rather than the log/2 and - blog/2 functions is that of efficiency: the given - list is split into as large sublists as possible (limited by - the size of wrap log files), and each sublist is logged as - one single item, which reduces the overhead. +

Synchronously appends a list of items to the log. It is more + efficient to use these functions instead of functions log/2 + and blog/2. The specified list is split into as large + sublists as possible (limited by the size of wrap log files), + and each sublist is logged as one single item, which reduces + the overhead.

-

The log_terms/2 function is used for internally formatted +

log_terms/2 is used for internally formatted logs, and blog_terms/2 for externally formatted logs. - blog_terms/2 can be used - for internally formatted logs as well provided the binaries were - constructed with calls to term_to_binary/1. -

-

The owners that subscribe to notifications will be notified + blog_terms/2 can also be used + for internally formatted logs if the binaries are + constructed with calls to + + term_to_binary/1.

+

Owners subscribing to notifications are notified of an error with an error_status message if the error reason tag is invalid_header or file_error.

@@ -755,110 +787,119 @@ -

The ArgL parameter is a list of options which have - the following meanings:

- +

Parameter ArgL is a list of the following + options:

+ + {name, Log} -

{name, Log} specifies the name of the log. - This is the name which must be passed on as a parameter in +

Specifies the log name. + This name must be passed on as a parameter in all subsequent logging operations. A name must always be supplied.

+ {file, FileName} -

{file, FileName} specifies the name of the - file which will be used for logged terms. If this value is - omitted and the name of the log is either an atom or a string, - the file name will default to lists:concat([Log, ".LOG"]) for halt logs. For wrap logs, this will be - the base name of the files. Each file in a wrap log - will be called .N]]>, where N is an - integer. Each wrap log will also have two files called +

Specifies the name of the + file to be used for logged terms. If this value is + omitted and the log name is an atom or a string, + the filename defaults to lists:concat([Log, ".LOG"]) + for halt logs.

+

For wrap logs, this is the base name of the files. Each file in + a wrap log is called .N]]>, where N + is an integer. Each wrap log also has two files called .idx]]> and .siz]]>.

+ {linkto, LinkTo} -

{linkto, LinkTo}. -If - LinkTo is a pid, that pid becomes an owner of the - log. If LinkTo is none the log records +

If LinkTo is a pid, it becomes an owner of the + log. If LinkTo is none, the log records that it is used anonymously by some process by incrementing the users counter. By default, the - process which calls open/1 owns the log. + process that calls open/1 owns the log.

+ {repair, Repair} -

{repair, Repair}. If Repair is true, - the current log file will be repaired, if needed. As the +

If Repair is true, + the current log file is repaired, if needed. As the restoration is initiated, a message is output on the error log. - If false is given, - no automatic repair will be attempted. Instead, the + If false is specified, + no automatic repair is attempted. Instead, the tuple {error, {need_repair, Log}} is returned if an attempt is made to open a corrupt log file. - If truncate is given, the log file will - be truncated, creating an empty log. Default is + If truncate is specified, the log file becomes + truncated, creating an empty log. Defaults to true, which has no effect on logs opened in read-only mode.

+ {type, Type} -

{type, Type} is the type of the log. Default - is halt. +

The log type. Defaults to halt.

+ {format, Format} -

{format, Format} specifies the format of the - disk log. Default is internal. +

Disk log format. Defaults to internal.

+ {size, Size} -

{size, Size} specifies the size of the log. - When a halt log has reached its maximum size, all attempts to - log more items are rejected. The default size is +

Log size.

+

When a halt log has reached its maximum size, all attempts to + log more items are rejected. Defaults to infinity, which for halt implies that there is no - maximum size. For wrap logs, the Size parameter - may be either a pair - {MaxNoBytes, MaxNoFiles} or infinity. In the - latter case, if the files of an already existing wrap log + maximum size.

+

For wrap logs, parameter Size + can be a pair + {MaxNoBytes, MaxNoFiles} or + infinity. + In the latter case, if the files of an existing wrap log with the same name can be found, the size is read - from the existing wrap log, otherwise an error is returned. - Wrap logs write at most MaxNoBytes bytes on each file - and use MaxNoFiles files before starting all over with - the first wrap log file. Regardless of MaxNoBytes, + from the existing wrap log, otherwise an error is returned.

+

Wrap logs write at most MaxNoBytes + bytes on each file and use MaxNoFiles + files before starting all over with the first wrap log + file. Regardless of MaxNoBytes, at least the header (if there is one) and one - item is written on each wrap log file before - wrapping to the next file. - When opening an existing wrap log, it is not - necessary to supply a value for the option Size, but any - supplied value must equal the current size of the log, otherwise - the tuple {error, {size_mismatch, CurrentSize, NewSize}} - is returned. -

+ item are written on each wrap log file before + wrapping to the next file.

+

When opening an existing wrap log, it is not + necessary to supply a value for option Size, but any + supplied value must equal the current log size, otherwise + the tuple {error, {size_mismatch, CurrentSize, + NewSize}} is returned.

+ {distributed, Nodes} -

{distributed, Nodes}. This option can be used for - adding members to a distributed disk log. The - default value is [], which means that +

This option can be used for + adding members to a distributed disk log. + Defaults to [], which means that the log is local on the current node.

+ {notify, boolean()} - -

{notify, bool()}. If true, the owners of the - log are notified when certain events occur in the log. - Default is false. The owners are sent one of the +

If true, the log owners + are notified when certain log events occur. + Defaults to false. The owners are sent one of the following messages when an event occurs:

- + + {disk_log, Node, Log, {wrap, NoLostItems}} -

{disk_log, Node, Log, {wrap, NoLostItems}} is sent when a wrap log has +

Sent when a wrap log has filled up one of its files and a new file is opened. NoLostItems is the number of - previously logged items that have been lost when + previously logged items that were lost when truncating existing files.

+ {disk_log, Node, Log, {truncated, NoLostItems}} -

{disk_log, Node, Log, {truncated, NoLostItems}} is sent when a log has been +

Sent when a log is truncated or reopened. For halt logs NoLostItems is the number of items written on the log since the disk log process was created. For wrap logs @@ -866,127 +907,132 @@ If wrap log files.

+ {disk_log, Node, Log, {read_only, Items}} -

{disk_log, Node, Log, {read_only, Items}} - is sent when an asynchronous log attempt is made to +

Sent when an asynchronous log attempt is made to a log file opened in read-only mode. Items is the items from the log attempt.

+ {disk_log, Node, Log, {blocked_log, Items}} -

{disk_log, Node, Log, {blocked_log, Items}} - is sent when an asynchronous log attempt is made to +

Sent when an asynchronous log attempt is made to a blocked log that does not queue log attempts. Items is the items from the log attempt.

+ {disk_log, Node, Log, {format_external, Items}} -

{disk_log, Node, Log, {format_external, Items}} - is sent when alog/2 or alog_terms/2 is +

Sent when function alog/2 or alog_terms/2 is used for internally formatted logs. Items is the items from the log attempt.

+ {disk_log, Node, Log, full} -

{disk_log, Node, Log, full} is sent when +

Sent when an attempt to log items to a wrap log would write more - bytes than the limit set by the size option. + bytes than the limit set by option size.

+ {disk_log, Node, Log, {error_status, Status}} -

{disk_log, Node, Log, {error_status, Status}} - is sent when the error status changes. The error status +

Sent when the error status changes. The error status is defined by the outcome of the last attempt to log - items to a the log or to truncate the log or the last - use of sync/1, inc_wrap_file/1 or - change_size/2. Status is one of ok and - {error, Error}, the former being the initial value. + items to the log, or to truncate the log, or the last + use of function sync/1, inc_wrap_file/1, or + change_size/2. Status is either ok or + {error, Error}, the former is the initial value.

-
+
+ {head, Head} -

{head, Head} specifies a header to be +

Specifies a header to be written first on the log file. If the log is a wrap log, the item Head is written first in each new file. - Head should be a term if the format is - internal, and a deep list of bytes (or a binary) - otherwise. Default is none, which means that + Head is to be a term if the format is + internal, otherwise a deep list of bytes (or a binary). + Defaults to none, which means that no header is written first on the file.

+ {head_func, {M,F,A}} -

{head_func, {M,F,A}} specifies a function +

Specifies a function to be called each time a new log file is opened. The call M:F(A) is assumed to return {ok, Head}. The item Head is written first in each file. - Head should be a term if the format is - internal, and a deep list of bytes (or a binary) - otherwise. + Head is to be a term if the format is + internal, otherwise a deep list of bytes (or a binary).

+ {mode, Mode} -

{mode, Mode} specifies if the log is to be - opened in read-only or read-write mode. It defaults to +

Specifies if the log is to be + opened in read-only or read-write mode. Defaults to read_write.

-
-

The open/1 function returns {ok, Log} if the - log file was successfully opened. If the file was - successfully repaired, the tuple {repaired, Log, {recovered, Rec}, {badbytes, Bad}} is returned, where - Rec is the number of whole Erlang terms found in the - file and Bad is the number of bytes in the file which - were non-Erlang terms. If the distributed parameter - was given, open/1 returns a list of + +

open/1 returns {ok, Log} if the + log file is successfully opened. If the file is + successfully repaired, the tuple {repaired, Log, + {recovered, Rec}, {badbytes, Bad}} + is returned, where Rec is the number of + whole Erlang terms found in the file and Bad + is the number of bytes in the file that + are non-Erlang terms. If the parameter distributed + is specified, open/1 returns a list of successful replies and a list of erroneous replies. Each reply is tagged with the node name.

When a disk log is opened in read-write mode, any existing - log file is checked for. If there is none a new empty + log file is checked for. If there is none, a new empty log is created, otherwise the existing file is opened at the position after the last logged item, and the logging of items - will commence from there. If the format is internal + starts from there. If the format is internal and the existing file is not recognized as an internally - formatted log, a tuple {error, {not_a_log_file, FileName}} + formatted log, a tuple + {error, {not_a_log_file, FileName}} is returned.

-

The open/1 function cannot be used for changing the - values of options of an already open log; when there are prior +

open/1 cannot be used for changing the + values of options of an open log. When there are prior owners or users of a log, all option values except name, - linkto and notify are just checked against - the values that have been supplied before as option values - to open/1, change_header/2, change_notify/3 - or change_size/2. As a consequence, + linkto, and notify are only checked against + the values supplied before as option values + to function open/1, change_header/2, change_notify/3, + or change_size/2. Thus, none of the options except name is mandatory. If some - given value differs from the current value, a tuple + specified value differs from the current value, a tuple {error, {arg_mismatch, OptionName, CurrentValue, Value}} - is returned. Caution: an owner's attempt to open a log - as owner once again is acknowledged with the return value + is returned.

+

If an owner attempts to open a log + as owner once again, it is acknowledged with the return value {ok, Log}, but the state of the disk log is not - affected in any way. -

-

If a log with a given name is local on some node, + affected.

+

If a log with a specified name is local on some node, and one tries to open the log distributed on the same node, - then the tuple {error, {node_already_open, Log}} is + the tuple {error, {node_already_open, Log}} is returned. The same tuple is returned if the log is distributed on some node, and one tries to open the log locally on the same node. Opening individual distributed disk logs for the first time adds those logs to a (possibly empty) distributed disk log. - The option values supplied are used - on all nodes mentioned by the distributed option. + The supplied option values are used + on all nodes mentioned by option distributed. Individual distributed logs know nothing about each other's option values, so each node can be given unique option values by creating a distributed - log with several calls to open/1. + log with many calls to open/1.

-

It is possible to open a log file more than once by giving - different values to the option name or by using the +

A log file can be opened more than once by giving + different values to option name or by using the same file when distributing a log on different nodes. - It is up to the user of the disk_log - module to ensure that no more than one - disk log process has write access to any file, or the - the file may be corrupted. + It is up to the user of module disk_log + to ensure that not more than one disk log process has write + access to any file, otherwise the file can be corrupted.

If an attempt to open a log file for the first time fails, the disk log process terminates with the EXIT message @@ -999,9 +1045,9 @@ If Return the name of the disk log handled by a pid. -

The pid2name/1 function returns the name of the log +

Returns the log name given the pid of a disk log process on the current node, or - undefined if the given pid is not a disk log process. + undefined if the specified pid is not a disk log process.

This function is meant to be used for debugging only.

@@ -1018,25 +1064,25 @@ If -

The reopen functions first rename the log file - to File and then re-create a new log file. - In case of a wrap log, File is used as the base name +

Renames the log file + to File and then recreates a new log file. + If a wrap log exists, File is used as the base name of the renamed files. By default the header given to open/1 is written first in - the newly opened log file, but if the Head or the - BHead argument is given, this item is used instead. - The header argument is used once only; next time a wrap log file + the newly opened log file, but if argument Head or + BHead is specified, this item is used instead. + The header argument is used only once. Next time a wrap log file is opened, the header given to open/1 is used.

-

The reopen/2,3 functions are used for internally formatted +

reopen/2,3 are used for internally formatted logs, and breopen/3 for externally formatted logs.

-

The owners that subscribe to notifications will receive +

Owners subscribing to notifications receive a truncate message.

Upon failure to reopen the log, the disk log process terminates - with the EXIT message {{failed,Error},[{disk_log,Fun,Arity}]}, - and other processes that have requests queued receive the message + with the EXIT message {{failed,Error},[{disk_log,Fun,Arity}]}. + Other processes having requests queued receive the message {disk_log, Node, {error, disk_log_stopped}}.

@@ -1046,8 +1092,7 @@ If Flush the contents of a disk log to the disk. -

The sync/1 function ensures that the contents of the - log are actually written to the disk. +

Ensures that the contents of the log are written to the disk. This is usually a rather expensive operation.

@@ -1062,24 +1107,24 @@ If -

The truncate functions remove all items from a disk log. - If the Head or the BHead argument is - given, this item is written first in the newly truncated +

Removes all items from a disk log. + If argument Head or BHead is + specified, this item is written first in the newly truncated log, otherwise the header given to open/1 is used. - The header argument is only used once; next time a wrap log file + The header argument is used only once. Next time a wrap log file is opened, the header given to open/1 is used.

-

The truncate/1,2 functions are used for internally +

truncate/1,2 are used for internally formatted logs, and btruncate/2 for externally formatted logs.

-

The owners that subscribe to notifications will receive +

Owners subscribing to notifications receive a truncate message.

If the attempt to truncate the log fails, the disk log process terminates with the EXIT message - {{failed,Reason},[{disk_log,Fun,Arity}]}, and - other processes that have requests queued receive the message + {{failed,Reason},[{disk_log,Fun,Arity}]}. + Other processes having requests queued receive the message {disk_log, Node, {error, disk_log_stopped}}.

@@ -1089,7 +1134,7 @@ If Unblock a disk log. -

The unblock/1 function unblocks a log. +

Unblocks a log. A log can only be unblocked by the blocking process.

@@ -1098,8 +1143,8 @@ If
See Also -

file(3), - pg2(3), - wrap_log_reader(3)

+

file(3), + pg2(3), + wrap_log_reader(3)

diff --git a/lib/kernel/doc/src/erl_boot_server.xml b/lib/kernel/doc/src/erl_boot_server.xml index a8015fa453..ac4c97b43a 100644 --- a/lib/kernel/doc/src/erl_boot_server.xml +++ b/lib/kernel/doc/src/erl_boot_server.xml @@ -29,72 +29,73 @@ erl_boot_server - Boot Server for Other Erlang Machines + Boot server for other Erlang machines. -

This server is used to assist diskless Erlang nodes which fetch +

This server is used to assist diskless Erlang nodes that fetch all Erlang code from another machine.

This server is used to fetch all code, including the start script, if an Erlang runtime system is started with - the -loader inet command line flag. All hosts specified - with the -hosts Host command line flag must have one + command-line flag -loader inet. All hosts specified + with command-line flag -hosts Host must have one instance of this server running.

-

This server can be started with the kernel configuration +

This server can be started with the Kernel configuration parameter start_boot_server.

-

The erl_boot_server can both read regular files as well as - files in archives. See code(3) - and erl_prim_loader(3).

-

The support for loading of code from archive files is - experimental. The sole purpose of releasing it before it is ready - is to obtain early feedback. The file format, semantics, - interfaces etc. may be changed in a future release.

+

The erl_boot_server can read regular files and + files in archives. See code(3) + and + erl_prim_loader(3) + in ERTS.

+

The support for loading code from archive files is + experimental. It is released before it is ready + to obtain early feedback. The file format, semantics, + interfaces, and so on, can be changed in a future release.

- - Start the boot server + + Add a slave to the list of allowed slaves. -

Starts the boot server. Slaves is a list of IP - addresses for hosts which are allowed to use this server as a - boot server.

+

Adds a Slave node to the list of allowed slave hosts.

- - Start the boot server and links the caller + + Delete a slave from the list of allowed slaves. -

Starts the boot server and links to the caller. This function - is used to start the server if it is included in a supervision - tree.

+

Deletes a Slave node from the list of allowed slave + hosts.

- - Add a slave to the list of allowed slaves + + Start the boot server. -

Adds a Slave node to the list of allowed slave hosts.

+

Starts the boot server. Slaves is a list of + IP addresses for hosts, which are allowed to use this server as a + boot server.

- - Delete a slave from the list of allowed slaves + + Start the boot server and link to the the caller. -

Deletes a Slave node from the list of allowed slave - hosts.

+

Starts the boot server and links to the caller. This function + is used to start the server if it is included in a supervision + tree.

- Return the current list of allowed slave hosts + Return the current list of allowed slave hosts.

Returns the current list of allowed slave hosts.

-
SEE ALSO -

init(3), - erl_prim_loader(3)

+

erts:init(3), + erts:erl_prim_loader(3)

diff --git a/lib/kernel/doc/src/erl_ddll.xml b/lib/kernel/doc/src/erl_ddll.xml index 8d71883cf4..1f8a3ba20e 100644 --- a/lib/kernel/doc/src/erl_ddll.xml +++ b/lib/kernel/doc/src/erl_ddll.xml @@ -29,84 +29,91 @@ erl_ddll - Dynamic Driver Loader and Linker + Dynamic driver loader and linker. -

The erl_ddll module provides an interface for loading - and unloading erlang linked in drivers in runtime.

+

This module provides an interface for loading + and unloading Erlang linked-in drivers in runtime.

-

This is a large reference document. For casual use of the - module, as well as for most real world applications, the - descriptions of the functions load/2 and unload/1 are enough to get - going.

+

This is a large reference document. For casual use of this + module, and for most real world applications, the + descriptions of functions + load/2 and + unload/1 + are enough to getting started.

-

The driver should be provided as a dynamically linked library - in a object code format specific for the platform in use, - i. e. .so files on most Unix systems and .ddl - files on windows. An erlang linked in driver has to provide +

The driver is to be provided as a dynamically linked library + in an object code format specific for the platform in use, + that is, .so files on most Unix systems and .ddl + files on Windows. An Erlang linked-in driver must provide specific interfaces to the emulator, so this module is not - designed for loading arbitrary dynamic libraries. For further - information about erlang drivers, refer to the ERTS reference - manual section erl_driver.

+ designed for loading arbitrary dynamic libraries. For more + information about Erlang drivers, see + erts:erl_driver + .

-

When describing a set of functions, (i.e. a module, a part of a - module or an application) executing in a process and wanting to - use a ddll-driver, we use the term user. There can be - several users in one process (different modules needing the same - driver) and several processes running the same code, making up - several users of a driver. In the basic scenario, each - user loads the driver before starting to use it and unloads the - driver when done. The reference counting keeps track of - processes as well as the number of loads by each process, so that - the driver will only be unloaded when no one wants it - (it has no user). The driver also keeps track of ports that are - opened towards it, so that one can delay unloading until all - ports are closed or kill all ports using the driver when it is - unloaded.

+

When describing a set of functions (that is, a module, a part of a + module, or an application), executing in a process and wanting to + use a ddll-driver, we use the term user. A process can + have many users (different modules needing the same + driver) and many processes running the same code, making up + many users of a driver.

+

In the basic scenario, each user loads the driver before + starting to use it and unloads the driver when done. + The reference counting keeps track of + processes and the number of loads by each process. This way + the driver is only unloaded when no one wants it (it has no user). + The driver also keeps track of ports that are + opened to it. This enables delay of unloading until all + ports are closed, or killing of all ports that use the driver when + it is unloaded.

The interface supports two basic scenarios of loading and unloading. Each scenario can also have the option of either killing ports when the driver is unloading, or waiting for the - ports to close themselves. The scenarios are:

+ ports to close themselves. The scenarios are as follows:

- Load and unload on a "when needed basis" + Load and Unload on a "When Needed Basis"

This (most common) scenario simply supports that each user of the driver loads - it when it is needed and unloads it when the user no longer have any use for - it. The driver is always reference counted and as long as a + it when needed and unloads it when no longer needed. + The driver is always reference counted and as long as a process keeping the driver loaded is still alive, the driver is present in the system.

Each user of the driver use literally the same pathname for the driver when - demanding load, but the users are not really concerned - with if the driver is already loaded from the filesystem or - if the object code has to be loaded from filesystem.

-

Two pairs of functions support this scenario:

+ demanding load, but the + users are not concerned + with if the driver is already loaded from the file system or + if the object code must be loaded from file system.

+

The following two pairs of functions support this scenario:

load/2 and unload/1

When using the load/unload interfaces, the - driver will not actually get unloaded until the - last port using the driver is closed. The function - unload/1 can return immediately, as the users are not really concerned - with when the actual unloading occurs. The - driver will actually get unloaded when no one needs it any longer.

-

If a process having the driver loaded dies, it will have - the same effect as if unloading was done.

-

When loading, the function load/2 returns - ok as soon as there is any instance of the driver - present, so that if a driver is waiting to get unloaded - (due to open ports), it will simply change state to no + driver is not unloaded until the + last port using the driver is closed. Function + unload/1 can return immediately, as the + users + have no interrest in when the unloading occurs. The + driver is unloaded when no one needs it any longer.

+

If a process having the driver loaded dies, it has + the same effect as if unloading is done.

+

When loading, function load/2 returns + ok when any instance of the driver is + present. Thus, if a driver is waiting to get unloaded + (because of open ports), it simply changes state to no longer need unloading.

load_driver/2 and unload_driver/1 -

These interfaces is intended to be used when it is considered an - error that ports are open towards a driver that no user - has loaded. The ports still open when the +

These interfaces are intended to be used when it is considered an + error that ports are open to a driver that no + user + has loaded. The ports that are still open when the last user calls unload_driver/1 or when the last process having the - driver loaded dies, will get killed with reason + driver loaded dies, are killed with reason driver_unloaded.

The function names load_driver and unload_driver are kept for backward @@ -114,60 +121,66 @@ - Loading and reloading for code replacement + Loading and Reloading for Code Replacement -

This scenario occurs when the driver code might need +

This scenario can occur if the driver code needs replacement during operation of the Erlang - emulator. Implementing driver code replacement is somewhat - more tedious than beam code replacement, as one driver - cannot be loaded as both "old" and "new" code. All users of a driver must have it + emulator. Implementing driver code replacement is a little + more tedious than Beam code replacement, as one driver + cannot be loaded as both "old" and "new" code. All + users of a driver must have it closed (no open ports) before the old code can be unloaded and the new code can be loaded.

-

The actual unloading/loading is done as one atomic +

The unloading/loading is done as one atomic operation, blocking all processes in the system from using - the driver concerned while in progress.

+ the driver in question while in progress.

The preferred way to do driver code replacement is to let one single process keep track of the driver. When - the process start, the driver is loaded. When replacement + the process starts, the driver is loaded. When replacement is required, the driver is reloaded. Unload is probably never - done, or done when the process exits. If more than one user has a driver loaded when code - replacement is demanded, the replacement cannot occur until - the last "other" user has + done, or done when the process exits. If more than one + user has a driver + loaded when code replacement is demanded, the replacement cannot + occur until the last "other" + user has unloaded the driver.

Demanding reload when a reload is already in progress is - always an error. Using the high level functions, it is also - an error to demand reloading when more than one user has the driver loaded. To - simplify driver replacement, avoid designing your system so - that more than than one user has the driver loaded.

-

The two functions for reloading drivers should be used - together with corresponding load functions, to support the two + always an error. Using the high-level functions, it is also + an error to demand reloading when more than one + user has the driver loaded.

+

To simplify driver replacement, avoid designing your system so + that more than one + user has the driver loaded.

+

The two functions for reloading drivers are to be used + together with corresponding load functions to support the two different behaviors concerning open ports:

load/2 and reload/2 -

This pair of functions is used when reloading should be - done after the last open port towards the driver is +

This pair of functions is used when reloading is to be + done after the last open port to the driver is closed.

-

As reload/2 actually waits for the reloading to - occur, a misbehaving process keeping open ports towards - the driver (or keeping the driver loaded) might cause - infinite waiting for reload. Timeouts has to be provided +

As reload/2 waits for the reloading to + occur, a misbehaving process keeping open ports to + the driver (or keeping the driver loaded) can cause + infinite waiting for reload. Time-outs must be provided outside of the process demanding the reload or by using - the low-level interface try_load/3 in combination - with driver monitors (see below).

+ the low-level interface + try_load/3 + in combination with driver monitors.

load_driver/2 and reload_driver/2 -

This pair of functions are used when open ports towards - the driver should be killed with reason +

This pair of functions are used when open ports to + the driver are to be killed with reason driver_unloaded to allow for new driver code to get loaded.

-

If, however, another process has the driver loaded, - calling reload_driver returns the error code +

However, if another process has the driver loaded, + calling reload_driver returns error code pending_process. As stated earlier, - the recommended design is to not allow other users than the "driver - reloader" to actually demand loading of the concerned - driver.

+ the recommended design is to not allow other + users than the "driver + reloader" to demand loading of the driver in question.

@@ -184,903 +197,982 @@ - Remove a monitor for a driver + Remove a monitor for a driver.

Removes a driver monitor in much the same way as - erlang:demonitor/1 does with process - monitors. See monitor/2, try_load/3 and try_unload/2 for details - about how to create driver monitors.

+ erlang:demonitor/1 + in ERTS + does with process monitors. For details about how to create + driver monitors, see + monitor/2, + try_load/3, and + try_unload/2.

The function throws a badarg exception if the - parameter is not a reference().

+ parameter is not a reference().

+
+
+ + + Format an error descriptor. + +

Takes an ErrorDesc returned by load, unload, or + reload functions and returns a string that + describes the error or warning.

+ +

Because of peculiarities in the dynamic loading interfaces on + different platforms, the returned string is only guaranteed + to describe the correct error if format_error/1 is called + in the same instance of the Erlang virtual machine as the error + appeared in (meaning the same operating + system process).

+
- Retrieve information about all drivers + Retrieve information about all drivers. -

Returns a list of tuples {DriverName, InfoList}, where - InfoList is the result of calling info/1 for that - DriverName. Only dynamically linked in drivers are +

Returns a list of tuples {DriverName, InfoList}, + where InfoList is the result of calling + info/1 for that + DriverName. Only dynamically linked-in drivers are included in the list.

- Retrieve information about one driver + Retrieve information about one driver. -

Returns a list of tuples {Tag, Value}, where - Tag is the information item and Value is the result - of calling info/2 with this driver name and - this tag. The result being a tuple list containing all - information available about a driver.

-

The different tags that will appear in the list are:

+

Returns a list of tuples {Tag, Value}, + where Tag is the information item and + Value is the result of calling + info/2 with this driver + name and this tag. The result is a tuple list containing all information + available about a driver.

+

The following tags appears in the list:

- processes - driver_options - port_count - linked_in_driver - permanent - awaiting_load - awaiting_unload + processes + driver_options + port_count + linked_in_driver + permanent + awaiting_load + awaiting_unload -

For a detailed description of each value, please read the - description of info/2 below.

+

For a detailed description of each value, see + info/2.

The function throws a badarg exception if the driver is not present in the system.

- Retrieve specific information about one driver + Retrieve specific information about one driver. -

This function returns specific information about one aspect - of a driver. The Tag parameter specifies which aspect - to get information about. The Value return differs +

Returns specific information about one aspect of a driver. + Parameter Tag specifies which aspect + to get information about. The return Value differs between different tags:

- processes + processes -

Return all processes containing users of the specific drivers - as a list of tuples {pid(),integer() >= 0}, where the - integer() denotes the number of users in the process +

Returns all processes containing + users of the specific drivers + as a list of tuples {pid(),integer() >= 0}, where + integer() denotes the number of users in process pid().

- driver_options + driver_options -

Return a list of the driver options provided when - loading, as well as any options set by the driver itself - during initialization. The currently only valid option - being kill_ports.

+

Returns a list of the driver options provided when + loading, and any options set by the driver + during initialization. The only valid option + is kill_ports.

- port_count + port_count -

Return the number of ports (an integer >= 0()) using the driver.

+

Returns the number of ports (an integer() >= 0) + using the driver.

- linked_in_driver + linked_in_driver -

Return a boolean(), being true if the driver is a - statically linked in one and false otherwise.

+

Returns a boolean(), which is true if the driver is a + statically linked-in one, otherwise false.

- permanent + permanent -

Return a boolean(), being true if the driver has made - itself permanent (and is not a statically - linked in driver). false otherwise.

+

Returns a boolean(), which is true if the driver has + made itself permanent (and is not a statically + linked-in driver), otherwise false.

- awaiting_load + awaiting_load -

Return a list of all processes having monitors for - loading active, each process returned as - {pid(),integer() >= 0}, where the integer() is the - number of monitors held by the process pid().

+

Returns a list of all processes having monitors for + loading active. Each process is returned as + {pid(),integer() >= 0}, where integer() is the + number of monitors held by process pid().

- awaiting_unload + awaiting_unload -

Return a list of all processes having monitors for - unloading active, each process returned as - {pid(),integer() >= 0}, where the integer() is the - number of monitors held by the process pid().

+

Returns a list of all processes having monitors for + unloading active. Each process is returned as + {pid(),integer() >= 0}, where integer() is the + number of monitors held by process pid().

-

If the options linked_in_driver or permanent - return true, all other options will return the value - linked_in_driver or permanent respectively.

+

If option linked_in_driver or permanent + returns true, all other options return + linked_in_driver or permanent, respectively.

The function throws a badarg exception if the driver - is not present in the system or the tag is not supported.

+ is not present in the system or if the tag is not supported.

- Load a driver + Load a driver. -

Loads and links the dynamic driver Name. Path +

Loads and links the dynamic driver Name. + Path is a file path to the directory containing the driver. Name must be a sharable object/dynamic library. Two drivers with different Path parameters cannot be - loaded under the same name. The Name is a string or + loaded under the same name. Name is a string or atom containing at least one character.

-

The Name given should correspond to the filename - of the actual dynamically loadable object file residing in - the directory given as Path, but without the - extension (i.e. .so). The driver name provided in +

The Name specified is to correspond to the filename + of the dynamically loadable object file residing in + the directory specified as Path, but without the + extension (that is, .so). The driver name provided in the driver initialization routine must correspond with the - filename, in much the same way as erlang module names + filename, in much the same way as Erlang module names correspond to the names of the .beam files.

-

If the driver has been previously unloaded, but is still - present due to open ports against it, a call to - load/2 will stop the unloading and keep the driver - (as long as the Path is the same) and ok is - returned. If one actually wants the object code to be - reloaded, one uses reload/2 or the low-level - interface try_load/3 - instead. Please refer to the description of different scenarios for +

If the driver was previously unloaded, but is still + present because of open ports to it, a call to + load/2 stops the unloading and keeps the driver + (as long as Path is the same), and ok is + returned. If you really want the object code to be + reloaded, use reload/2 + or the low-level interface + try_load/3 instead. + See also the description of + different scenarios for loading/unloading in the introduction.

If more than one process tries to load an already loaded - driver withe the same Path, or if the same process - tries to load it several times, the function will return - ok. The emulator will keep track of the + driver with the same Path, or if the same process + tries to load it many times, the function returns + ok. The emulator keeps track of the load/2 calls, so that a corresponding number of - unload/2 calls will have to be done from the same - process before the driver will actually get unloaded. It is + unload/2 calls must be done from the same + process before the driver gets unloaded. It is therefore safe for an application to load a driver that is shared between processes or applications when needed. It can safely be unloaded without causing trouble for other - parts of the system.

-

It is not allowed to load - several drivers with the same name but with different - Path parameters.

+ parts of the system.

+

It is not allowed to load multiple drivers with + the same name but with different Path parameters.

-

Note especially that the Path is interpreted - literally, so that all loaders of the same driver needs to - give the same literalPath string, even - though different paths might point out the same directory - in the filesystem (due to use of relative paths and +

Path is interpreted + literally, so that all loaders of the same driver must + specify the same literal Path string, + although different paths can point out the same directory + in the file system (because of use of relative paths and links).

On success, the function returns ok. On failure, the return value is {error,ErrorDesc}, where ErrorDesc is an opaque term to be - translated into human readable form by the format_error/1 - function.

-

For more control over the error handling, again use the - try_load/3 + translated into human readable form by function + format_error/1.

+

For more control over the error handling, use the + try_load/3 interface instead.

The function throws a badarg exception if the - parameters are not given as described above.

+ parameters are not specified as described here.

- Load a driver + Load a driver. -

Works essentially as load/2, but will load the driver - with other options. All ports that are using the - driver will get killed with the reason - driver_unloaded when the driver is to be unloaded.

-

The number of loads and unloads by different users influence the actual loading - and unloading of a driver file. The port killing will - therefore only happen when the last user unloads the driver, or the - last process having loaded the driver exits.

+

Works essentially as load/2, but loads the driver + with other options. All ports using the + driver are killed with reason driver_unloaded + when the driver is to be unloaded.

+

The number of loads and unloads by different + users influences the loading + and unloading of a driver file. The port killing + therefore only occurs when the last + user unloads the driver, + or when the last process having loaded the driver exits.

This interface (or at least the name of the functions) is - kept for backward compatibility. Using try_load/3 with - {driver_options,[kill_ports]} in the option list will - give the same effect regarding the port killing.

+ kept for backward compatibility. + Using try_load/3 with + {driver_options,[kill_ports]} in the option list + gives the same effect regarding the port killing.

The function throws a badarg exception if the - parameters are not given as described above.

+ parameters are not specified as described here.

+
+
+ + + List loaded drivers. + +

Returns a list of all the available drivers, both + (statically) linked-in and dynamically loaded ones.

+

The driver names are returned as a list of strings rather + than a list of atoms for historical reasons.

+

For more information about drivers, see + info.

- Create a monitor for a driver + Create a monitor for a driver. -

This function creates a driver monitor and works in many - ways as the function erlang:monitor/2, +

Creates a driver monitor and works in many + ways as + erlang:monitor/2 + in ERTS, does for processes. When a driver changes state, the monitor - results in a monitor-message being sent to the calling - process. The MonitorRef returned by this function is + results in a monitor message that is sent to the calling + process. MonitorRef returned by this function is included in the message sent.

-

As with process monitors, each driver monitor set will only - generate one single message. The monitor is - "destroyed" after the message is sent and there is then no - need to call demonitor/1.

-

The MonitorRef can also be used in subsequent calls - to demonitor/1 to +

As with process monitors, each driver monitor set only + generates one single message. The monitor is + "destroyed" after the message is sent, so it is then not + needed to call + demonitor/1.

+

MonitorRef can also be used in subsequent calls + to demonitor/1 to remove a monitor.

The function accepts the following parameters:

- Tag + Tag -

The monitor tag is always driver as this function +

The monitor tag is always driver, as this function can only be used to create driver monitors. In the future, driver monitors will be integrated with process monitors, - why this parameter has to be given for consistence.

+ why this parameter has to be specified for consistence.

- Item + Item -

The Item parameter specifies which driver one - wants to monitor (the name of the driver) as well as - which state change one wants to monitor. The parameter +

Parameter Item specifies + which driver to monitor (the driver name) and + which state change to monitor. The parameter is a tuple of arity two whose first element is the - driver name and second element is either of:

+ driver name and second element is one of the following:

- loaded + loaded -

Notify me when the driver is reloaded (or loaded if +

Notifies when the driver is reloaded (or loaded if loading is underway). It only makes sense to monitor drivers that are in the process of being loaded or - reloaded. One cannot monitor a future-to-be driver - name for loading, that will only result in a - 'DOWN' message being immediately sent. + reloaded. A future driver name for loading cannot be + monitored. That only results in a + DOWN message sent immediately. Monitoring for loading is therefore most useful when - triggered by the try_load/3 function, + triggered by function + try_load/3, where the monitor is created because the driver is in such a pending state.

-

Setting a driver monitor for loading will - eventually lead to one of the following messages +

Setting a driver monitor for loading + eventually leads to one of the following messages being sent:

- {'UP', reference(), driver, Name, loaded} + {'UP', reference(), driver, Name, loaded} -

This message is sent, either immediately if the +

This message is sent either immediately if the driver is already loaded and no reloading is pending, or when reloading is executed if reloading is pending.

The user is - expected to know if reloading is demanded prior - to creating a monitor for loading.

+ expected to know if reloading is demanded before + creating a monitor for loading.

- {'UP', reference(), driver, Name, permanent} + {'UP', reference(), driver, Name, permanent} -

This message will be sent if reloading was +

This message is sent if reloading was expected, but the (old) driver made itself - permanent prior to reloading. It will also be + permanent before reloading. It is also sent if the driver was permanent or statically - linked in when trying to create the monitor.

+ linked-in when trying to create the monitor.

- {'DOWN', reference(), driver, Name, load_cancelled} + {'DOWN', reference(), driver, Name, load_cancelled} -

This message will arrive if reloading was - underway, but the user having requested - reload cancelled it by either dying or calling - try_unload/2 +

This message arrives if reloading was + underway, but the requesting + user + cancelled it by dying or calling + try_unload/2 (or unload/1/unload_driver/1) again before it was reloaded.

- {'DOWN', reference(), driver, Name, {load_failure, Failure}} + {'DOWN', reference(), driver, Name, {load_failure, Failure}} -

This message will arrive if reloading was +

This message arrives if reloading was underway but the loading for some reason failed. The Failure term is one of the - errors that can be returned from try_load/3. The - error term can be passed to format_error/1 - for translation into human readable form. Note - that the translation has to be done in the same - running erlang virtual machine as the error + errors that can be returned from + try_load/3. + The error term can be passed to + format_error/1 + for translation into human readable form. Notice + that the translation must be done in the same + running Erlang virtual machine as the error was detected in.

- unloaded + unloaded -

Monitor when a driver gets unloaded. If one +

Monitors when a driver gets unloaded. If one monitors a driver that is not present in the system, - one will immediately get notified that the driver got + one immediately gets notified that the driver got unloaded. There is no guarantee that the driver was - actually ever loaded.

-

A driver monitor for unload will eventually result + ever loaded.

+

A driver monitor for unload eventually results in one of the following messages being sent:

- {'DOWN', reference(), driver, Name, unloaded} + {'DOWN', reference(), driver, Name, unloaded} -

The driver instance monitored is now - unloaded. As the unload might have been due to a - reload/2 request, the driver might once +

The monitored driver instance is now + unloaded. As the unload can be a result of a + reload/2 request, the driver can once again have been loaded when this message arrives.

- {'UP', reference(), driver, Name, unload_cancelled} + {'UP', reference(), driver, Name, unload_cancelled} -

This message will be sent if unloading was +

This message is sent if unloading was expected, but while the driver was waiting for - all ports to get closed, a new user of the driver - appeared and the unloading was cancelled.

-

This message appears when an {ok, pending_driver}) was returned from try_unload/2) - for the last user of the driver and - then a {ok, already_loaded} is returned - from a call to try_load/3.

-

If one wants to really monitor when the - driver gets unloaded, this message will distort - the picture, no unloading was really done. - The unloaded_only option creates a monitor - similar to an unloaded monitor, but does - never result in this message.

+ all ports to get closed, a new + user of the driver + appeared, and the unloading was cancelled.

+

This message appears if {ok, pending_driver} + was returned from + try_unload/2 + for the last user + of the driver, and then {ok, already_loaded} is returned + from a call to + try_load/3.

+

If one really wants to monitor when the + driver gets unloaded, this message distorts + the picture, because no unloading was done. + Option unloaded_only creates a monitor + similar to an unloaded monitor, but + never results in this message.

- {'UP', reference(), driver, Name, permanent} + {'UP', reference(), driver, Name, permanent} -

This message will be sent if unloading was +

This message is sent if unloading was expected, but the driver made itself - permanent prior to unloading. It will also be + permanent before unloading. It is also sent if trying to monitor a permanent or - statically linked in driver.

+ statically linked-in driver.

- unloaded_only + unloaded_only

A monitor created as unloaded_only behaves - exactly as one created as unloaded with the - exception that the {'UP', reference(), driver, Name, unload_cancelled} message will never be - sent, but the monitor instead persists until the - driver really gets unloaded.

+ exactly as one created as unloaded + except that the + {'UP', reference(), driver, Name, unload_cancelled} + message is never sent, but the monitor instead persists until + the driver really gets unloaded.

The function throws a badarg exception if the - parameters are not given as described above.

+ parameters are not specified as described here.

- Replace a driver + Replace a driver.

Reloads the driver named Name from a possibly - different Path than was previously used. This - function is used in the code change scenario described in the + different Path than previously used. This + function is used in the code change + scenario described in the introduction.

If there are other users - of this driver, the function will return {error, pending_process}, but if there are no more users, the - function call will hang until all open ports are closed.

+ of this driver, the function returns {error, pending_process}, + but if there are no other users, the function call hangs until all + open ports are closed.

-

Avoid mixing - several users - with driver reload requests.

-
-

If one wants to avoid hanging on open ports, one should use - the try_load/3 - function instead.

-

The Name and Path parameters have exactly the - same meaning as when calling the plain load/2 function.

- -

Avoid mixing - several users - with driver reload requests.

+

Avoid mixing multiple + users + with driver reload requests.

+

To avoid hanging on open ports, use function + try_load/3 + instead.

+

The Name and Path parameters + have exactly the same meaning as when calling the plain function + load/2.

+

On success, the function returns ok. On - failure, the function returns an opaque error, with the - exception of the pending_process error described - above. The opaque errors are to be translated into human - readable form by the format_error/1 function.

-

For more control over the error handling, again use the - try_load/3 + failure, the function returns an opaque error, + except the pending_process error described + earlier. The opaque errors are to be translated into human + readable form by function + format_error/1.

+

For more control over the error handling, use the + try_load/3 interface instead.

The function throws a badarg exception if the - parameters are not given as described above.

+ parameters are not specified as described here.

- Replace a driver + Replace a driver. -

Works exactly as reload/2, but for drivers - loaded with the load_driver/2 interface.

-

As this interface implies that ports are being killed when - the last user disappears, the function wont hang waiting for +

Works exactly as reload/2, + but for drivers loaded with the + load_driver/2 interface.

+

As this interface implies that ports are killed when + the last user disappears, the function does not hang waiting for ports to get closed.

-

For further details, see the scenarios in the module - description and refer to the reload/2 function description.

+

For more details, see + scenarios in this module + description and the function description for + reload/2.

The function throws a badarg exception if the - parameters are not given as described above.

+ parameters are not specified as described here.

- Load a driver + Load a driver. -

This function provides more control than the +

Provides more control than the load/2/reload/2 and load_driver/2/reload_driver/2 interfaces. It - will never wait for completion of other operations related - to the driver, but immediately return the status of the - driver as either:

+ never waits for completion of other operations related + to the driver, but immediately returns the status of the + driver as one of the following:

- {ok, loaded} + {ok, loaded} -

The driver was actually loaded and is immediately - usable.

+

The driver was loaded and is immediately usable.

- {ok, already_loaded} + {ok, already_loaded}

The driver was already loaded by another process - and/or is in use by a living port. The load by you is + or is in use by a living port, or both. The load by you is registered and a corresponding try_unload is expected sometime in the future.

- {ok, pending_driver}or {ok, pending_driver, reference()} + {ok, pending_driver}or {ok, pending_driver, reference()}

The load request is registered, but the loading is - delayed due to the fact that an earlier instance of the - driver is still waiting to get unloaded (there are open - ports using it). Still, unload is expected when you are - done with the driver. This return value will - mostly happen when the + delayed because an earlier instance of the + driver is still waiting to get unloaded (open + ports use it). Still, unload is expected when you are + done with the driver. This return value + mostly occurs when options {reload,pending_driver} or - {reload,pending} options are used, but - can happen when another user is unloading a driver in - parallel and the kill_ports driver option is - set. In other words, this return value will always need - to be handled!

+ {reload,pending} are used, but + can occur when another + user is unloading a + driver in parallel and driver option kill_ports is set. + In other words, this return value always needs + to be handled.

- {ok, pending_process}or {ok, pending_process, reference()} + {ok, pending_process}or {ok, pending_process, reference()}

The load request is registered, but the loading is - delayed due to the fact that an earlier instance of the + delayed because an earlier instance of the driver is still waiting to get unloaded by another user (not only by a port, in which case {ok,pending_driver} would have been returned). Still, unload is expected when you - are done with the driver. This return value will - only happen when the {reload,pending} - option is used.

+ are done with the driver. This return value + only occurs when option {reload,pending} + is used.

When the function returns {ok, pending_driver} or - {ok, pending_process}, one might want to get information - about when the driver is actually loaded. This can - be achieved by using the {monitor, MonitorOption} option.

-

When monitoring is requested, and a corresponding {ok, pending_driver} or {ok, pending_process} would be - returned, the function will instead return a tuple {ok, PendingStatus, reference()} and the process will, at a later - time when the driver actually gets loaded, get a monitor - message. The monitor message one can expect is described in - the monitor/2 - function description.

+ {ok, pending_process}, one can get information + about when the driver is actually loaded by using + option {monitor, MonitorOption}.

+

When monitoring is requested, and a corresponding + {ok, pending_driver} or {ok, pending_process} would + be returned, the function instead returns a tuple + {ok, PendingStatus, reference()} + and the process then gets a monitor message later, when the + driver gets loaded. The monitor message to expect is described in + the function description of + monitor/2.

-

Note that in case of loading, monitoring can - not only get triggered by using the {reload, ReloadOption} option, but also in special cases where - the load-error is transient, why {monitor, pending_driver} should be used under basically - all real world circumstances!

+

In case of loading, monitoring can not only get + triggered by using option {reload, ReloadOption}, + but also in special cases where the load error is transient. Thus, + {monitor, pending_driver} is to be used under basically + all real world circumstances.

The function accepts the following parameters:

- Path + Path -

The filesystem path to the directory where the driver - object file is situated. The filename of the object file +

The file system path to the directory where the driver + object file is located. The filename of the object file (minus extension) must correspond to the driver name - (used in the name parameter) and the driver must - identify itself with the very same name. The - Path might be provided as an iolist(), + (used in parameter Name) and the driver must + identify itself with the same name. + Path can be provided as an iolist(), meaning it can be a list of other iolist()s, characters - (eight bit integers) or binaries, all to be flattened + (8-bit integers), or binaries, all to be flattened into a sequence of characters.

The (possibly flattened) Path parameter must be - consistent throughout the system, a driver should, by + consistent throughout the system. A driver is to, by all users, be loaded - using the same literalPath. The - exception is when reloading is requested, in - which case the Path may be specified - differently. Note that all users trying to load the - driver at a later time will need to use the newPath if the Path is changed using a - reload option. This is yet another reason + using the same literal Path. + The exception is when reloading is requested, + in which case Path can be specified + differently. Notice that all + users trying to load the + driver later need to use the + new Path if Path + is changed using a reload option. This is yet another reason to have only one loader of a driver one wants to - upgrade in a running system!

+ upgrade in a running system.

- Name + Name -

The name parameter is the name of the driver to be used - in subsequent calls to open_port. The - name can be specified either as an iolist() or - as an atom(). The name given when loading is used - to find the actual object file (with the - help of the Path and the system implied - extension suffix, i.e. .so). The name by which - the driver identifies itself must also be consistent - with this Name parameter, much as a beam-file's - module name much correspond to its filename.

+

This parameter is the name of the driver + to be used in subsequent calls to function + erlang:open_port + in ERTS. + The name can be specified as an iolist() or + an atom(). The name specified when loading is used + to find the object file (with the help of Path + and the system-implied extension suffix, that is, .so). + The name by which the driver identifies itself must also be consistent + with this Name parameter, much as + the module name of a Beam file much corresponds to its filename.

- OptionList + OptionList -

A number of options can be specified to control the - loading operation. The options are given as a list of - two-tuples, the tuples having the following values and +

Some options can be specified to control the + loading operation. The options are specified as a list of + two-tuples. The tuples have the following values and meanings:

- {driver_options, DriverOptionList} + {driver_options, DriverOptionList} -

This option is to provide options that will change - its general behavior and will "stick" to the driver +

This is to provide options that changes + its general behavior and "sticks" to the driver throughout its lifespan.

-

The driver options for a given driver name need - always to be consistent, even when the driver is reloaded, meaning that they are as much a part - of the driver as the actual name.

-

Currently the only allowed driver option is +

The driver options for a specified driver name need + always to be consistent, even when the driver is reloaded, + meaning that they are as much a part of the driver as the name.

+

The only allowed driver option is kill_ports, which means that all ports opened - towards the driver are killed with the exit-reason + to the driver are killed with exit reason driver_unloaded when no process any longer has the driver loaded. This situation arises either - when the last user calls try_unload/2, or - the last process having loaded the driver exits.

+ when the last user calls + try_unload/2, or + when the last process having loaded the driver exits.

- {monitor, MonitorOption} + {monitor, MonitorOption}

A MonitorOption tells try_load/3 to trigger a driver monitor under certain conditions. When the monitor is triggered, the - function will return a three-tuple {ok, PendingStatus, reference()}, where the reference() is - the monitor ref for the driver monitor.

-

Only one MonitorOption can be specified and - it is either the atom pending, which means - that a monitor should be created whenever a load - operation is delayed, and the atom - pending_driver, in which a monitor is - created whenever the operation is delayed due to - open ports towards an otherwise unused driver. The - pending_driver option is of little use, but - is present for completeness, it is very well defined - which reload-options might give rise to which - delays. It might, however, be a good idea to use the - same MonitorOption as the ReloadOption - if present.

-

If reloading is not requested, it might still be - useful to specify the monitor option, as - forced unloads (kill_ports driver option or - the kill_ports option to try_unload/2) will - trigger a transient state where driver loading + function returns a three-tuple + {ok, PendingStatus, reference()}, where + reference() is the monitor reference for the driver monitor.

+

Only one MonitorOption can be specified. + It is one of the following:

+ + +

The atom pending, which means + that a monitor is to be created whenever a load + operation is delayed,

+
+ +

The atom pending_driver, in which a monitor + is created whenever the operation is delayed because + of open ports to an otherwise unused driver.

+
+
+

Option pending_driver is of little use, but + is present for completeness, as it is well defined which + reload options that can give rise to which delays. + However, it can be a good idea to use the same + MonitorOption as the + ReloadOption, if present.

+

If reloading is not requested, it can still be + useful to specify option monitor, as + forced unloads (driver option kill_ports or + option kill_ports to + try_unload/2) + trigger a transient state where driver loading cannot be performed until all closing ports are - actually closed. So, as try_unload can, in - almost all situations, return {ok, pending_driver}, one should always specify at least - {monitor, pending_driver} in production - code (see the monitor discussion above).

+ closed. Thus, as try_unload can, in + almost all situations, return {ok, pending_driver}, + always specify at least {monitor, pending_driver} + in production code (see the monitor discussion earlier).

- {reload, ReloadOption} + {reload, ReloadOption} -

This option is used when one wants to +

This option is used to reload a driver from disk, most often in a code upgrade scenario. Having a reload option - also implies that the Path parameter need - not be consistent with earlier loads of + also implies that parameter Path does + not need to be consistent with earlier loads of the driver.

-

To reload a driver, the process needs to have previously - loaded the driver, i.e there has to be an active user of the driver in the process.

-

The reload option can be either the atom - pending, in which reloading is requested for - any driver and will be effectuated when all - ports opened against the driver are closed. The - replacement of the driver will in this case take - place regardless of if there are still - pending users - having the driver loaded! - The option also triggers port-killing (if the - kill_ports driver option is used) even though - there are pending users, making it usable for forced - driver replacement, but laying a lot of - responsibility on the driver users. The pending option is - seldom used as one does not want other users to have loaded the - driver when code change is underway.

-

The more useful option is pending_driver, - which means that reloading will be queued if the - driver is not loaded by any other users, but the driver has - opened ports, in which case {ok, pending_driver} will be returned (a - monitor option is of course recommended).

-

If the driver is unloaded (not present in the - system), the error code - not_loaded will be returned. The - reload option is intended for when the user +

To reload a driver, the process must have loaded the driver + before, that is, there must be an active + user of the driver + in the process.

+

The reload option can be either of the following:

+ + pending + +

With the atom pending, reloading is requested + for any driver and is effectuated when all + ports opened to the driver are closed. The driver + replacement in this case takes + place regardless if there are still + pending users + having the driver loaded.

+

The option also triggers port-killing (if driver + option kill_ports is used) although + there are pending users, making it usable for forced + driver replacement, but laying much + responsibility on the driver + users. + The pending option is seldom used as one does not want other + users to have loaded + the driver when code change is underway.

+ pending_driver + +

This option is more useful. Here, reloading is queued + if the driver is not loaded by any other + users, but the + driver has opened ports, in which case + {ok, pending_driver} is returned + (a monitor option is recommended).

+
+

If the driver is unloaded (not present in the system), + error code not_loaded is returned. Option + reload is intended for when the user has already loaded the driver in advance.

-

The function might return numerous errors, of which some - only can be returned given a certain combination of options.

-

A number of errors are opaque and can only be interpreted by - passing them to the format_error/1 function, +

The function can return numerous errors, some + can only be returned given a certain combination of options.

+

Some errors are opaque and can only be interpreted by + passing them to function + format_error/1, but some can be interpreted directly:

- {error,linked_in_driver} + {error,linked_in_driver} -

The driver with the specified name is an erlang - statically linked in driver, which cannot be manipulated +

The driver with the specified name is an Erlang + statically linked-in driver, which cannot be manipulated with this API.

- {error,inconsistent} + {error,inconsistent} -

The driver has already been loaded with either other - DriverOptionList or a different literalPath argument.

-

This can happen even if a reload option is given, - if the DriverOptionList differ from the current.

+

The driver is already loaded with other + DriverOptionList or a different + literal Path argument.

+

This can occur even if a reload option is specified, + if DriverOptionList differs from the current.

- {error, permanent} + {error, permanent}

The driver has requested itself to be permanent, making - it behave like an erlang linked in driver and it can no + it behave like an Erlang linked-in driver and can no longer be manipulated with this API.

- {error, pending_process} + {error, pending_process} -

The driver is loaded by other users when the {reload, pending_driver} option was given.

+

The driver is loaded by other + users when + option {reload, pending_driver} was specified.

- {error, pending_reload} + {error, pending_reload} -

Driver reload is already requested by another user when the {reload, ReloadOption} option was given.

+

Driver reload is already requested by another + user when option + {reload, ReloadOption} was specified.

- {error, not_loaded_by_this_process} + {error, not_loaded_by_this_process} -

Appears when the reload option is given. The - driver Name is present in the system, but there is no - user of it in this +

Appears when option reload is specified. The + driver Name is present in the system, but there + is no user of it in this process.

- {error, not_loaded} + {error, not_loaded} -

Appears when the reload option is given. The +

Appears when option reload is specified. The driver Name is not in the system. Only drivers loaded by this process can be reloaded.

-

All other error codes are to be translated by the format_error/1 - function. Note that calls to format_error should be - performed from the same running instance of the erlang - virtual machine as the error was detected in, due to system - dependent behavior concerning error values.

-

If the arguments or options are malformed, the function will - throw a badarg exception.

+

All other error codes are to be translated by function + format_error/1. + Notice that calls to format_error are to be + performed from the same running instance of the Erlang + virtual machine as the error is detected in, because of + system-dependent behavior concerning error values.

+

If the arguments or options are malformed, the function + throws a badarg exception.

- Unload a driver + Unload a driver. -

This is the low level function to unload (or decrement +

This is the low-level function to unload (or decrement reference counts of) a driver. It can be used to force port killing, in much the same way as the driver option - kill_ports implicitly does, and it can trigger a - monitor either due to other users still having the driver - loaded or that there are open ports using the driver.

+ kill_ports implicitly does. Also, it can trigger a + monitor either because other + users still have the driver + loaded or because open ports use the driver.

Unloading can be described as the process of telling the emulator that this particular part of the code in this - particular process (i.e. this user) no longer needs the - driver. That can, if there are no other users, trigger - actual unloading of the driver, in which case the driver - name disappears from the system and (if possible) the memory - occupied by the driver executable code is reclaimed. If the - driver has the kill_ports option set, or if - kill_ports was specified as an option to this - function, all pending ports using this driver will get - killed when unloading is done by the last user. If no port-killing is - involved and there are open ports, the actual unloading - is delayed until there are no more open ports using the - driver. If, in this case, another user (or even this user) loads the - driver again before the driver is actually unloaded, the - unloading will never take place.

-

To allow the user that - requests unloading to wait for actual unloading to - take place, monitor triggers can be specified in much - the same way as when loading. As users of this function however - seldom are interested in more than decrementing the - reference counts, monitoring is more seldom needed. If the - kill_ports option is used however, monitor trigging is - crucial, as the ports are not guaranteed to have been killed - until the driver is unloaded, why a monitor should be - triggered for at least the pending_driver case.

-

The possible monitor messages that can be expected are the - same as when using the unloaded option to the - monitor/2 function.

-

The function will return one of the following statuses upon + particular process (that is, this + user) no longer needs + the driver. That can, if there are no other users, trigger + unloading of the driver, in which case the driver name + disappears from the system and (if possible) the memory + occupied by the driver executable code is reclaimed.

+

If the driver has option kill_ports set, or if + kill_ports is specified as an option to this + function, all pending ports using this driver are + killed when unloading is done by the last + user. If no port-killing + is involved and there are open ports, the unloading + is delayed until no more open ports use the + driver. If, in this case, another + user (or even this user) + loads the driver again before the driver is unloaded, the + unloading never takes place.

+

To allow the user to + request unloading to wait for actual unloading, + monitor triggers can be specified in much the same way as + when loading. However, as users + of this function seldom are interested in more than decrementing the + reference counts, monitoring is seldom needed.

+

If option kill_ports is used, monitor trigging is crucial, + as the ports are not guaranteed to be killed until the driver is unloaded. + Thus, a monitor must be triggered for at least the pending_driver + case.

+

The possible monitor messages to expect are the + same as when using option unloaded to function + monitor/2.

+

The function returns one of the following statuses upon success:

- {ok, unloaded} + {ok, unloaded}

The driver was immediately unloaded, meaning that the driver name is now free to use by other drivers and, if the underlying OS permits it, the memory occupied by the driver object code is now reclaimed.

The driver can only be unloaded when there are no open - ports using it and there are no more users requiring it to be + ports using it and no more + users require it to be loaded.

- {ok, pending_driver}or {ok, pending_driver, reference()} + {ok, pending_driver}or + {ok, pending_driver, reference()} -

This return value indicates that this call removed the - last user from the +

Indicates that this call removed the last + user from the driver, but there are still open ports using it. - When all ports are closed and no new users have arrived, the driver - will actually be reloaded and the name and memory + When all ports are closed and no new + users have arrived, + the driver is reloaded and the name and memory reclaimed.

-

This return value is valid even when the option - kill_ports was used, as killing ports may not be - a process that completes immediately. The condition is, - in that case, however transient. Monitors are as always - useful to detect when the driver is really unloaded.

+

This return value is valid even if option kill_ports + was used, as killing ports can be a process that does not + complete immediately. However, the condition is in that case + transient. Monitors are always useful to detect when the driver + is really unloaded.

- {ok, pending_process}or {ok, pending_process, reference()} + {ok, pending_process}or + {ok, pending_process, reference()} -

The unload request is registered, but there are still - other users holding - the driver. Note that the term pending_process - might refer to the running process, there might be more +

The unload request is registered, but + other users still hold + the driver. Notice that the term pending_process + can refer to the running process; there can be more than one user in the same process.

-

This is a normal, healthy return value if the call was +

This is a normal, healthy, return value if the call was just placed to inform the emulator that you have no - further use of the driver. It is actually the most - common return value in the most common scenario + further use of the driver. It is the most + common return value in the most common + scenario described in the introduction.

The function accepts the following parameters:

- Name + Name -

The name parameter is the name of the driver to be - unloaded. The name can be specified either as an - iolist() or as an atom().

+

Name is the name of the + driver to be unloaded. The name can be specified as an + iolist() or as an atom().

- OptionList + OptionList -

The OptionList argument can be used to specify - certain behavior regarding ports as well as triggering +

Argument OptionList can be used to specify + certain behavior regarding ports and triggering monitors under certain conditions:

- kill_ports + kill_ports -

Force killing of all ports opened using this driver, - with the exit reason driver_unloaded, if you are - the lastuser of the driver.

-

If there are other users having the driver - loaded, this option will have no effect.

-

If one wants the consistent behavior of killing ports +

Forces killing of all ports opened using this driver, + with exit reason driver_unloaded, if you are + the last user + of the driver.

+

If other users + have the driver loaded, this option has no effect.

+

To get the consistent behavior of killing ports when the last user - unloads, one should use the driver option + unloads, use driver option kill_ports when loading the driver instead.

- {monitor, MonitorOption} + {monitor, MonitorOption} -

This option creates a driver monitor if the condition - given in MonitorOption is true. The valid +

Creates a driver monitor if the condition + specified in MonitorOption is true. The valid options are:

- pending_driver + pending_driver -

Create a driver monitor if the return value is to +

Creates a driver monitor if the return value is to be {ok, pending_driver}.

- pending + pending -

Create a monitor if the return value will be either +

Creates a monitor if the return value is {ok, pending_driver} or {ok, pending_process}.

-

The pending_driver MonitorOption is by far - the most useful and it has to be used to ensure that the - driver has really been unloaded and the ports closed - whenever the kill_ports option is used or the - driver may have been loaded with the kill_ports - driver option.

-

By using the monitor-triggers in the call to - try_unload one can be sure that the monitor is - actually added before the unloading is executed, meaning - that the monitor will always get properly triggered, - which would not be the case if one called - erl_ddll:monitor/2 separately.

+

The pending_driver MonitorOption is + by far the most useful. It must be used to ensure that the + driver really is unloaded and the ports closed + whenever option kill_ports is used, or the + driver can have been loaded with driver option + kill_ports.

+

Using the monitor triggers in the call to + try_unload ensures that the monitor is + added before the unloading is executed, meaning + that the monitor is always properly triggered, + which is not the case if monitor/2 is called + separately.

-

The function may return several error conditions, of which - all are well specified (no opaque values):

+

The function can return the following error conditions, + all well specified (no opaque values):

- {error, linked_in_driver} + {error, linked_in_driver} -

You were trying to unload an erlang statically linked in +

You were trying to unload an Erlang statically linked-in driver, which cannot be manipulated with this interface (and cannot be unloaded at all).

- {error, not_loaded} + {error, not_loaded}

The driver Name is not present in the system.

- {error, not_loaded_by_this_process} + {error, not_loaded_by_this_process}

The driver Name is present in the system, but there is no user of it in this process.

As a special case, drivers can be unloaded from - processes that has done no corresponding call to - try_load/3 if, and only if, there are no users of the driver at all, which may happen if the + processes that have done no corresponding call to + try_load/3 if, and only if, there are + no users of the driver at all, which can occur if the process containing the last user dies.

- {error, permanent} + {error, permanent}

The driver has made itself permanent, in which case it can no longer be manipulated by this interface (much - like a statically linked in driver).

+ like a statically linked-in driver).

The function throws a badarg exception if the - parameters are not given as described above.

+ parameters are not specified as described here.

- Unload a driver + Unload a driver.

Unloads, or at least dereferences the driver named - Name. If the caller is the last user of the driver, and there - are no more open ports using the driver, the driver will - actually get unloaded. In all other cases, actual unloading - will be delayed until all ports are closed and there are no - remaining users.

-

If there are other users of the driver, the reference - counts of the driver is merely decreased, so that the caller - is no longer considered a user of the driver. For usage - scenarios, see the description in the beginning - of this document.

+ Name. If the caller is the last + user of the driver, + and no more open ports use the driver, the driver + gets unloaded. Otherwise, unloading + is delayed until all ports are closed and no + users remain.

+

If there are other users + of the driver, the reference counts of the driver is merely decreased, + so that the caller is no longer considered a + user of the driver. For use + scenarios, see the description + in the beginning of this module.

The ErrorDesc returned is an opaque value to be - passed further on to the format_error/1 - function. For more control over the operation, use the - try_unload/2 + passed further on to function + format_error/1. + For more control over the operation, use the + try_unload/2 interface.

The function throws a badarg exception if the - parameters are not given as described above.

+ parameters are not specified as described here.

- Unload a driver + Unload a driver.

Unloads, or at least dereferences the driver named - Name. If the caller is the last user of the driver, all - remaining open ports using the driver will get killed with - the reason driver_unloaded and the driver will - eventually get unloaded.

+ Name. If the caller is the last + user of the driver, all + remaining open ports using the driver are killed with + reason driver_unloaded and the driver + eventually gets unloaded.

If there are other users of the driver, the reference counts of the driver is merely decreased, so that the caller is no longer considered a user. For - usage scenarios, see the description in the beginning - of this document.

+ use scenarios, see the + description in the + beginning of this module.

The ErrorDesc returned is an opaque value to be - passed further on to the format_error/1 - function. For more control over the operation, use the - try_unload/2 + passed further on to function + format_error/1. + For more control over the operation, use the + try_unload/2 interface.

The function throws a badarg exception if the - parameters are not given as described above.

-
-
- - - List loaded drivers - -

Returns a list of all the available drivers, both - (statically) linked-in and dynamically loaded ones.

-

The driver names are returned as a list of strings rather - than a list of atoms for historical reasons.

-

More information about drivers can be obtained using one of - the info functions.

-
-
- - - Format an error descriptor - -

Takes an ErrorDesc returned by load, unload or - reload functions and returns a string which - describes the error or warning.

- -

Due to peculiarities in the dynamic loading interfaces on - different platform, the returned string is only guaranteed - to describe the correct error if format_error/1 is called in the same instance of the erlang virtual machine as the error appeared in (meaning the same operating - system process)!

-
+ parameters are not specified as described here.

-
- SEE ALSO -

erl_driver(4), driver_entry(4)

+ See Also +

erts:erl_driver(4), + erts:driver_entry(4)

- diff --git a/lib/kernel/doc/src/erl_prim_loader_stub.xml b/lib/kernel/doc/src/erl_prim_loader_stub.xml index 8d5f58dc3a..731ede2dad 100644 --- a/lib/kernel/doc/src/erl_prim_loader_stub.xml +++ b/lib/kernel/doc/src/erl_prim_loader_stub.xml @@ -37,7 +37,7 @@ The module erl_prim_loader is moved to the runtime system application. Please see erl_prim_loader(3) in the - erts reference manual instead. + ERTS reference manual instead.

diff --git a/lib/kernel/doc/src/erlang_stub.xml b/lib/kernel/doc/src/erlang_stub.xml index b9867806bd..6b95568224 100644 --- a/lib/kernel/doc/src/erlang_stub.xml +++ b/lib/kernel/doc/src/erlang_stub.xml @@ -37,7 +37,7 @@ The module erlang is moved to the runtime system application. Please see erlang(3) in the - erts reference manual instead. + ERTS reference manual instead.

diff --git a/lib/kernel/doc/src/error_handler.xml b/lib/kernel/doc/src/error_handler.xml index 6aec5c77d5..14e7537d1f 100644 --- a/lib/kernel/doc/src/error_handler.xml +++ b/lib/kernel/doc/src/error_handler.xml @@ -31,35 +31,48 @@ error_handler - Default System Error Handler + Default system error handler. -

The error handler module defines what happens when certain types +

This module defines what happens when certain types of errors occur.

+ + + Raise an undef exception. + + A (possibly empty) list of arguments Arg1,..,ArgN + + +

Raises an undef exception with a stacktrace, indicating + that Module:Function/N is + undefined. +

+
+
- Called when an undefined function is encountered + Called when an undefined function is encountered. A (possibly empty) list of arguments Arg1,..,ArgN -

This function is called by the run-time system if a call is made to +

This function is called by the runtime system if a call is made to Module:Function(Arg1,.., ArgN) and - Module:Function/N is undefined. Note that - undefined_function/3 is evaluated inside the process + Module:Function/N is undefined. + Notice that this function is evaluated inside the process making the original call.

-

This function will first attempt to autoload +

This function first attempts to autoload Module. If that is not possible, - an undef exception will be raised.

+ an undef exception is raised.

-

If it was possible to load Module - and the function Function/N is exported, - it will be called.

+

If it is possible to load Module + and function Function/N is exported, + it is called.

-

Otherwise, if the function '$handle_undefined_function'/2 - is exported, it will be called as +

Otherwise, if function '$handle_undefined_function'/2 + is exported, it is called as '$handle_undefined_function'(Function, Args).

@@ -67,61 +80,48 @@

Defining '$handle_undefined_function'/2 in ordinary application code is highly discouraged. It is very easy to make subtle errors that can take a long time to - debug. Furthermore, none of the tools for static code + debug. Furthermore, none of the tools for static code analysis (such as Dialyzer and Xref) supports the use of '$handle_undefined_function'/2 and no such support will be added. Only use this function after having carefully - considered other, less dangerous, solutions. One example of + considered other, less dangerous, solutions. One example of potential legitimate use is creating stubs for other sub-systems during testing and debugging.

-

Otherwise an undef exception will be raised.

-
-
- - - Raise an undef exception - - A (possibly empty) list of arguments Arg1,..,ArgN - - -

Raise an undef exception with a stacktrace indicating - that Module:Function/N is - undefined. -

+

Otherwise an undef exception is raised.

- Called when an undefined lambda (fun) is encountered + Called when an undefined lambda (fun) is encountered. A (possibly empty) list of arguments Arg1,..,ArgN

This function is evaluated if a call is made to - Fun(Arg1,.., ArgN) when the module defining the fun is - not loaded. The function is evaluated inside the process + Fun(Arg1,.., ArgN) when the module defining + the fun is not loaded. The function is evaluated inside the process making the original call.

If Module is interpreted, the interpreter is invoked and the return value of the interpreted Fun(Arg1,.., ArgN) call is returned.

Otherwise, it returns, if possible, the value of - apply(Fun, Args) after an attempt has been made to - autoload Module. If this is not possible, the call - fails with exit reason undef.

+ apply(Fun, Args) after an attempt + is made to autoload Module. If this is not possible, + the call fails with exit reason undef.

Notes -

The code in error_handler is complex and should not be - changed without fully understanding the interaction between +

The code in error_handler is complex. Do not + change it without fully understanding the interaction between the error handler, the init process of the code server, and the I/O mechanism of the code.

-

Changes in the code which may seem small can cause a deadlock - as unforeseen consequences may occur. The use of input is +

Code changes that seem small can cause a deadlock, + as unforeseen consequences can occur. The use of input is dangerous in this type of code.

diff --git a/lib/kernel/doc/src/error_logger.xml b/lib/kernel/doc/src/error_logger.xml index 92e14c2bef..3bd192fd41 100644 --- a/lib/kernel/doc/src/error_logger.xml +++ b/lib/kernel/doc/src/error_logger.xml @@ -29,41 +29,44 @@ error_logger - Erlang Error Logger + Erlang error logger.

The Erlang error logger is an event manager (see OTP Design Principles and - gen_event(3)), - registered as error_logger. Error, warning and info events + stdlib:gen_event(3)), + registered as error_logger. Errors, warnings, and info events are sent to the error logger from the Erlang runtime system and the different Erlang/OTP applications. The events are, by default, - logged to tty. Note that an event from a process P is + logged to the terminal. Notice that an event from a process P is logged at the node of the group leader of P. This means that log output is directed to the node from which a process was created, which not necessarily is the same node as where it is executing.

-

Initially, error_logger only has a primitive event +

Initially, error_logger has only a primitive event handler, which buffers and prints the raw event messages. During - system startup, the application Kernel replaces this with a - standard event handler, by default one which writes - nicely formatted output to tty. Kernel can also be configured so - that events are logged to file instead, or not logged at all, see - kernel(6).

-

Also the SASL application, if started, adds its own event - handler, which by default writes supervisor, crash and progress - reports to tty. See - sasl(6).

-

It is recommended that user defined applications should report - errors through the error logger, in order to get uniform reports. - User defined event handlers can be added to handle application - specific events. (add_report_handler/1,2). Also, there is - a useful event handler in STDLIB for multi-file logging of events, - see log_mf_h(3).

+ system startup, the Kernel application replaces this with a + standard event handler, by default one that writes + nicely formatted output to the terminal. Kernel can also be + configured so that events are logged to a file instead, or not logged at all, + see kernel(6).

+

Also the SASL application, if started, adds its own event + handler, which by default writes supervisor, crash, and progress + reports to the terminal. See + sasl(6).

+

It is recommended that user-defined applications report + errors through the error logger to get uniform reports. + User-defined event handlers can be added to handle application-specific + events, see + add_report_handler/1,2. + Also, a useful event handler is provided in STDLIB for multi-file + logging of events, see + stdlib:log_mf_h(3).

Warning events were introduced in Erlang/OTP R9C and are enabled - by default as of 18.0. To retain backwards compatibility with existing - user defined event handlers, these may be tagged as errors or info - using the command line flag ]]>, thus - showing up as error or info reports in the logs.

+ by default as from Erlang/OTP 18.0. To retain backwards compatibility + with existing user-defined event handlers, the warning events can be + tagged as errors or info using command-line flag + ]]>, thus showing up as + ERROR REPORT or INFO REPORT in the logs.

@@ -71,16 +74,45 @@ + + + + Add an event handler to the error logger. + +

Adds a new event handler to the error logger. The event + handler must be implemented as a gen_event callback + module, see + stdlib:gen_event(3).

+

Handler is typically the name of the callback module + and Args is an optional term (defaults to []) passed + to the initialization callback function Handler:init/1. + The function returns ok if successful.

+

The event handler must be able to handle the events in this module, see + section Events.

+
+
+ + + Delete an event handler from the error logger. + +

Deletes an event handler from the error logger by calling + gen_event:delete_handler(error_logger, Handler, []), + see stdlib:gen_event(3).

+
+
- Send an standard error event to the error logger + Send a standard error event to the error logger.

Sends a standard error event to the error logger. - The Format and Data arguments are the same as - the arguments of io:format/2. The event is handled by - the standard event handler.

+ The Format and Data arguments + are the same as the arguments of + io:format/2 + in STDLIB. + The event is handled by the standard event handler.

+

Example:

 1> error_logger:error_msg("An error occurred in ~p~n", [a_module]).
 
@@ -90,16 +122,19 @@ ok

If called with bad arguments, this function can crash the standard event handler, meaning no further events are - logged. When in doubt, use error_report/1 instead.

+ logged. When in doubt, use + error_report/1 + instead.

- Send a standard error report event to the error logger + Send a standard error report event to the error logger.

Sends a standard error report event to the error logger. The event is handled by the standard event handler.

+

Example:

 2> error_logger:error_report([{tag1,data1},a_term,{tag2,data}]).
 
@@ -117,100 +152,27 @@ ok
- Send a user defined error report event to the error logger + Send a user-defined error report event to the error logger. -

Sends a user defined error report event to the error logger. +

Sends a user-defined error report event to the error logger. An event handler to handle the event is supposed to have been added. The event is ignored by the standard event handler.

It is recommended that Report follows the same - structure as for error_report/1.

-
-
- - - Return the current mapping for warning events - -

Returns the current mapping for warning events. Events sent - using warning_msg/1,2 or warning_report/1,2 - are tagged as errors, warnings (default) or info, depending - on the value of the command line flag +W.

-
-os$ erl
-Erlang (BEAM) emulator version 5.4.8 [hipe] [threads:0] [kernel-poll]
-
-Eshell V5.4.8  (abort with ^G)
-1> error_logger:warning_map().
-warning
-2> error_logger:warning_msg("Warnings tagged as: ~p~n", [warning]).
-
-=WARNING REPORT==== 11-Aug-2005::15:31:55 ===
-Warnings tagged as: warning
-ok
-3> 
-User switch command
- --> q
-os$ erl +W e
-Erlang (BEAM) emulator version 5.4.8 [hipe] [threads:0] [kernel-poll]
-
-Eshell V5.4.8  (abort with ^G)
-1> error_logger:warning_map().
-error
-2> error_logger:warning_msg("Warnings tagged as: ~p~n", [error]).
-
-=ERROR REPORT==== 11-Aug-2005::15:31:23 ===
-Warnings tagged as: error
-ok
-
-
- - - - Send a standard warning event to the error logger - -

Sends a standard warning event to the error logger. - The Format and Data arguments are the same as - the arguments of io:format/2. The event is handled by - the standard event handler. It is tagged either as an error, - warning or info, see - warning_map/0.

- -

If called with bad arguments, this function can crash - the standard event handler, meaning no further events are - logged. When in doubt, use warning_report/1 instead.

-
-
-
- - - Send a standard warning report event to the error logger - -

Sends a standard warning report event to the error logger. - The event is handled by the standard event handler. It is - tagged either as an error, warning or info, see - warning_map/0.

-
-
- - - Send a user defined warning report event to the error logger - -

Sends a user defined warning report event to the error - logger. An event handler to handle the event is supposed to - have been added. The event is ignored by the standard event - handler. It is tagged either as an error, warning or info, - depending on the value of - warning_map/0.

+ structure as for + error_report/1.

- Send a standard information event to the error logger + Send a standard information event to the error logger.

Sends a standard information event to the error logger. - The Format and Data arguments are the same as - the arguments of io:format/2. The event is handled by - the standard event handler.

+ The Format and Data arguments + are the same as the arguments of + io:format/2 + in STDLIB. The event is handled by the standard event handler.

+

Example:

 1> error_logger:info_msg("Something happened in ~p~n", [a_module]).
 
@@ -226,10 +188,11 @@ ok
- Send a standard information report event to the error logger + Send a standard information report event to the error logger.

Sends a standard information report event to the error logger. The event is handled by the standard event handler.

+

Example:

 2> error_logger:info_report([{tag1,data1},a_term,{tag2,data}]).
 
@@ -247,59 +210,22 @@ ok
- Send a user defined information report event to the error logger + Send a user-defined information report event to the error logger. -

Sends a user defined information report event to the error +

Sends a user-defined information report event to the error logger. An event handler to handle the event is supposed to have been added. The event is ignored by the standard event handler.

It is recommended that Report follows the same - structure as for info_report/1.

-
-
- - - - Add an event handler to the error logger - -

Adds a new event handler to the error logger. The event - handler must be implemented as a gen_event callback - module, see - gen_event(3).

-

Handler is typically the name of the callback module - and Args is an optional term (defaults to []) passed - to the initialization callback function Handler:init/1. - The function returns ok if successful.

-

The event handler must be able to handle the - events described below.

-
-
- - - Delete an event handler from the error logger - -

Deletes an event handler from the error logger by calling - gen_event:delete_handler(error_logger, Handler, []), - see gen_event(3).

-
-
- - - Enable or disable printouts to the tty - -

Enables (Flag == true) or disables - (Flag == false) printout of standard events to the tty.

-

This is done by adding or deleting the standard event handler - for output to tty, thus calling this function overrides - the value of the Kernel error_logger configuration - parameter.

+ structure as for + info_report/1.

- Enable or disable error printouts to a file + Enable or disable error printouts to a file. @@ -308,22 +234,22 @@ ok

Enables or disables printout of standard events to a file.

This is done by adding or deleting the standard event handler - for output to file, thus calling this function overrides - the value of the Kernel error_logger configuration + for output to file. Thus, calling this function overrides + the value of the Kernel error_logger configuration parameter.

-

Enabling file logging can be used in combination with calling - tty(false), in order to have a silent system, where +

Enabling file logging can be used together with calling + tty(false), to have a silent system where all standard events are logged to a file only. - There can only be one active log file at a time.

-

Request is one of:

+ Only one log file can be active at a time.

+

Request is one of the following:

{open, Filename} -

Opens the log file Filename. Returns ok if +

Opens log file Filename. Returns ok if successful, or {error, allready_have_logfile} if logging to file is already enabled, or an error tuple if - another error occurred. For example, if Filename - could not be opened.

+ another error occurred (for example, if Filename + cannot be opened).

close @@ -339,6 +265,97 @@ ok
+ + + Enable or disable printouts to the terminal. + +

Enables (Flag == true) or disables + (Flag == false) printout of standard events + to the terminal.

+

This is done by adding or deleting the standard event handler + for output to the terminal. Thus, calling this function overrides + the value of the Kernel error_logger configuration parameter.

+
+
+ + + Return the current mapping for warning events. + +

Returns the current mapping for warning events. Events sent + using warning_msg/1,2 or warning_report/1,2 + are tagged as errors, warnings (default), or info, depending + on the value of command-line flag +W.

+

Example:

+
+os$ erl
+Erlang (BEAM) emulator version 5.4.8 [hipe] [threads:0] [kernel-poll]
+
+Eshell V5.4.8  (abort with ^G)
+1> error_logger:warning_map().
+warning
+2> error_logger:warning_msg("Warnings tagged as: ~p~n", [warning]).
+
+=WARNING REPORT==== 11-Aug-2005::15:31:55 ===
+Warnings tagged as: warning
+ok
+3>
+User switch command
+ --> q
+os$ erl +W e
+Erlang (BEAM) emulator version 5.4.8 [hipe] [threads:0] [kernel-poll]
+
+Eshell V5.4.8  (abort with ^G)
+1> error_logger:warning_map().
+error
+2> error_logger:warning_msg("Warnings tagged as: ~p~n", [error]).
+
+=ERROR REPORT==== 11-Aug-2005::15:31:23 ===
+Warnings tagged as: error
+ok
+
+
+ + + + Send a standard warning event to the error logger. + +

Sends a standard warning event to the error logger. + The Format and Data arguments + are the same as the arguments of + io:format/2 + in STDLIB. + The event is handled by the standard event handler. It is tagged + as an error, warning, or info, see + warning_map/0.

+ +

If called with bad arguments, this function can crash + the standard event handler, meaning no further events are + logged. When in doubt, use warning_report/1 instead.

+
+
+
+ + + Send a standard warning report event to the error logger. + +

Sends a standard warning report event to the error logger. + The event is handled by the standard event handler. It is + tagged as an error, warning, or info, see + warning_map/0.

+
+
+ + + Send a user-defined warning report event to the error logger. + +

Sends a user-defined warning report event to the error + logger. An event handler to handle the event is supposed to + have been added. The event is ignored by the standard event + handler. It is tagged as an error, warning, or info, + depending on the value of + warning_map/0.

+
+
@@ -346,8 +363,8 @@ ok Events

All event handlers added to the error logger must handle the following events. Gleader is the group leader pid of - the process which sent the event, and Pid is the process - which sent the event.

+ the process that sent the event, and Pid is the process + that sent the event.

{error, Gleader, {Pid, Format, Data}} @@ -364,18 +381,18 @@ ok {warning_msg, Gleader, {Pid, Format, Data}} -

Generated when warning_msg/1,2 is called, provided - that warnings are set to be tagged as warnings.

+

Generated when warning_msg/1,2 is called + if warnings are set to be tagged as warnings.

{warning_report, Gleader, {Pid, std_warning, Report}} -

Generated when warning_report/1 is called, provided - that warnings are set to be tagged as warnings.

+

Generated when warning_report/1 is called + if warnings are set to be tagged as warnings.

{warning_report, Gleader, {Pid, Type, Report}} -

Generated when warning_report/2 is called, provided - that warnings are set to be tagged as warnings.

+

Generated when warning_report/2 is called + if warnings are set to be tagged as warnings.

{info_msg, Gleader, {Pid, Format, Data}} @@ -390,17 +407,19 @@ ok

Generated when info_report/2 is called.

-

Note that also a number of system internal events may be - received, a catch-all clause last in the definition of +

Notice that some system-internal events can also be + received. Therefore a catch-all clause last in the definition of the event handler callback function Module:handle_event/2 - is necessary. This also holds true for - Module:handle_info/2, as there are a number of system - internal messages the event handler must take care of as well.

+ is necessary. This also applies for + Module:handle_info/2, as the event handler must also take care of + some system-internal messages.

-
- SEE ALSO -

gen_event(3), log_mf_h(3), kernel(6), sasl(6)

+ See Also +

stdlib:gen_event(3), + stdlib:log_mf_h(3) + kernel(6) + sasl(6)

diff --git a/lib/kernel/doc/src/file.xml b/lib/kernel/doc/src/file.xml index 831ef1c22a..2c4e2a16f9 100644 --- a/lib/kernel/doc/src/file.xml +++ b/lib/kernel/doc/src/file.xml @@ -29,56 +29,57 @@ file - File Interface Module + File interface module. -

The module file provides an interface to the file system.

-

On operating systems with thread support, it is possible to let - file operations be performed in threads of their own, allowing +

This module provides an interface to the file system.

+ +

On operating systems with thread support, + file operations can be performed in threads of their own, allowing other Erlang processes to continue executing in parallel with - the file operations. See the command line flag - +A in erl(1).

+ the file operations. See command-line flag + +A in erl(1).

-

With regard to file name encoding, the Erlang VM can operate in - two modes. The current mode can be queried using the native_name_encoding/0 - function. It returns either latin1 or utf8.

+

Regarding filename encoding, the Erlang VM can operate in + two modes. The current mode can be queried using function + native_name_encoding/0. + It returns latin1 or utf8.

-

In the latin1 mode, the Erlang VM does not change the - encoding of file names. In the utf8 mode, file names can - contain Unicode characters greater than 255 and the VM will - convert file names back and forth to the native file name encoding +

In latin1 mode, the Erlang VM does not change the + encoding of filenames. In utf8 mode, filenames can + contain Unicode characters greater than 255 and the VM + converts filenames back and forth to the native filename encoding (usually UTF-8, but UTF-16 on Windows).

The default mode depends on the operating system. Windows and - MacOS X enforce consistent file name encoding and therefore the - VM uses the utf8 mode.

+ MacOS X enforce consistent filename encoding and therefore the + VM uses utf8 mode.

-

On operating systems with transparent naming (i.e. all Unix - systems except MacOS X), the default will be utf8 if the - terminal supports UTF-8, otherwise latin1. The default may - be overridden using the +fnl (to force latin1 mode) - or +fnu (to force utf8 mode) when starting erl.

+

On operating systems with transparent naming (for example, all Unix + systems except MacOS X), default is utf8 if the + terminal supports UTF-8, otherwise latin1. The default can + be overridden using +fnl (to force latin1 mode) + or +fnu (to force utf8 mode) when starting + erts:erl.

-

On operating systems with transparent naming, files could be - inconsistently named, i.e. some files are encoded in UTF-8 while - others are encoded in (for example) iso-latin1. To be able to - handle file systems with inconsistent naming when running in the - utf8 mode, the concept of "raw file names" has been - introduced.

+

On operating systems with transparent naming, files can be + inconsistently named, for example, some files are encoded in UTF-8 while + others are encoded in ISO Latin-1. The concept of raw filenames is + introduced to handle file systems with inconsistent naming when running in + utf8 mode.

-

A raw file name is a file name given as a binary. The Erlang VM - will perform no translation of a file name given as a binary on +

A raw filename is a filename specified as a binary. The Erlang VM + does not translate a filename specified as a binary on systems with transparent naming.

-

When running in the utf8 mode, the - file:list_dir/1 and file:read_link/1 functions will - never return raw file names. Use the list_dir_all/1 and read_link_all/1 functions to - return all file names including raw file names.

+

When running in utf8 mode, functions + list_dir/1 and + read_link/1 + never return raw filenames. To return all filenames including raw filenames, + use functions + list_dir_all/1 and + read_link_all/1.

-

Also see Notes about raw file names.

+

See also section Notes About Raw Filenames in the STDLIB User´s Giude.

@@ -90,8 +91,8 @@ fd()

- A file descriptor representing a file opened in raw mode.

+ A file descriptor representing a file opened in + raw mode.

@@ -104,7 +105,7 @@

As returned by - file:open/2; + open/2; pid() is a process handling I/O-protocols.

@@ -112,7 +113,7 @@

If VM is in Unicode filename mode, string() and char() - are allowed to be > 255. + are allowed to be > 255.

@@ -120,12 +121,12 @@

If VM is in Unicode filename mode, string() and char() - are allowed to be > 255. + are allowed to be > 255. RawFilename is a filename not subject to Unicode translation, meaning that it can contain characters not conforming to - the Unicode encoding expected from the filesystem - (i.e. non-UTF-8 characters although the VM is started + the Unicode encoding expected from the file system + (that is, non-UTF-8 characters although the VM is started in Unicode filename mode).

@@ -133,7 +134,7 @@ -

An atom which is named from the POSIX error codes used in +

An atom that is named from the POSIX error codes used in Unix, and in the runtime libraries of most C compilers.

@@ -160,7 +161,7 @@ - Predeclare an access pattern for file data + Predeclare an access pattern for file data.

advise/4 can be used to announce an intention to access file @@ -171,80 +172,80 @@ - Allocate file space + Allocate file space.

allocate/3 can be used to preallocate space for a file.

-

This function only succeeds in platforms that implement this +

This function only succeeds in platforms that provide this feature. When it succeeds, space is preallocated for the file but the file size might not be updated. This behaviour depends on the - preallocation implementation. To guarantee the file size is updated - one must truncate the file to the new size.

+ preallocation implementation. To guarantee that the file size is updated, + truncate the file to the new size.

- Change group of a file + Change group of a file.

Changes group of a file. See - write_file_info/2.

+ write_file_info/2.

- Change permissions of a file + Change permissions of a file.

Changes permissions of a file. See - write_file_info/2.

+ write_file_info/2.

- Change owner of a file + Change owner of a file.

Changes owner of a file. See - write_file_info/2.

+ write_file_info/2.

- Change owner and group of a file + Change owner and group of a file.

Changes owner and group of a file. See - write_file_info/2.

+ write_file_info/2.

- Change the modification time of a file + Change the modification time of a file.

Changes the modification and access times of a file. See - write_file_info/2.

+ write_file_info/2.

- Change the modification and last access time of a file + Change the modification and last access time of a file.

Changes the modification and last access times of a file. See - write_file_info/2.

+ write_file_info/2.

- Close a file + Close a file.

Closes the file referenced by IoDevice. It mostly - returns ok, expect for some severe errors such as out + returns ok, except for some severe errors such as out of memory.

-

Note that if the option delayed_write was - used when opening the file, close/1 might return an +

Notice that if option delayed_write was + used when opening the file, close/1 can return an old write error and not even try to close the file. See - open/2.

+ open/2.

- Read Erlang terms from a file + Read Erlang terms from a file.

Reads Erlang terms, separated by '.', from Filename. Returns one of the following:

@@ -256,42 +257,44 @@ {error, atom()}

An error occurred when opening the file or reading it. - See open/2 for a list - of typical error codes.

+ For a list of typical error codes, see + open/2.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang terms in - the file. Use format_error/1 to convert - the three-element tuple to an English description of - the error.

+ the file. To convert the three-element tuple to an English + description of the error, use + format_error/1.

-

Example:

-f.txt: {person, "kalle", 25}. +

Example:

+ +f.txt: {person, "kalle", 25}. {person, "pelle", 30}. -
1> file:consult("f.txt").
+
+1> file:consult("f.txt").
 {ok,[{person,"kalle",25},{person,"pelle",30}]}
-

The encoding of of Filename can be set - by a comment as described in epp(3).

+

The encoding of Filename can be set + by a comment, as described in + stdlib:epp(3).

- Copy file contents + Copy file contents.

Copies ByteCount bytes from Source to Destination. Source and Destination refer - to either filenames or IO devices from e.g. open/2. + to either filenames or IO devices from, for example, open/2. ByteCount defaults to infinity, denoting an infinite number of bytes.

-

The argument Modes is a list of possible modes, - see open/2, and defaults to - [].

+

Argument Modes is a list of possible modes, + see open/2, and defaults to + [].

If both Source and Destination refer to filenames, the files are opened with [read, binary] @@ -303,25 +306,51 @@

If Destination refers to a filename, it is opened with write mode prepended to the mode list before the copy, and closed when done.

-

Returns {ok, BytesCopied} where +

Returns {ok, BytesCopied}, where BytesCopied is - the number of bytes that actually was copied, which may be + the number of bytes that was copied, which can be less than ByteCount if end of file was encountered on the source. If the operation fails, {error, Reason} is returned.

-

Typical error reasons: As for open/2 if a file had to - be opened, and as for read/2 and write/2.

+

Typical error reasons: as for + open/2 if a file + had to be opened, and as for + read/2 and + write/2.

+
+
+ + + Synchronize the in-memory data of a file, ignoring most of its metadata, with that on the physical medium. + +

Ensures that any buffers kept by the operating system + (not by the Erlang runtime system) are written to disk. In + many ways it resembles fsync but it does not update + some of the metadata of the file, such as the access time. On + some platforms this function has no effect.

+

Applications that access databases or log files often write + a tiny data fragment (for example, one line in a log file) and then + call fsync() immediately to ensure that the written + data is physically stored on the hard disk. Unfortunately, fsync() + always initiates two write operations: one for the newly + written data and another one to update the modification + time stored in the inode. If the modification time is not a part + of the transaction concept, fdatasync() can be used to avoid + unnecessary inode disk write operations.

+

Available only in some POSIX systems, this call results in a + call to fsync(), or has no effect in systems not providing + the fdatasync() syscall.

- Delete a directory + Delete a directory. -

Tries to delete the directory Dir. +

Tries to delete directory Dir. The directory must be empty before it can be deleted. Returns ok if successful.

-

Typical error reasons are:

+

Typical error reasons:

eacces @@ -351,11 +380,11 @@
- Delete a file + Delete a file. -

Tries to delete the file Filename. +

Tries to delete file Filename. Returns ok if successful.

-

Typical error reasons are:

+

Typical error reasons:

enoent @@ -367,32 +396,32 @@ eperm -

The file is a directory and the user is not super-user.

+

The file is a directory and the user is not superuser.

enotdir -

A component of the file name is not a directory. On some +

A component of the filename is not a directory. On some platforms, enoent is returned instead.

einval -

Filename had an improper type, such as tuple.

+

Filename has an improper type, such as tuple.

-

In a future release, a bad type for the - Filename argument will probably generate +

In a future release, a bad type for argument + Filename will probably generate an exception.

- Evaluate Erlang expressions in a file + Evaluate Erlang expressions in a file.

Reads and evaluates Erlang expressions, separated by '.' (or - ',', a sequence of expressions is also an expression), from - Filename. The actual result of the evaluation + ',', a sequence of expressions is also an expression) from + Filename. The result of the evaluation is not returned; any expression sequence in the file must be there for its side effect. Returns one of the following:

@@ -403,35 +432,36 @@ {error, atom()}

An error occurred when opening the file or reading it. - See open/2 for a list of typical error codes.

+ For a list of typical error codes, see + open/2.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang - expressions in the file. Use format_error/1 to - convert the three-element tuple to an English description - of the error.

+ expressions in the file. To convert the three-element tuple + to an English description of the error, use + format_error/1.

-

The encoding of of Filename can be set - by a comment as described in epp(3).

+

The encoding of Filename can be set + by a comment, as described in + stdlib:epp(3).

- Evaluate Erlang expressions in a file + Evaluate Erlang expressions in a file. -

The same as eval/1 but the variable bindings - Bindings are used in the evaluation. See - erl_eval(3) about - variable bindings.

+

The same as eval/1, but the variable bindings + Bindings are used in the evaluation. For information + about the variable bindings, see + stdlib:erl_eval(3).

- Return a descriptive string for an error reason + Return a descriptive string for an error reason.

Given the error reason returned by any function in this module, returns a descriptive string of the error in English.

@@ -439,17 +469,17 @@
- Get the current working directory + Get the current working directory.

Returns {ok, Dir}, where Dir is the current working directory of the file server.

In rare circumstances, this function can fail on Unix. - It may happen if read permission does not exist for + It can occur if read permission does not exist for the parent directories of the current directory.

-

Typical error reasons are:

+

A typical error reason:

eacces @@ -461,17 +491,19 @@
- Get the current working directory for the drive specified + Get the current working directory for the specified drive. -

Drive should be of the form - "Letter:", - for example "c:". Returns {ok, Dir} or +

Returns {ok, Dir} or {error, Reason}, where Dir - is the current - working directory of the drive specified.

-

This function returns {error, enotsup} on platforms - which have no concept of current drive (Unix, for example).

-

Typical error reasons are:

+ is the current working directory of the specified drive.

+ +

Drive is to be of the form + "Letter:", for example, "c:".

+ +

Returns {error, enotsup} on platforms + that have no concept of current drive (Unix, for example).

+ +

Typical error reasons:

enotsup @@ -490,16 +522,16 @@
- List files in a directory + List files in a directory.

Lists all files in a directory, except files - with "raw" names. Returns - {ok, Filenames} if successful. - Otherwise, it returns {error, Reason}. + with raw filenames. Returns + {ok, Filenames} if successful, + otherwise {error, Reason}. Filenames is a list of the names of all the files in the directory. The names are not sorted.

-

Typical error reasons are:

+

Typical error reasons:

eacces @@ -513,24 +545,24 @@ {no_translation, Filename}

Filename is a binary() with - characters coded in ISO-latin-1 and the VM was started - with the parameter +fnue.

+ characters coded in ISO Latin-1 and the VM was started + with parameter +fnue.

- List all files in a directory + List all files in a directory.

Lists all the files in a directory, - including files with "raw" names. - Returns {ok, Filenames} if successful. - Otherwise, it returns {error, Reason}. + including files with raw filenames. + Returns {ok, Filenames} if successful, + otherwise {error, Reason}. Filenames is a list of the names of all the files in the directory. The names are not sorted.

-

Typical error reasons are:

+

Typical error reasons:

eacces @@ -546,12 +578,12 @@
- Make a directory + Make a directory. -

Tries to create the directory Dir. Missing parent +

Tries to create directory Dir. Missing parent directories are not created. Returns ok if successful.

-

Typical error reasons are:

+

Typical error reasons:

eacces @@ -560,7 +592,7 @@ eexist -

There is already a file or directory named Dir.

+

A file or directory named Dir exists already.

enoent @@ -568,7 +600,7 @@ enospc -

There is a no space left on the device.

+

No space is left on the device.

enotdir @@ -580,13 +612,13 @@
- Make a hard link to a file + Make a hard link to a file.

Makes a hard link from Existing to - New, on - platforms that support links (Unix and Windows). This function returns - ok if the link was successfully created, or - {error, Reason}. On platforms that do not support + New on + platforms supporting links (Unix and Windows). This function returns + ok if the link was successfully created, otherwise + {error, Reason}. On platforms not supporting links, {error,enotsup} is returned.

Typical error reasons:

@@ -609,17 +641,16 @@
- Make a symbolic link to a file or directory + Make a symbolic link to a file or directory. -

This function creates a symbolic link New to - the file or directory Existing, on platforms that - support symbolic links (most Unix systems and Windows beginning with +

Creates a symbolic link New to + the file or directory Existing on platforms + supporting symbolic links (most Unix systems and Windows, beginning with Vista). - Existing need not exist. - This function returns ok if the link was - successfully created, or {error, Reason}. - On platforms - that do not support symbolic links, {error, enotsup} + Existing does not need to exist. + Returns ok if the link is + successfully created, otherwise {error, Reason}. + On platforms not supporting symbolic links, {error, enotsup} is returned.

Typical error reasons:

@@ -646,23 +677,23 @@
- Return the VM's configured filename encoding + Return the configured filename encoding of the VM. -

This function returns - the file name encoding mode. If it is latin1, the - system does no translation of file names. If it is - utf8, file names will be converted back and forth to - the native file name encoding (usually UTF-8, but UTF-16 on +

Returns + the filename encoding mode. If it is latin1, the + system translates no filenames. If it is + utf8, filenames are converted back and forth to + the native filename encoding (usually UTF-8, but UTF-16 on Windows).

- Open a file + Open a file. -

Opens the file File in the mode determined - by Modes, which may contain one or more of the - following items:

+

Opens file File in the mode determined + by Modes, which can contain one or more of the + following options:

read @@ -671,98 +702,100 @@ write

The file is opened for writing. It is created if it does - not exist. If the file exists, and if write is not - combined with read, the file will be truncated.

+ not exist. If the file exists and write is not + combined with read, the file is truncated.

append -

The file will be opened for writing, and it will be - created if it does not exist. Every write operation to a - file opened with append will take place at - the end of the file.

+

The file is opened for writing. It is created if it does + not exist. Every write operation to a file opened with + append takes place at the end of the file.

exclusive -

The file, when opened for writing, is created if it - does not exist. If the file exists, open will return - {error, eexist}.

+

The file is opened for writing. It is created if it does + not exist. If the file exists, {error, eexist} + is returned.

This option does not guarantee exclusiveness on - file systems that do not support O_EXCL properly, + file systems not supporting O_EXCL properly, such as NFS. Do not depend on this option unless you know that the file system supports it (in general, local - file systems should be safe).

+ file systems are safe).

raw

- The raw option allows faster access to a file, - because no Erlang process is needed to handle the file. + Allows faster access to a file, + as no Erlang process is needed to handle the file. However, a file opened in this way has the following limitations:

- The functions in the io module cannot be used, - because they can only talk to an Erlang process. - Instead, use the read/2, read_line/1 and - write/2 - functions. - Especially if read_line/1 is to be used on a raw file, it is recommended to combine this option with the {read_ahead, Size} option as line oriented I/O is inefficient without buffering. - Only the Erlang process which opened the file can use - it. - A remote Erlang file server cannot be used; - the computer on which the Erlang node is running must +

The functions in the io module cannot be used, + as they can only talk to an Erlang process. + Instead, use functions + read/2, + read_line/1, and + write/2.

+

Especially if read_line/1 is to be used on a raw + file, it is recommended to combine this option with option + {read_ahead, Size} as line-oriented I/O is inefficient + without buffering.

+

Only the Erlang process that opened the file can use + it.

+

A remote Erlang file server cannot be used. + The computer on which the Erlang node is running must have access to the file system (directly or through - NFS). + NFS).

binary -

When this option has been given, read operations on the file - will return binaries rather than lists.

+

Read operations on the file return binaries rather than lists.

{delayed_write, Size, Delay} -

If this option is used, the data in subsequent - write/2 calls is buffered until there are at least - Size bytes buffered, or until the oldest buffered +

Data in subsequent + write/2 calls is buffered until at least + Size bytes are buffered, or until the oldest buffered data is Delay milliseconds old. Then all buffered data is written in one operating system call. The buffered data is also flushed before some other file operation than write/2 is executed.

The purpose of this option is to increase performance - by reducing the number of operating system calls, so the - write/2 calls should be for sizes significantly - less than Size, and not interspersed by to many - other file operations, for this to happen.

+ by reducing the number of operating system calls. Thus, the + write/2 calls must be for sizes significantly + less than Size, and not interspersed by too many + other file operations.

When this option is used, the result of write/2 - calls may prematurely be reported as successful, and if - a write error should actually occur the error is - reported as the result of the next file operation, which - is not executed.

+ calls can prematurely be reported as successful, and if + a write error occurs, the error is reported as the result + of the next file operation, which is not executed.

For example, when delayed_write is used, after a - number of write/2 calls, close/1 might - return {error, enospc} because there was not enough - space on the disc for previously written data, and - close/1 should probably be called again since the + number of write/2 calls, close/1 can + return {error, enospc}, as there is not enough + space on the disc for previously written data. + close/1 must probably be called again, as the file is still open.

delayed_write

The same as {delayed_write, Size, Delay} with reasonable default values for Size and - Delay. (Roughly some 64 KBytes, 2 seconds)

+ Delay (roughly some 64 KB, 2 seconds).

{read_ahead, Size} -

This option activates read data buffering. If +

Activates read data buffering. If read/2 calls are for significantly less than - Size bytes, read operations towards the operating + Size bytes, read operations to the operating system are still performed for blocks of Size bytes. The extra data is buffered and returned in subsequent read/2 calls, giving a performance gain - since the number of operating system calls is reduced.

-

The read_ahead buffer is also highly utilized - by the read_line/1 function in raw mode, - why this option is recommended (for performance reasons) + as the number of operating system calls is reduced.

+

The read_ahead buffer is also highly used + by function read_line/1 in raw mode, + therefore this option is recommended + (for performance reasons) when accessing raw files using that function.

If read/2 calls are for sizes not significantly less than, or even greater than Size bytes, no @@ -771,93 +804,141 @@ read_ahead

The same as {read_ahead, Size} with a reasonable - default value for Size. (Roughly some 64 KBytes)

+ default value for Size (roughly some 64 KB).

compressed

Makes it possible to read or write gzip compressed - files. The compressed option must be combined - with either read or write, but not both. - Note that the file size obtained with - read_file_info/1 will most probably not match the - number of bytes that can be read from a compressed file.

+ files. Option compressed must be combined + with read or write, but not both. + Notice that the file size obtained with + read_file_info/1 + does probably not match the number of bytes that can be + read from a compressed file.

{encoding, Encoding} -

Makes the file perform automatic translation of characters to and from a specific (Unicode) encoding. Note that the data supplied to file:write or returned by file:read still is byte oriented, this option only denotes how data is actually stored in the disk file.

-

Depending on the encoding, different methods of reading and writing data is preferred. The default encoding of latin1 implies using this (the file) module for reading and writing data, as the interfaces provided here work with byte-oriented data, while using other (Unicode) encodings makes the io(3) module's get_chars, get_line and put_chars functions more suitable, as they can work with the full Unicode range.

-

If data is sent to an io_device() in a format that cannot be converted to the specified encoding, or if data is read by a function that returns data in a format that cannot cope with the character range of the data, an error occurs and the file will be closed.

-

The allowed values for Encoding are:

+

Makes the file perform automatic translation of characters to + and from a specific (Unicode) encoding. Notice that the data supplied + to + write/2 + or returned by + read/2 + still is byte-oriented; this option + denotes only how data is stored in the disk file.

+

Depending on the encoding, different methods of reading and writing + data is preferred. The default encoding of latin1 implies using + this module (file) for reading and writing data as the interfaces + provided here work with byte-oriented data. Using other (Unicode) + encodings makes the + stdlib:io(3) functions + get_chars, get_line, and put_chars more suitable, + as they can work with the full Unicode range.

+

If data is sent to an io_device() in a format that cannot be + converted to the specified encoding, or if data is read by a function + that returns data in a format that cannot cope with the character range + of the data, an error occurs and the file is closed.

+

Allowed values for Encoding:

latin1 -

The default encoding. Bytes supplied to i.e. file:write are written as is on the file, likewise bytes read from the file are returned to i.e. file:read as is. If the io(3) module is used for writing, the file can only cope with Unicode characters up to codepoint 255 (the ISO-latin-1 range).

+

The default encoding. Bytes supplied to the file, that is, + write/2 + are written "as is" on the file. Likewise, bytes read from the file, + that is, + read/2 are + returned "as is". If module + stdlib:io(3) is used for + writing, the file can only cope with Unicode characters up to code point + 255 (the ISO Latin-1 range).

- unicode or utf8 + unicode or utf8 -

Characters are translated to and from the UTF-8 encoding before being written to or read from the file. A file opened in this way might be readable using the file:read function, as long as no data stored on the file lies beyond the ISO-latin-1 range (0..255), but failure will occur if the data contains Unicode codepoints beyond that range. The file is best read with the functions in the Unicode aware io(3) module.

-

Bytes written to the file by any means are translated to UTF-8 encoding before actually being stored on the disk file.

+

Characters are translated to and from UTF-8 encoding before they are + written to or read from the file. A file opened in this way can be + readable using function + read/2, + as long as no data stored on + the file lies beyond the ISO Latin-1 range (0..255), but failure occurs + if the data contains Unicode code points beyond that range. The file is + best read with the functions in the Unicode aware module + stdlib:io(3).

+

Bytes written to the file by any means are translated to UTF-8 encoding + before being stored on the disk file.

- utf16 or {utf16,big} + utf16 or {utf16,big} -

Works like unicode, but translation is done to and from big endian UTF-16 instead of UTF-8.

+

Works like unicode, but translation is done to and from big + endian UTF-16 instead of UTF-8.

{utf16,little} -

Works like unicode, but translation is done to and from little endian UTF-16 instead of UTF-8.

+

Works like unicode, but translation is done to and from little + endian UTF-16 instead of UTF-8.

- utf32 or {utf32,big} + utf32 or {utf32,big} -

Works like unicode, but translation is done to and from big endian UTF-32 instead of UTF-8.

+

Works like unicode, but translation is done to and from big + endian UTF-32 instead of UTF-8.

{utf32,little} -

Works like unicode, but translation is done to and from little endian UTF-32 instead of UTF-8.

+

Works like unicode, but translation is done to and from little + endian UTF-32 instead of UTF-8.

-

The Encoding can be changed for a file "on the fly" by using the io:setopts/2 function, why a file can be analyzed in latin1 encoding for i.e. a BOM, positioned beyond the BOM and then be set for the right encoding before further reading.See the unicode(3) module for functions identifying BOM's.

+

The Encoding can be changed for a file "on the fly" by using function + io:setopts/2. + So a file can be analyzed in latin1 encoding for, for example, a BOM, + positioned beyond the BOM and then be set for the right encoding before + further reading. For functions identifying BOMs, see module + stdlib:unicode(3).

This option is not allowed on raw files.

ram -

File must be iodata(). Returns an fd() which lets the file module operate on the data in-memory as if it is a file.

+

File must be iodata(). Returns an fd(), which lets + module file operate on the data in-memory as if it is a file.

sync -

On platforms that support it, enables the POSIX O_SYNC synchronous I/O flag or its platform-dependent - equivalent (e.g., FILE_FLAG_WRITE_THROUGH on Windows) so that writes to the file block until the data has - been physically written to disk. Be aware, though, that the exact semantics of this flag differ from platform to - platform; for example, neither Linux nor Windows guarantees that all file metadata are also written before the call - returns. For precise semantics, check the details of your platform's documentation. On platforms with no - support for POSIX O_SYNC or equivalent, use of the sync flag causes open to return - {error, enotsup}.

+

On platforms supporting it, enables the POSIX O_SYNC synchronous + I/O flag or its platform-dependent equivalent (for example, + FILE_FLAG_WRITE_THROUGH on Windows) so that writes to the file + block until the data is physically written to disk. However, be aware + that the exact semantics of this flag differ from platform to + platform. For example, none of Linux or Windows guarantees that all file + metadata are also written before the call returns. For precise semantics, + check the details of your platform documentation. On platforms with no + support for POSIX O_SYNC or equivalent, use of the sync + flag causes open to return {error, enotsup}.

Returns:

{ok, IoDevice} -

The file has been opened in the requested mode. +

The file is opened in the requested mode. IoDevice is a reference to the file.

{error, Reason} -

The file could not be opened.

+

The file cannot be opened.

-

IoDevice is really the pid of the process which +

IoDevice is really the pid of the process that handles the file. This process is linked to the process - which originally opened the file. If any process to which - the IoDevice is linked terminates, the file will - be closed and the process itself will be terminated. + that originally opened the file. If any process to which + the IoDevice is linked terminates, the file is + closed and the process itself is terminated. An IoDevice returned from this call can be used - as an argument to the IO functions (see - io(3)).

+ as an argument to the I/O functions (see + stdlib:io(3)).

-

In previous versions of file, modes were given +

In previous versions of file, modes were specified as one of the atoms read, write, or read_write instead of a list. This is still allowed - for reasons of backwards compatibility, but should not be + for reasons of backwards compatibility, but is not to be used for new code. Also note that read_write is not allowed in a mode list.

@@ -874,17 +955,17 @@ eisdir -

The named file is not a regular file. It may be a - directory, a fifo, or a device.

+

The named file is not a regular file. It can be a + directory, a FIFO, or a device.

enotdir -

A component of the file name is not a directory. On some +

A component of the filename is not a directory. On some platforms, enoent is returned instead.

enospc -

There is a no space left on the device (if write +

There is no space left on the device (if write access was specified).

@@ -892,182 +973,186 @@
- Read Erlang terms from a file + Read Erlang terms from a file.

Searches the path Path (a list of directory names) until the file Filename is found. If Filename is an absolute filename, Path is ignored. - Then reads Erlang terms, separated by '.', from the file. - Returns one of the following:

+ Then reads Erlang terms, separated by '.', from the file.

+

Returns one of the following:

{ok, Terms, FullName} -

The file was successfully read. FullName is +

The file is successfully read. FullName is the full name of the file.

{error, enoent} -

The file could not be found in any of the directories in +

The file cannot be found in any of the directories in Path.

{error, atom()}

An error occurred when opening the file or reading it. - See open/2 for a list - of typical error codes.

+ For a list of typical error codes, see + open/2.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang terms in - the file. Use format_error/1 to convert - the three-element tuple to an English description of + the file. Use + format_error/1 + to convert the three-element tuple to an English description of the error.

-

The encoding of of Filename can be set - by a comment as described in epp(3).

+

The encoding of Filename can be set + by a comment as described in + epp(3).

- Evaluate Erlang expressions in a file + Evaluate Erlang expressions in a file.

Searches the path Path (a list of directory names) until the file Filename is found. - If Filename is an absolute file name, + If Filename is an absolute filename, Path is ignored. Then reads and evaluates Erlang expressions, separated by '.' (or ',', a sequence of expressions is also an expression), from the file. - The actual result of evaluation is not returned; any + The result of evaluation is not returned; any expression sequence in the file must be there for its side - effect. Returns one of the following:

+ effect.

+

Returns one of the following:

{ok, FullName} -

The file was read and evaluated. FullName is +

The file is read and evaluated. FullName is the full name of the file.

{error, enoent} -

The file could not be found in any of the directories in +

The file cannot be found in any of the directories in Path.

{error, atom()}

An error occurred when opening the file or reading it. - See open/2 for a list - of typical error codes.

+ For a list of typical error codes, see + open/2.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang - expressions in the file. Use format_error/1 to - convert the three-element tuple to an English description + expressions in the file. Use + format_error/1 + to convert the three-element tuple to an English description of the error.

-

The encoding of of Filename can be set - by a comment as described in epp(3).

+

The encoding of Filename can be set + by a comment as described in + stdlib:epp(3).

- Open a file + Open a file.

Searches the path Path (a list of directory names) until the file Filename is found. If Filename - is an absolute file name, Path is ignored. - Then opens the file in the mode determined by Modes. - Returns one of the following:

+ is an absolute filename, Path is ignored. + Then opens the file in the mode determined by Modes.

+

Returns one of the following:

{ok, IoDevice, FullName} -

The file has been opened in the requested mode. +

The file is opened in the requested mode. IoDevice is a reference to the file and FullName is the full name of the file.

{error, enoent} -

The file could not be found in any of the directories in +

The file cannot be found in any of the directories in Path.

{error, atom()} -

The file could not be opened.

+

The file cannot be opened.

- Evaluate and return the value of Erlang expressions in a file + Evaluate and return the value of Erlang expressions in a file.

Searches the path Path (a list of directory names) until the file Filename is found. - If Filename is an absolute file name, + If Filename is an absolute filename, Path is ignored. Then reads and evaluates Erlang expressions, separated by '.' (or ',', a - sequence of expressions is also an expression), from the file. - Returns one of the following:

+ sequence of expressions is also an expression), from the file.

+

Returns one of the following:

{ok, Value, FullName} -

The file was read and evaluated. FullName is +

The file is read and evaluated. FullName is the full name of the file and Value the value of the last expression.

{error, enoent} -

The file could not be found in any of the directories in +

The file cannot be found in any of the directories in Path.

{error, atom()}

An error occurred when opening the file or reading it. - See open/2 for a list - of typical error codes.

+ For a list of typical error codes, see + open/2.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang - expressions in the file. Use format_error/1 to - convert the three-element tuple to an English description + expressions in the file. Use + format_error/1 + to convert the three-element tuple to an English description of the error.

-

The encoding of of Filename can be set - by a comment as described in epp(3).

+

The encoding of Filename can be set + by a comment as described in + stdlib:epp(3).

- Evaluate and return the value of Erlang expressions in a file + Evaluate and return the value of Erlang expressions in a file.

The same as path_script/2 but the variable bindings Bindings are used in the evaluation. See - erl_eval(3) about + erl_eval(3) about variable bindings.

- Return the name of the file handled by a pid + Return the name of the file handled by a pid. -

If Pid is an IO device, that is, a pid returned from +

If Pid is an I/O device, that is, a pid returned from open/2, this function returns the filename, or rather:

{ok, Filename} -

If this node's file server is not a slave, the file was - opened by this node's file server, (this implies that +

If the file server of this node is not a slave, the file was + opened by the file server of this node (this implies that Pid must be a local pid) and the file is not closed. Filename is the filename in flat string format.

@@ -1084,13 +1169,12 @@
- Set position in a file + Set position in a file.

Sets the position of the file referenced by IoDevice - to Location. Returns - {ok, NewPosition} (as - absolute offset) if successful, otherwise - {error, Reason}. Location is + to Location. Returns {ok, NewPosition} + (as absolute offset) if successful, otherwise + {error, Reason}. Location is one of the following:

Offset @@ -1114,14 +1198,21 @@

The same as above with Offset 0.

-

Note that offsets are counted in bytes, not in characters. If the file is opened using some other encoding than latin1, one byte does not correspond to one character. Positioning in such a file can only be done to known character boundaries, i.e. to a position earlier retrieved by getting a current position, to the beginning/end of the file or to some other position known to be on a correct character boundary by some other means (typically beyond a byte order mark in the file, which has a known byte-size).

-

Typical error reasons are:

+

Notice that offsets are counted in bytes, not in characters. If the file + is opened using some other encoding than latin1, one byte + does not correspond to one character. Positioning in such a file can only + be done to known character boundaries. That is, to a position earlier retrieved + by getting a current position, to the beginning/end of the file or to some + other position known to be on a correct character boundary by some + other means (typically beyond a byte order mark in the file, which has a + known byte-size).

+

A typical error reason is:

einval -

Either Location was illegal, or it +

Either Location is illegal, or it is evaluated to a - negative offset in the file. Note that if the resulting + negative offset in the file. Notice that if the resulting position is a negative value, the result is an error, and after the call the file position is undefined.

@@ -1130,7 +1221,7 @@
- Read from a file at certain positions + Read from a file at certain positions.

Performs a sequence of pread/3 in one operation, which is more efficient than calling them one at a time. @@ -1139,70 +1230,94 @@ where each Data, the result of the corresponding pread, is either a list or a binary depending on the mode of the file, or eof if the requested position - was beyond end of file.

-

As the position is given as a byte-offset, special caution has to be taken when working with files where encoding is set to something else than latin1, as not every byte position will be a valid character boundary on such a file.

+ is beyond end of file.

+

As the position is specified as a byte-offset, take special caution + when working with files where encoding is set to something else + than latin1, as not every byte position is a valid character + boundary on such a file.

- Read from a file at a certain position + Read from a file at a certain position.

Combines position/2 and read/2 in one operation, which is more efficient than calling them one at a - time. If IoDevice has been opened in raw mode, - some restrictions apply: Location is only allowed - to be an - integer; and the current position of the file is undefined - after the operation.

-

As the position is given as a byte-offset, special caution has to be taken when working with files where encoding is set to something else than latin1, as not every byte position will be a valid character boundary on such a file.

+ time. If IoDevice is opened in raw mode, + some restrictions apply:

+ + Location is only allowed to be an + integer. + The current position of the file is undefined after the + operation. + +

As the position is specified as a byte-offset, take special caution + when working with files where encoding is set to something else + than latin1, as not every byte position is a valid character + boundary on such a file.

- Write to a file at certain positions + Write to a file at certain positions.

Performs a sequence of pwrite/3 in one operation, which is more efficient than calling them one at a time. Returns ok or {error, {N, Reason}}, where - N is the number of successful writes that was done + N is the number of successful writes done before the failure.

-

When positioning in a file with other encoding than latin1, caution must be taken to set the position on a correct character boundary, see position/2 for details.

+

When positioning in a file with other encoding than latin1, + caution must be taken to set the position on a correct character boundary. + For details, see position/2.

- Write to a file at a certain position + Write to a file at a certain position.

Combines position/2 and write/2 in one operation, which is more efficient than calling them one at a - time. If IoDevice has been opened in raw mode, - some restrictions apply: Location is only allowed - to be an - integer; and the current position of the file is undefined - after the operation.

-

When positioning in a file with other encoding than latin1, caution must be taken to set the position on a correct character boundary, see position/2 for details.

+ time. If IoDevice has been opened in raw mode, + some restrictions apply:

+ + Location is only allowed to be an + integer. + The current position of the file is undefined after the + operation. + +

When positioning in a file with other encoding than latin1, + caution must be taken to set the position on a correct character boundary. + For details, see position/2.

- Read from a file + Read from a file.

Reads Number bytes/characters from the file referenced by IoDevice. The functions - read/2, pread/3 - and read_line/1 are the only ways to read from a file - opened in raw mode (although they work for normally opened - files, too).

-

For files where encoding is set to something else than latin1, one character might be represented by more than one byte on the file. The parameter Number always denotes the number of characters read from the file, while the position in the file might be moved much more than this number when reading a Unicode file.

-

Also, if encoding is set to something else than latin1, the read/3 call will fail if the data contains characters larger than 255, which is why the io(3) module is to be preferred when reading such a file.

+ read/2, + pread/3, and + read_line/1 + are the only ways to read from a file opened in raw mode + (although they work for normally opened files, too).

+

For files where encoding is set to something else than latin1, + one character can be represented by more than one byte on the file. + The parameter Number always denotes the number of characters + read from the file, while the position in the file can be moved much more than + this number when reading a Unicode file.

+

Also, if encoding is set to something else than latin1, + the read/3 call fails if the data contains characters larger than 255, + which is why module io(3) + is to be preferred when reading such a file.

The function returns:

{ok, Data}

If the file was opened in binary mode, the read bytes are returned in a binary, otherwise in a list. The list or - binary will be shorter than the number of bytes requested + binary is shorter than the number of bytes requested if end of file was reached.

eof @@ -1223,14 +1338,16 @@ {no_translation, unicode, latin1} -

The file was opened with another encoding than latin1 and the data in the file can not be translated to the byte-oriented data that this function returns.

+

The file is opened with another encoding than latin1 and + the data in the file cannot be translated to the byte-oriented data that + this function returns.

- Read a file + Read a file.

Returns {ok, Binary}, where Binary is a binary @@ -1254,7 +1371,7 @@ enotdir -

A component of the file name is not a directory. On some +

A component of the filename is not a directory. On some platforms, enoent is returned instead.

enomem @@ -1267,34 +1384,38 @@ - Get information about a file + Retrieve information about a file.

Retrieves information about a file. Returns {ok, FileInfo} if successful, otherwise {error, Reason}. FileInfo is a record - file_info, defined in the Kernel include file + file_info, defined in the Kernel include file file.hrl. Include the following directive in the module from which the function is called:

--include_lib("kernel/include/file.hrl"). -

The time type returned in atime, mtime and ctime - is dependent on the time type set in Opts :: {time, Type}. - Type local will return local time, universal will - return universal time and posix will return seconds since - or before unix time epoch which is 1970-01-01 00:00 UTC. - Default is {time, local}. -

-

If the raw option is set, the file server will not be called - and only informations about local files will be returned.

- -

- Since file times is stored in posix time on most OS it is - faster to query file information with the posix option. -

-
+ -include_lib("kernel/include/file.hrl").
+

The time type returned in atime, mtime, and ctime + is dependent on the time type set in Opts :: {time, Type} as + follows:

+ + local +

Returns local time.

+ universal +

Returns universal time.

+ posix +

Returns seconds since or before Unix time epoch, + which is 1970-01-01 00:00 UTC.

+
+

Default is {time, local}.

+

If the option raw is set, the file server is not called + and only information about local files is returned.

+ +

As file times are stored in POSIX time on most OS, it is faster to + query file information with option posix.

+
-

The record file_info contains the following fields.

+

The record file_info contains the following fields:

size = integer() >= 0 @@ -1308,19 +1429,25 @@

The current system access to the file.

- atime = date_time() | integer() >= 0 + atime = + date_time() | + integer() >= 0

The last time the file was read.

- mtime = date_time() | integer() >= 0 + mtime = + date_time() | + integer() >= 0

The last time the file was written.

- ctime = date_time() | integer() >=0 + ctime = + date_time() | + integer() >=0

The interpretation of this time field depends on the operating system. On Unix, it is the last time - the file or the inode was changed. In Windows, it is + the file or the inode was changed. In Windows, it is the create time.

mode = integer() >= 0 @@ -1328,36 +1455,36 @@

The file permissions as the sum of the following bit values:

- 8#00400 - read permission: owner - 8#00200 - write permission: owner - 8#00100 - execute permission: owner - 8#00040 - read permission: group - 8#00020 - write permission: group - 8#00010 - execute permission: group - 8#00004 - read permission: other - 8#00002 - write permission: other - 8#00001 - execute permission: other - 16#800 - set user id on execution - 16#400 - set group id on execution + 8#00400 +

read permission: owner

+ 8#00200 +

write permission: owner

+ 8#00100 +

execute permission: owner

+ 8#00040 +

read permission: group

+ 8#00020 +

write permission: group

+ 8#00010 +

execute permission: group

+ 8#00004 +

read permission: other

+ 8#00002 +

write permission: other

+ 8#00001 +

execute permission: other

+ 16#800 +

set user id on execution

+ 16#400 +

set group id on execution

-

On Unix platforms, other bits than those listed above - may be set.

+

On Unix platforms, the following bits + can also be set:

links = integer() >= 0 -

Number of links to the file (this will always be 1 for - file systems which have no concept of links).

+

Number of links to the file (this is always 1 for + file systems that have no concept of links).

major_device = integer() >= 0 @@ -1373,17 +1500,17 @@ inode = integer() >= 0

Gives the inode number. On non-Unix file systems, - this field will be zero.

+ this field is zero.

uid = integer() >= 0 -

Indicates the owner of the file. Will be zero for - non-Unix file systems.

+

Indicates the owner of the file. On non-Unix file systems, + this field is zero.

gid = integer() >= 0

Gives the group that the owner of the file belongs to. - Will be zero for non-Unix file systems.

+ On non-Unix file systems, this field is zero.

Typical error reasons:

@@ -1399,7 +1526,7 @@ enotdir -

A component of the file name is not a directory. On some +

A component of the filename is not a directory. On some platforms, enoent is returned instead.

@@ -1407,18 +1534,34 @@ - Read a line from a file + Read a line from a file.

Reads a line of bytes/characters from the file referenced by - IoDevice. Lines are defined to be delimited by the linefeed (LF, \n) character, but any carriage return (CR, \r) followed by a newline is also treated as a single LF character (the carriage return is silently ignored). The line is returned including the LF, but excluding any CR immediately followed by a LF. This behaviour is consistent with the behaviour of io:get_line/2. If end of file is reached without any LF ending the last line, a line with no trailing LF is returned.

-

The function can be used on files opened in raw mode. It is however inefficient to use it on raw files if the file is not opened with the option {read_ahead, Size} specified, why combining raw and {read_ahead, Size} is highly recommended when opening a text file for raw line oriented reading.

-

If encoding is set to something else than latin1, the read_line/1 call will fail if the data contains characters larger than 255, why the io(3) module is to be preferred when reading such a file.

+ IoDevice. Lines are defined to be delimited by the + linefeed (LF, \n) character, but any carriage return (CR, \r) + followed by a newline is also treated as a single LF character (the carriage + return is silently ignored). The line is returned including the LF, + but excluding any CR immediately followed by an LF. This behaviour is + consistent with the behaviour of + io:get_line/2. + If end of file is reached without any LF ending the last line, a line with no + trailing LF is returned.

+

The function can be used on files opened in raw mode. However, it is + inefficient to use it on raw files if the file is not opened with + option {read_ahead, Size} specified. Thus, combining raw and + {read_ahead, Size} is highly recommended when opening a text file for + raw line-oriented reading.

+

If encoding is set to something else than latin1, the + read_line/1 call fails if the data contains characters larger than 255, + why module stdlib:io(3) is to be + preferred when reading such a file.

The function returns:

{ok, Data} -

One line from the file is returned, including the trailing LF, but with CRLF sequences replaced by a single LF (see above).

-

If the file was opened in binary mode, the read bytes are +

One line from the file is returned, including the trailing LF, + but with CRLF sequences replaced by a single LF (see above).

+

If the file is opened in binary mode, the read bytes are returned in a binary, otherwise in a list.

eof @@ -1439,22 +1582,24 @@ {no_translation, unicode, latin1} -

The file is was opened with another encoding than latin1 and the data on the file can not be translated to the byte-oriented data that this function returns.

+

The file is opened with another encoding than latin1 and + the data on the file cannot be translated to the byte-oriented data that + this function returns.

- See what a link is pointing to + See what a link is pointing to. -

This function returns +

Returns {ok, Filename} if Name refers to a symbolic link that is - not a "raw" file name, or {error, Reason} + not a raw filename, or {error, Reason} otherwise. On platforms that do not support symbolic links, the return - value will be {error,enotsup}.

+ value is {error,enotsup}.

Typical error reasons:

einval @@ -1476,14 +1621,14 @@
- See what a link is pointing to + See what a link is pointing to. -

This function returns {ok, Filename} if +

Returns {ok, Filename} if Name refers to a symbolic link or {error, Reason} otherwise. On platforms that do not support symbolic links, the return - value will be {error,enotsup}.

-

Note that Filename can be either a list + value is {error,enotsup}.

+

Notice that Filename can be either a list or a binary.

Typical error reasons:

@@ -1505,31 +1650,30 @@ - Get information about a link or file + Retrieve information about a link or file. -

This function works like - read_file_info/1,2 except that - if Name is a symbolic link, information about - the link will be returned in the file_info record and - the type field of the record will be set to - symlink.

-

If the raw option is set, the file server will not be called - and only informations about local files will be returned.

+

Works like + read_file_info/1,2 + except that if Name is a symbolic link, information + about the link is returned in the file_info record and + the type field of the record is set to symlink.

+

If the option raw is set, the file server is not called + and only information about local files is returned.

If Name is not a symbolic link, this function returns - exactly the same result as read_file_info/1. + the same result as read_file_info/1. On platforms that do not support symbolic links, this function is always equivalent to read_file_info/1.

- Rename a file + Rename a file.

Tries to rename the file Source to Destination. It can be used to move files (and directories) between directories, but it is not sufficient to specify - the destination only. The destination file name must also be + the destination only. The destination filename must also be specified. For example, if bar is a normal file and foo and baz are directories, rename("foo/bar", "baz") returns an error, but @@ -1560,7 +1704,7 @@

Source is a root directory, or Destination - is a sub-directory of Source.

+ is a subdirectory of Source.

eisdir @@ -1586,58 +1730,105 @@
- Evaluate and return the value of Erlang expressions in a file + Evaluate and return the value of Erlang expressions in a file.

Reads and evaluates Erlang expressions, separated by '.' (or ',', a sequence of expressions is also an expression), from - the file. Returns one of the following:

+ the file.

+

Returns one of the following:

{ok, Value} -

The file was read and evaluated. Value is +

The file is read and evaluated. Value is the value of the last expression.

{error, atom()}

An error occurred when opening the file or reading it. - See open/2 for a list - of typical error codes.

+ For a list of typical error codes, see + open/2.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang - expressions in the file. Use format_error/1 to - convert the three-element tuple to an English description + expressions in the file. Use + format_error/1 + to convert the three-element tuple to an English description of the error.

-

The encoding of of Filename can be set - by a comment as described in epp(3).

+

The encoding of Filename can be set + by a comment as described in + epp(3).

- Evaluate and return the value of Erlang expressions in a file + Evaluate and return the value of Erlang expressions in a file.

The same as script/1 but the variable bindings Bindings are used in the evaluation. See - erl_eval(3) about + erl_eval(3) about variable bindings.

+ + + Send a file to a socket. + +

Sends the file Filename to Socket. + Returns {ok, BytesSent} if successful, + otherwise {error, Reason}.

+
+
+ + + Send a file to a socket. + + +

Sends Bytes from the file + referenced by RawFile beginning at Offset to + Socket. + Returns {ok, BytesSent} if successful, + otherwise {error, Reason}. If Bytes is set to + 0 all data after the specified Offset is sent.

+

The file used must be opened using the raw flag, and the process + calling sendfile must be the controlling process of the socket. + See gen_tcp:controlling_process/2.

+

If the OS used does not support sendfile, an Erlang fallback + using + read/2 and + gen_tcp:send/2 is used.

+

The option list can contain the following options:

+ + chunk_size +

The chunk size used by the Erlang fallback to send + data. If using the fallback, set this to a value + that comfortably fits in the systems memory. Default is 20 MB.

+ use_threads +

Instructs the emulator to use the async thread pool for the + sendfile system call. This can be useful if the OS you are running + on does not properly support non-blocking sendfile calls. Notice that + using async threads potentially makes your system vulnerable to slow + client attacks. If set to true and no async threads are available, + the sendfile call returns {error,einval}. + Introduced in Erlang/OTP 17.0. Default is false.

+
+
+
- Set the current working directory + Set the current working directory.

Sets the current working directory of the file server to Dir. Returns ok if successful.

-

The functions in the file module usually treat binaries - as raw filenames, i.e. they are passed as is even when the encoding - of the binary does not agree with file:native_name_encoding(). - This function however expects binaries to be encoded according to the - value returned by file:native_name_encoding().

+

The functions in the module file usually treat binaries + as raw filenames, that is, they are passed "as is" even when the + encoding of the binary does not agree with + native_name_encoding(). + However, this function expects binaries to be encoded according to the + value returned by native_name_encoding().

Typical error reasons are:

enoent @@ -1656,31 +1847,31 @@ badarg -

Dir had an improper type, +

Dir has an improper type, such as tuple.

no_translation

Dir is a binary() with characters coded in ISO-latin-1 and the VM is operating - with unicode file name encoding.

+ with unicode filename encoding.

-

In a future release, a bad type for the +

In a future release, a bad type for argument Dir - argument will probably generate an exception.

+ will probably generate an exception.

- Synchronizes the in-memory state of a file with that on the physical medium + Synchronize the in-memory state of a file with that on the physical medium. -

Makes sure that any buffers kept by the operating system +

Ensures that any buffers kept by the operating system (not by the Erlang runtime system) are written to disk. On some platforms, this function might have no effect.

-

Typical error reasons are:

+

A typical error reason is:

enospc @@ -1689,91 +1880,29 @@
- - - Synchronizes the in-memory data of a file, ignoring most of its metadata, with that on the physical medium - -

Makes sure that any buffers kept by the operating system - (not by the Erlang runtime system) are written to disk. In - many ways it resembles fsync but it does not update - some of the file's metadata such as the access time. On - some platforms this function has no effect.

-

Applications that access databases or log files often write - a tiny data fragment (e.g., one line in a log file) and then - call fsync() immediately in order to ensure that the written - data is physically stored on the harddisk. Unfortunately, fsync() - will always initiate two write operations: one for the newly - written data and another one in order to update the modification - time stored in the inode. If the modification time is not a part - of the transaction concept, fdatasync() can be used to avoid - unnecessary inode disk write operations.

-

Available only in some POSIX systems, this call results in a - call to fsync(), or has no effect in systems not implementing - the fdatasync() syscall.

-
-
- Truncate a file + Truncate a file.

Truncates the file referenced by IoDevice at - the current position. Returns ok if successful, + the current position. Returns ok if successful, otherwise {error, Reason}.

- - - send a file to a socket - -

Sends the file Filename to Socket. - Returns {ok, BytesSent} if successful, - otherwise {error, Reason}.

-
-
- - - send a file to a socket - - -

Sends Bytes from the file - referenced by RawFile beginning at Offset to - Socket. - Returns {ok, BytesSent} if successful, - otherwise {error, Reason}. If Bytes is set to - 0 all data after the given Offset is sent.

-

The file used must be opened using the raw flag, and the process - calling sendfile must be the controlling process of the socket. - See gen_tcp:controlling_process/2

-

If the OS used does not support sendfile, an Erlang fallback - using file:read and gen_tcp:send is used.

-

The option list can contain the following options:

- - chunk_size - The chunk size used by the erlang fallback to send - data. If using the fallback, this should be set to a value - which comfortably fits in the systems memory. Default is 20 MB. - use_threads - Instruct the emulator to use the async thread pool for the - sendfile system call. This could be usefull if the OS you are running - on does not properly support non-blocking sendfile calls. Do note that - using async threads potentially makes your system volnerable to slow - client attacks. If set to true and no async threads are available, - the sendfile call will return {error,einval}. - Introduced in Erlang/OTP 17.0. Default is false. - -
-
- Write to a file + Write to a file.

Writes Bytes to the file referenced by IoDevice. This function is the only way to write to a - file opened in raw mode (although it works for normally - opened files, too). Returns ok if successful, and + file opened in raw mode (although it works for normally opened + files too). Returns ok if successful, and {error, Reason} otherwise.

-

If the file is opened with encoding set to something else than latin1, each byte written might result in several bytes actually being written to the file, as the byte range 0..255 might represent anything between one and four bytes depending on value and UTF encoding type.

-

Typical error reasons are:

+

If the file is opened with encoding set to something else than + latin1, each byte written can result in many bytes being written to + the file, as the byte range 0..255 can represent anything between one and + four bytes depending on value and UTF encoding type.

+

Typical error reasons:

ebadf @@ -1781,34 +1910,35 @@ enospc -

There is a no space left on the device.

+

No space is left on the device.

- Write a file + Write a file. -

Writes the contents of the iodata term Bytes - to the file Filename. - The file is created if it does not - exist. If it exists, the previous contents are - overwritten. Returns ok, or {error, Reason}.

-

Typical error reasons are:

+

Writes the contents of the iodata term Bytes + to file Filename. + The file is created if it does not exist. + If it exists, the previous contents are overwritten. + Returns ok if successful, otherwise + {error, Reason}.

+

Typical error reasons:

enoent -

A component of the file name does not exist.

+

A component of the filename does not exist.

enotdir -

A component of the file name is not a directory. On some +

A component of the filename is not a directory. On some platforms, enoent is returned instead.

enospc -

There is a no space left on the device.

+

No space is left on the device.

eacces @@ -1824,51 +1954,64 @@
- Write a file + Write a file.

Same as write_file/2, but takes a third argument Modes, a list of possible modes, see - open/2. The mode flags - binary and write are implicit, so they should - not be used.

+ open/2. The mode flags + binary and write are implicit, so they are + not to be used.

- Change information about a file + Change file information. -

Change file information. Returns ok if successful, +

Changes file information. Returns ok if successful, otherwise {error, Reason}. FileInfo is a record - file_info, defined in the Kernel include file + file_info, defined in the Kernel include file file.hrl. Include the following directive in the module from which the function is called:

--include_lib("kernel/include/file.hrl"). -

The time type set in atime, mtime and ctime - is dependent on the time type set in Opts :: {time, Type}. - Type local will interpret the time set as local, universal will - interpret it as universal time and posix must be seconds since - or before unix time epoch which is 1970-01-01 00:00 UTC. - Default is {time, local}.

-

If the raw option is set, the file server will not be called - and only informations about local files will be returned.

+ -include_lib("kernel/include/file.hrl"). +

The time type set in atime, mtime, and ctime + depends on the time type set in Opts :: {time, Type} as + follows:

+ + local +

Interprets the time set as local.

+ universal +

Interprets it as universal time.

+ posix +

Must be seconds since or before Unix time epoch, + which is 1970-01-01 00:00 UTC.

+
+

Default is {time, local}.

+

If the option raw is set, the file server is not called + and only information about local files is returned.

The following fields are used from the record, if they are - given.

+ specified:

- atime = date_time() | integer() >= 0 + atime = + date_time() | + integer() >= 0

The last time the file was read.

- mtime = date_time() | integer() >= 0 + mtime = + date_time() | + integer() >= 0

The last time the file was written.

- ctime = date_time() | integer() >= 0 + ctime = + date_time() | + integer() >= 0 -

On Unix, any value give for this field will be ignored - (the "ctime" for the file will be set to the current +

On Unix, any value specified for this field is ignored + (the "ctime" for the file is set to the current time). On Windows, this field is the new creation time to set for the file.

@@ -1877,40 +2020,40 @@

The file permissions as the sum of the following bit values:

- 8#00400 - read permission: owner - 8#00200 - write permission: owner - 8#00100 - execute permission: owner - 8#00040 - read permission: group - 8#00020 - write permission: group - 8#00010 - execute permission: group - 8#00004 - read permission: other - 8#00002 - write permission: other - 8#00001 - execute permission: other - 16#800 - set user id on execution - 16#400 - set group id on execution + 8#00400 +

Read permission: owner

+ 8#00200 +

Write permission: owner

+ 8#00100 +

Execute permission: owner

+ 8#00040 +

Read permission: group

+ 8#00020 +

Write permission: group

+ 8#00010 +

Execute permission: group

+ 8#00004 +

Read permission: other

+ 8#00002 +

Write permission: other

+ 8#00001 +

Execute permission: other

+ 16#800 +

Set user id on execution

+ 16#400 +

Set group id on execution

-

On Unix platforms, other bits than those listed above - may be set.

+

On Unix platforms, the following bits + can also be set.

uid = integer() >= 0 -

Indicates the owner of the file. Ignored for non-Unix +

Indicates the file owner. Ignored for non-Unix file systems.

gid = integer() >= 0 -

Gives the group that the owner of the file belongs to. +

Gives the group that the file owner belongs to. Ignored for non-Unix file systems.

@@ -1927,7 +2070,7 @@ enotdir -

A component of the file name is not a directory. On some +

A component of the filename is not a directory. On some platforms, enoent is returned instead.

@@ -1938,77 +2081,82 @@
POSIX Error Codes - eacces - permission denied - eagain - resource temporarily unavailable - ebadf - bad file number - ebusy - file busy - edquot - disk quota exceeded - eexist - file already exists - efault - bad address in system call argument - efbig - file too large - eintr - interrupted system call - einval - invalid argument - eio - IO error - eisdir - illegal operation on a directory - eloop - too many levels of symbolic links - emfile - too many open files - emlink - too many links - enametoolong - file name too long - enfile - file table overflow - enodev - no such device - enoent - no such file or directory - enomem - not enough memory - enospc - no space left on device - enotblk - block device required - enotdir - not a directory - enotsup - operation not supported - enxio - no such device or address - eperm - not owner - epipe - broken pipe - erofs - read-only file system - espipe - invalid seek - esrch - no such process - estale - stale remote file handle - exdev - cross-domain link + eacces - Permission denied + eagain - Resource temporarily unavailable + ebadf - Bad file number + ebusy - File busy + edquot - Disk quota exceeded + eexist - File already exists + efault - Bad address in system call argument + efbig - File too large + eintr - Interrupted system call + einval - Invalid argument + eio - I/O error + eisdir - Illegal operation on a directory + eloop - Too many levels of symbolic links + emfile - Too many open files + emlink - Too many links + enametoolong - Filename too long + enfile - File table overflow + enodev - No such device + enoent - No such file or directory + enomem - Not enough memory + enospc - No space left on device + enotblk - Block device required + enotdir - Not a directory + enotsup - Operation not supported + enxio - No such device or address + eperm - Not owner + epipe - Broken pipe + erofs - Read-only file system + espipe - Invalid seek + esrch - No such process + estale - Stale remote file handle + exdev - Cross-domain link
Performance -

Some operating system file operations, for example a - sync/1 or close/1 on a huge file, may block their - calling thread for seconds. If this befalls the emulator main +

Some operating system file operations, for example, a + sync/1 or close/1 on a huge file, can block their + calling thread for seconds. If this affects the emulator main thread, the response time is no longer in the order of milliseconds, depending on the definition of "soft" in soft real-time system.

If the device driver thread pool is active, file operations are done through those threads instead, so the emulator can go on executing Erlang processes. Unfortunately, the time for serving a - file operation increases due to the extra scheduling required + file operation increases because of the extra scheduling required from the operating system.

If the device driver thread pool is disabled or of size 0, large - file reads and writes are segmented into several smaller, which - enables the emulator so server other processes during the file - operation. This gives the same effect as when using the thread + file reads and writes are segmented into many smaller, which + enable the emulator to serve other processes during the file + operation. This has the same effect as when using the thread pool, but with larger overhead. Other file operations, for - example sync/1 or close/1 on a huge file, still are + example, sync/1 or close/1 on a huge file, still are a problem.

For increased performance, raw files are recommended. Raw files - uses the file system of the node's host machine. For normal files - (non-raw), the file server is used to find the files, and if - the node is running its file server as slave to another node's, - and the other node runs on some other host machine, they may have - different file systems. This is seldom a problem, but you have - now been warned.

-

A normal file is really a process so it can be used as an IO - device (see io). Therefore when data is written to a + use the file system of the host machine of the node.

+ +

+ For normal files (non-raw), the file server is used to find the files, + and if the node is running its file server as slave to the file server + of another node, and the other node runs on some other host machine, + they can have different file systems. + However, this is seldom a problem.

+
+

A normal file is really a process so it can be used as an I/O + device (see + io). + Therefore, when data is written to a normal file, the sending of the data to the file process, copies all data that are not binaries. Opening the file in binary mode and writing binaries is therefore recommended. If the file is opened on another node, or if the file server runs as slave to - another node's, also binaries are copied.

+ the file server of another node, also binaries are copied.

Caching data to reduce the number of file operations, or rather - the number of calls to the file driver, will generally increase + the number of calls to the file driver, generally increases performance. The following function writes 4 MBytes in 23 seconds when tested:

create_file_slow(FD, M, N) -> ok = file:write(FD, <>), create_file_slow(FD, M+1, N).]]> +

The following, functionally equivalent, function collects 1024 entries into a list of 128 32-byte binaries before each call to - file:write/2 and so does the same work in 0.52 seconds, - which is 44 times faster.

+ write/2 and so + does the same work in 0.52 seconds, + which is 44 times faster:

= 0 -> {ok, FD} = file:open(Name, [raw, write, delayed_write, binary]), @@ -2055,61 +2205,62 @@ create_file(FD, M, N0, R) when M + 8 =< N0 -> create_file(FD, M, N0, R) -> N1 = N0-1, create_file(FD, M, N1, [<> | R]).]]> +

Trust only your own benchmarks. If the list length in - create_file/2 above is increased, it will run slightly - faster, but consume more memory and cause more memory + create_file/2 above is increased, it runs slightly + faster, but consumes more memory and causes more memory fragmentation. How much this affects your application is - something that this simple benchmark can not predict.

-

If the size of each binary is increased to 64 bytes, it will - also run slightly faster, but the code will be twice as clumsy. - In the current implementation are binaries larger than 64 bytes + something that this simple benchmark cannot predict.

+

If the size of each binary is increased to 64 bytes, it + also runs slightly faster, but the code is then twice as clumsy. + In the current implementation, binaries larger than 64 bytes are stored in memory common to all processes and not copied when sent between processes, while these smaller binaries are stored on the process heap and copied when sent like any other term.

-

So, with a binary size of 68 bytes create_file/2 runs - 30 percent slower then with 64 bytes, and will cause much more - memory fragmentation. Note that if the binaries were to be sent - between processes (for example a non-raw file) the results +

So, with a binary size of 68 bytes, create_file/2 runs + 30 percent slower than with 64 bytes, and causes much more + memory fragmentation. Notice that if the binaries were to be sent + between processes (for example, a non-raw file), the results would probably be completely different.

A raw file is really a port. When writing data to a port, it is - efficient to write a list of binaries. There is no need to + efficient to write a list of binaries. It is not needed to flatten a deep list before writing. On Unix hosts, scatter output, which writes a set of buffers in one operation, is used when - possible. In this way file:write(FD, [Bin1, Bin2 | Bin3]) - will write the contents of the binaries without copying the data - at all except for perhaps deep down in the operating system + possible. In this way write(FD, [Bin1, Bin2 | Bin3]) + writes the contents of the binaries without copying the data + at all, except for perhaps deep down in the operating system kernel.

For raw files, pwrite/2 and pread/2 are efficiently implemented. The file driver is called only once for the whole operation, and the list iteration is done in the file driver.

The options delayed_write and read_ahead to - file:open/2 makes the file driver cache data to reduce + open/2 + make the file driver cache data to reduce the number of operating system calls. The function - create_file/2 in the example above takes 60 seconds - seconds without the delayed_write option, which is 2.6 + create_file/2 in the recent example takes 60 seconds + without option delayed_write, which is 2.6 times slower.

-

And, as a really bad example, create_file_slow/2 above - without the raw, binary and delayed_write - options, that is it calls file:open(Name, [write]), needs +

As a bad example, create_file_slow/2 + without options raw, binary, and delayed_write, + meaning it calls open(Name, [write]), needs 1 min 20 seconds for the job, which is 3.5 times slower than the first example, and 150 times slower than the optimized - create_file/2.

-
- -
- Warnings -

If an error occurs when accessing an open file with the io - module, the process which handles the file will exit. The dead - file process might hang if a process tries to access it later. + create_file/2.

+ +

If an error occurs when accessing an open file with module + io, + the process handling the file exits. The dead + file process can hang if a process tries to access it later. This will be fixed in a future release.

+
- SEE ALSO -

filename(3)

+ See Also +

filename(3)

diff --git a/lib/kernel/doc/src/gen_sctp.xml b/lib/kernel/doc/src/gen_sctp.xml index 456108a2fe..0d938d550b 100644 --- a/lib/kernel/doc/src/gen_sctp.xml +++ b/lib/kernel/doc/src/gen_sctp.xml @@ -30,68 +30,60 @@ 2007-03-21 A - gen_sctp.sgml + gen_sctp.xml gen_sctp - The gen_sctp module provides functions for communicating with sockets using the SCTP protocol. + Functions for communicating with sockets using the SCTP + protocol. -

The gen_sctp module provides functions for communicating with +

This module provides functions for communicating with sockets using the SCTP protocol. The implementation assumes that the OS kernel supports SCTP - (RFC2960) through the user-level - Sockets API Extensions. - During development this implementation was tested on - Linux Fedora Core 5.0 (kernel 2.6.15-2054 or later is needed), - and on Solaris 10, 11. During OTP adaptation it was tested on - SUSE Linux Enterprise Server 10 (x86_64) kernel 2.6.16.27-0.6-smp, - with lksctp-tools-1.0.6, briefly on Solaris 10, and later on - SUSE Linux Enterprise Server 10 Service Pack 1 (x86_64) - kernel 2.6.16.54-0.2.3-smp with lksctp-tools-1.0.7, - and later also on FreeBSD 8.2. -

-

- This module was written for one-to-many style sockets + (RFC 2960) + through the user-level + Sockets API Extensions.

+

During development, this implementation was tested on:

+ + Linux Fedora Core 5.0 (kernel 2.6.15-2054 or later is needed) + Solaris 10, 11 + +

During OTP adaptation it was tested on:

+ + SUSE Linux Enterprise Server 10 (x86_64) kernel 2.6.16.27-0.6-smp, + with lksctp-tools-1.0.6 + Briefly on Solaris 10 + SUSE Linux Enterprise Server 10 Service Pack 1 (x86_64) + kernel 2.6.16.54-0.2.3-smp with lksctp-tools-1.0.7 + FreeBSD 8.2 + +

This module was written for one-to-many style sockets (type seqpacket). With the addition of - peeloff/2, one-to-one style - sockets (type stream) were introduced. -

-

Record definitions for the gen_sctp module can be found using:

-
  -include_lib("kernel/include/inet_sctp.hrl").    
+ peeloff/2, + one-to-one style sockets (type stream) were introduced.

+

Record definitions for this module can be found using:

+
+-include_lib("kernel/include/inet_sctp.hrl").

These record definitions use the "new" spelling 'adaptation', not the deprecated 'adaption', regardless of which spelling the underlying C API uses.

-
- - CONTENTS - - DATA TYPES - EXPORTS - SCTP SOCKET OPTIONS - SCTP EXAMPLES - SEE ALSO - - -
- assoc_id()

- An opaque term returned in for example #sctp_paddr_change{} - that identifies an association for an SCTP socket. The term - is opaque except for the special value 0 that has a - meaning such as "the whole endpoint" or "all future associations". -

+ An opaque term returned in, for example, #sctp_paddr_change{}, + which identifies an association for an SCTP socket. The term + is opaque except for the special value 0, which has a + meaning such as "the whole endpoint" or "all future associations".

-

One of the - SCTP Socket Options.

+

One of the + SCTP Socket Options.

@@ -101,8 +93,8 @@ sctp_socket() -

- Socket identifier returned from open/*.

+

Socket identifier returned from + open/*.

@@ -111,405 +103,438 @@ - Abnormally terminate the association given by Assoc, without flushing of unsent data + Abnormally terminate the association specified by + Assoc, without flushing of unsent data. -

Abnormally terminates the association given by Assoc, without +

Abnormally terminates the association specified by + Assoc, without flushing of unsent data. The socket itself remains open. Other - associations opened on this socket are still valid, and it can be - used in new associations.

+ associations opened on this socket are still valid, and the socket + can be used in new associations.

+ - Completely close the socket and all associations on it + Close the socket and all associations on it. -

Completely closes the socket and all associations on it. The unsent - data is flushed as in eof/2. The close/1 call +

Closes the socket and all associations on it. The unsent + data is flushed as in eof/2. + The close/1 call is blocking or otherwise depending of the value of - the linger socket - option. - If close does not linger or linger timeout expires, + the linger + socket option. + If close does not linger or linger time-out expires, the call returns and the data is flushed in the background.

+ Same as connect(Socket, Addr, Port, Opts, infinity). -

Same as connect(Socket, Addr, Port, Opts, infinity).

+

Same as connect(Socket, Addr, + Port, Opts, infinity).

+ - Establish a new association for the socket Socket, with a peer (SCTP server socket) + Establish a new association for socket Socket, with a + peer (SCTP server socket). -

Establishes a new association for the socket Socket, - with the peer (SCTP server socket) given by - Addr and Port. The Timeout, - is expressed in milliseconds. A socket can be associated with multiple peers.

- -

WARNING:Using a value of Timeout less than - the maximum time taken by the OS to establish an association (around 4.5 minutes - if the default values from RFC 4960 are used) can result in - inconsistent or incorrect return values. This is especially - relevant for associations sharing the same Socket - (i.e. source address and port) since the controlling process - blocks until connect/* returns. - connect_init/* - provides an alternative not subject to this limitation.

- +

Establishes a new association for socket Socket, + with the peer (SCTP server socket) specified by + Addr and Port. + Timeout, is expressed in milliseconds. + A socket can be associated with multiple peers.

+

Using a value of Timeout less than + the maximum time taken by the OS to establish an association (around + 4.5 minutes if the default values from + RFC 4960 + are used), can result + in inconsistent or incorrect return values. This is especially + relevant for associations sharing the same Socket + (that is, source address and port), as the controlling process + blocks until connect/* returns. + connect_init/* + provides an alternative without this limitation.

+

The result of connect/* is an #sctp_assoc_change{} - event which contains, in particular, the new - Association ID.

-
   #sctp_assoc_change{
-        state             = atom(),
-        error             = atom(),
-        outbound_streams  = integer(),
-        inbound_streams   = integer(),
-        assoc_id          = assoc_id()
-  }        
+ event that contains, in particular, the new + Association ID:

+
+#sctp_assoc_change{
+      state             = atom(),
+      error             = atom(),
+      outbound_streams  = integer(),
+      inbound_streams   = integer(),
+      assoc_id          = assoc_id()
+}

The number of outbound and inbound streams can be set by - giving an sctp_initmsg option to connect - as in:

-
  connect(Socket, Ip, Port>,
-        [{sctp_initmsg,#sctp_initmsg{num_ostreams=OutStreams,
-                                     max_instreams=MaxInStreams}}])        
+ giving an sctp_initmsg option to connect as in:

+
+connect(Socket, Ip, Port>,
+      [{sctp_initmsg,#sctp_initmsg{num_ostreams=OutStreams,
+                                   max_instreams=MaxInStreams}}])

All options Opt are set on the socket before the - association is attempted. If an option record has got undefined + association is attempted. If an option record has undefined field values, the options record is first read from the socket - for those values. In effect, Opt option records only - define field values to change before connecting.

+ for those values. In effect, Opt option records + only define field values to change before connecting.

The returned outbound_streams and inbound_streams - are the actual stream numbers on the socket, which may be different - from the requested values (OutStreams and MaxInStreams + are the stream numbers on the socket. These can be different + from the requested values (OutStreams and MaxInStreams, respectively) if the peer requires lower values.

-

The following values of state are possible:

- - -

comm_up: association successfully established. This - indicates a successful completion of connect.

-
- -

cant_assoc: association cannot be established - (connect/* failure).

-
-
-

All other states do not normally occur in the output from - connect/*. Rather, they may occur in +

state can have the following values:

+ + comm_up +

Association is successfully established. This + indicates a successful completion of connect.

+ cant_assoc +

The association cannot be established + (connect/* failure).

+
+

Other states do not normally occur in the output from + connect/*. Rather, they can occur in #sctp_assoc_change{} events received instead of data in - recv/* calls. - All of them indicate losing the association due to various - error conditions, and are listed here for the sake of completeness. - The error field may provide more detailed diagnostics.

- - -

comm_lost;

-
- -

restart;

-
- -

shutdown_comp.

-
-
+ recv/* calls. + All of them indicate losing the association because of various error + conditions, and are listed here for the sake of completeness:

+ + comm_lost + + restart + + shutdown_comp + + +

Field error can provide more detailed diagnostics.

+ - Same as connect_init(Socket, Addr, Port, Opts, infinity). + Same as connect_init(Socket, Addr, Port, Opts, infinity).. -

Same as connect_init(Socket, Addr, Port, Opts, infinity).

+

Same as connect_init(Socket, Addr, + Port, Opts, infinity).

+ - Initiate a new association for the socket Socket, with a peer (SCTP server socket) + Initiate a new association for socket Socket, with a + peer (SCTP server socket). -

Initiates a new association for the socket Socket, - with the peer (SCTP server socket) given by +

Initiates a new association for socket Socket, + with the peer (SCTP server socket) specified by Addr and Port.

-

The fundamental difference between this API - and connect/* is that the return value is that of the - underlying OS connect(2) system call. If ok is returned - then the result of the association establishement is received - by the calling process as - an - #sctp_assoc_change{} - event. The calling process must be prepared to receive this, or - poll for it using recv/* depending on the value of the - active option.

-

The parameters are as described - in connect/*, with the - exception of the Timeout value.

-

The timer associated with Timeout only supervises - IP resolution of Addr

+

The fundamental difference between this API + and connect/* is that the return value is that of the + underlying OS connect(2) system call. If ok is returned, + the result of the association establishment is received + by the calling process as an + #sctp_assoc_change{} + event. The calling process must be prepared to receive this, or + poll for it using + recv/*, + depending on the value of the active option.

+

The parameters are as described in + connect/*, + except the Timeout value.

+

The timer associated with Timeout only supervises + IP resolution of Addr.

+ - Assign a new controlling process pid to the socket + Assign a new controlling process pid to the socket. -

Assigns a new controlling process Pid to Socket. Same implementation - as gen_udp:controlling_process/2.

+

Assigns a new controlling process Pid to + Socket. Same implementation as + gen_udp:controlling_process/2. +

+ - Gracefully terminate the association given by Assoc, with flushing of all unsent data + Gracefully terminate the association specified by Assoc, + with flushing of all unsent data. -

Gracefully terminates the association given by Assoc, with +

Gracefully terminates the association specified by + Assoc, with flushing of all unsent data. The socket itself remains open. Other - associations opened on this socket are still valid, and it can be - used in new associations.

+ associations opened on this socket are still valid. The socket can + be used in new associations.

+
+
+ + + + Translate an SCTP error number into a string. + +

Translates an SCTP error number from, for example, + #sctp_remote_error{} or #sctp_send_failed{} into + an explanatory string, or one of the atoms ok for no + error or undefined for an unrecognized error.

+ Set up a socket to listen.

Sets up a socket to listen on the IP address and port number - it is bound to.

-

For type seqpacket sockets (the default) - IsServer must be true or false. - In contrast to TCP, in SCTP there is no listening queue length. - If IsServer is true the socket accepts new associations, i.e. - it will become an SCTP server socket.

-

For type stream sockets Backlog defines - the backlog queue length just like in TCP.

+ it is bound to.

+

For type seqpacket, sockets (the default) + IsServer must be true or false. + In contrast to TCP, there is no listening queue length in SCTP. + If IsServer is true, the socket accepts + new associations, that is, it becomes an SCTP server socket.

+

For type stream, sockets Backlog define + the backlog queue length just like in TCP.

+ - Create an SCTP socket and bind it to local addresses + Create an SCTP socket and binds it to local addresses. -

Creates an SCTP socket and binds it to the local addresses - specified by all {ip,IP} (or synonymously {ifaddr,IP}) - options (this feature is called SCTP multi-homing). - The default IP and Port are any +

Creates an SCTP socket and binds it to the local addresses + specified by all {ip,IP} (or synonymously + {ifaddr,IP}) + options (this feature is called SCTP multi-homing). The default + IP and Port are any and 0, meaning bind to all local addresses on any - one free port.

- -

Other options are:

+ free port.

+

Other options:

inet6 -

Set up the socket for IPv6.

+

Sets up the socket for IPv6.

inet -

Set up the socket for IPv4. This is the default.

+

Sets up the socket for IPv4. This is the default.

-

A default set of socket options - is used. In particular, the socket is opened in + is used. In particular, the socket is opened in binary and passive mode, - with SockType seqpacket, - and with reasonably large + with SockType seqpacket, and with reasonably large kernel and driver - buffers.

+ buffers.

+ - - Peel off a type stream socket from a type seqpacket one - + Peel off a type stream socket from a type + seqpacket one. -

- Branch off an existing association Assoc - in a socket Socket of type seqpacket - (one-to-many style) into - a new socket NewSocket of type stream - (one-to-one style). -

-

- The existing association argument Assoc - can be either a - - #sctp_assoc_change{} - - record as returned from e.g - recv/*, - connect/* or - from a listening socket in active mode. Or it can be just - the field assoc_id integer from such a record. -

+

Branches off an existing association Assoc + in a socket Socket of type seqpacket + (one-to-many style) into + a new socket NewSocket of type stream + (one-to-one style).

+

The existing association argument Assoc + can be either a + #sctp_assoc_change{} + record as returned from, for example, + recv/*, + connect/*, or + from a listening socket in active mode. It can also be just + the field assoc_id integer from such a record.

+ - Receive a message from a socket + Receive a message from a socket. -

Receives the Data message from any association of the socket. - If the receive times out {error,timeout is returned. - The default timeout is infinity. - FromIP and FromPort indicate the sender's address.

-

AncData is a list of Ancillary Data items which - may be received along with the main Data. +

Receives the Data message from any association + of the socket. + If the receive times out, {error,timeout} is returned. + The default time-out is infinity. FromIP + and FromPort indicate the address of the + sender.

+

AncData is a list of ancillary data items that + can be received along with the main Data. This list can be empty, or contain a single - #sctp_sndrcvinfo{} - record, if receiving of such ancillary data is enabled - (see option - sctp_events). - It is enabled by default, since such ancillary data - provide an easy way of determining the association and stream - over which the message has been received. - (An alternative way would be to get the Association ID from the - FromIP and FromPort using the - sctp_get_peer_addr_info socket option, - but this would still not produce the Stream number).

-

The actual Data received may be a binary(), - or list() of bytes (integers in the range 0 through 255) - depending on the socket mode, or an SCTP Event. - - - The following SCTP Events are possible:

+ #sctp_sndrcvinfo{} + record if receiving of such ancillary data is enabled (see option + sctp_events). + It is enabled by default, as such ancillary data + provides an easy way of determining the association and stream + over which the message is received. + (An alternative way is to get the association ID from + FromIP and FromPort using + socket option + sctp_get_peer_addr_info, + but this does still not produce the stream number).

+

The Data received can be a binary() + or a list() of bytes (integers in the range 0 through 255) + depending on the socket mode, or an SCTP event.

+ +

Possible SCTP events:

-

#sctp_sndrcvinfo{}

+ #sctp_sndrcvinfo{}
-

#sctp_assoc_change{};

+ #sctp_assoc_change{}
-
  #sctp_paddr_change{
-        addr      = {ip_address(),port()},
-        state     = atom(),
-        error     = integer(),
-        assoc_id  = assoc_id()
-  }            
-

Indicates change of the status of the peer's IP address given by - addr within the association assoc_id. - Possible values of state (mostly self-explanatory) include:

- - -

addr_unreachable;

-
- -

addr_available;

-
- -

addr_removed;

-
- -

addr_added;

+
+#sctp_paddr_change{
+      addr      = {ip_address(),port()},
+      state     = atom(),
+      error     = integer(),
+      assoc_id  = assoc_id()
+}
+

Indicates change of the status of the IP address of the peer + specified by + addr within association assoc_id. Possible + values of state (mostly self-explanatory) include:

+ + addr_unreachable + + addr_available + + addr_removed + + addr_added + + addr_made_prim + + addr_confirmed + + +

In case of an error (for example, addr_unreachable), + field error provides more diagnostics. In such cases, + event #sctp_paddr_change{} is automatically + converted into an error term returned by + recv. + The error field value can be converted into a string using + error_string/1. +

+
+ +
+#sctp_send_failed{
+      flags     = true | false,
+      error     = integer(),
+      info      = #sctp_sndrcvinfo{},
+      assoc_id  = assoc_id()
+      data      = binary()
+}
+

The sender can receive this event if a send operation fails.

+ + flags +

A Boolean specifying if the data has been transmitted + over the wire.

+ error +

Provides extended diagnostics, use + error_string/1.

- -

addr_made_prim.

+ info +

The original + #sctp_sndrcvinfo{} + record used in the failed + send/*.

- -

addr_confirmed.

+ data +

The whole original data chunk attempted to be sent.

-
-

In case of an error (e.g. addr_unreachable), the - error field provides additional diagnostics. In such cases, - the #sctp_paddr_change{} Event is automatically - converted into an error term returned by - gen_sctp:recv. The error field value can be - converted into a string using error_string/1.

-
- -
  #sctp_send_failed{
-        flags     = true | false,
-        error     = integer(),
-        info      = #sctp_sndrcvinfo{},
-        assoc_id  = assoc_id()
-        data      = binary()
-  }            
-

The sender may receive this event if a send operation fails. - The flags is a Boolean specifying whether the data have - actually been transmitted over the wire; error provides - extended diagnostics, use error_string/1; - info is the original - #sctp_sndrcvinfo{} record used in the failed - send/*, and data - is the whole original data chunk attempted to be sent.

+

In the current implementation of the Erlang/SCTP binding, - this Event is internally converted into an error term - returned by recv/*.

+ this event is internally converted into an error term + returned by + recv/*.

-
  #sctp_adaptation_event{
-        adaptation_ind = integer(),
-        assoc_id       = assoc_id()
-  }            
-

Delivered when a peer sends an Adaptation Layer Indication - parameter (configured through the option - sctp_adaptation_layer). - Note that with the current implementation of +

+#sctp_adaptation_event{
+      adaptation_ind = integer(),
+      assoc_id       = assoc_id()
+}
+

Delivered when a peer sends an adaptation layer indication + parameter (configured through option + sctp_adaptation_layer). + Notice that with the current implementation of the Erlang/SCTP binding, this event is disabled by default.

-
  #sctp_pdapi_event{
-        indication = sctp_partial_delivery_aborted,
-        assoc_id   = assoc_id()
-  }            
+
+#sctp_pdapi_event{
+      indication = sctp_partial_delivery_aborted,
+      assoc_id   = assoc_id()
+}

A partial delivery failure. In the current implementation of - the Erlang/SCTP binding, this Event is internally converted - into an error term returned by recv/*.

+ the Erlang/SCTP binding, this event is internally converted + into an error term returned by + recv/*.

+ - Send a message using an #sctp_sndrcvinfo{}record + Send a message using an #sctp_sndrcvinfo{}record. -

Sends the Data message with all sending parameters from a - #sctp_sndrcvinfo{} record. - This way, the user can specify the PPID (passed to the remote end) - and Context (passed to the local SCTP layer) which can be used - for example for error identification. +

Sends the Data message with all sending + parameters from a + #sctp_sndrcvinfo{} + record. This way, the user can specify the PPID (passed to the remote + end) and context (passed to the local SCTP layer), which can be used, + for example, for error identification. However, such a fine level of user control is rarely required. - The send/4 function is sufficient for most applications.

+ The function send/4 is sufficient for most applications.

+ - Send a message over an existing association and given stream + Send a message over an existing association and specified + stream. -

Sends Data message over an existing association and given - stream.

-
-
- - - Translate an SCTP error number into a string - -

Translates an SCTP error number from for example - #sctp_remote_error{} or #sctp_send_failed{} into - an explanatory string, or one of the atoms ok for no - error and undefined for an unrecognized error.

+

Sends a Data message over an existing association + and specified stream.

- SCTP SOCKET OPTIONS + SCTP Socket Options

The set of admissible SCTP socket options is by construction - orthogonal to the sets of TCP, UDP and generic INET options: - only those options which are explicitly listed below are allowed + orthogonal to the sets of TCP, UDP, and generic inet options. + Only options listed here are allowed for SCTP sockets. Options can be set on the socket using - gen_sctp:open/1,2 - or inet:setopts/2, - retrieved using inet:getopts/2, - and when calling gen_sctp:connect/4,5 - options can be changed.

+ open/1,2 or + inet:setopts/2, + retrieved using + inet:getopts/2. + Options can be changed when calling + connect/4,5.

{mode, list|binary} or just list or binary -

Determines the type of data returned from gen_sctp:recv/1,2.

+

Determines the type of data returned from + recv/1,2.

{active, true|false|once|N} @@ -517,176 +542,177 @@

If false (passive mode, the default), - the caller needs to do an explicit gen_sctp:recv call - in order to retrieve the available data from the socket.

+ the caller must do an explicit + recv call + to retrieve the available data from the socket.

If true (full active mode), the pending data or events are sent to the owning process.

-

NB: This can cause the message queue to overflow, +

Notice that this can cause the message queue to overflow, as there is no way to throttle the sender in this case - (no flow control!).

+ (no flow control).

If once, only one message is automatically placed in the message queue, and after that the mode is automatically - reset to passive. This provides flow control as well as + reset to passive. This provides flow control and the possibility for the receiver to listen for its incoming SCTP data interleaved with other inter-process messages.

If active is specified as an integer N in the - range -32768 to 32767 (inclusive), then that number is added to - the socket's count of the number of data messages to be + range -32768 to 32767 (inclusive), that number is added to + the socket's counting of data messages to be delivered to the controlling process. If the result of the - addition would be negative, the count is set to 0. Once the - count reaches 0, either through the delivery of messages or by - being explicitly set with inet:setopts/2, the socket's - mode is automatically reset to passive ({active, - false}) mode. When a socket in this active mode transitions to + addition is negative, the count is set to 0. Once the + count reaches 0, either through the delivery of messages + or by being explicitly set with + inet:setopts/2, + the socket mode is automatically reset to passive ({active, + false}). When a socket in this active mode transitions to passive mode, the message {sctp_passive, Socket} is sent to the controlling process to notify it that if it wants to receive more data messages from the socket, it must call - inet:setopts/2 to set - the socket back into an active mode.

+ inet:setopts/2 + to set the socket back into an active mode.

- {tos, integer()} + {tos, integer()} -

Sets the Type-Of-Service field on the IP datagrams being sent, - to the given value, which effectively determines a prioritization +

Sets the Type-Of-Service field on the IP datagrams that are sent, + to the specified value. This effectively determines a prioritization policy for the outbound packets. The acceptable values - are system-dependent. TODO: we do not provide - symbolic names for these values yet.

+ are system-dependent.

{priority, integer()}

A protocol-independent equivalent of tos above. Setting - priority implies setting tos as well.

+ priority implies setting tos as well.

{dontroute, true|false} -

By default false. If true, the kernel does not - send packets via any gateway, only sends them to directly +

Defaults to false. If true, the kernel does not + send packets through any gateway, only sends them to directly connected hosts.

{reuseaddr, true|false} -

By default false. If true, the local binding address - {IP,Port} of the socket can be re-used immediately: - no waiting in the CLOSE_WAIT state is performed (may be +

Defaults to false. If true, the local binding address + {IP,Port} of the socket can be reused immediately. + No waiting in state CLOSE_WAIT is performed (can be required for high-throughput servers).

- {sndbuf, integer()} + {sndbuf, integer()} -

The size, in bytes, of the *kernel* send buffer for this socket. +

The size, in bytes, of the OS kernel send buffer for this socket. Sending errors would occur for datagrams larger than val(sndbuf). Setting this option also adjusts the size of the driver buffer (see buffer above).

{recbuf, integer()} -

The size, in bytes, of the *kernel* recv buffer for this socket. +

The size, in bytes, of the OS kernel receive buffer for this socket. Sending errors would occur for datagrams larger than - val(sndbuf). Setting this option also adjusts + val(recbuf). Setting this option also adjusts the size of the driver buffer (see buffer above).

- - {sctp_module, module()} -

- Override which callback module is used. Defaults to - inet_sctp for IPv4 and inet6_sctp for IPv6. -

-
- - + {sctp_module, module()} + +

Overrides which callback module is used. Defaults to + inet_sctp for IPv4 and inet6_sctp for IPv6.

+
{sctp_rtoinfo, #sctp_rtoinfo{}} -
  #sctp_rtoinfo{
-        assoc_id = assoc_id(),
-        initial  = integer(),
-        max      = integer(),
-        min      = integer()
-  }        
-

Determines re-transmission time-out parameters, in milliseconds, - for the association(s) given by assoc_id. - If assoc_id = 0 (default) indicates the whole endpoint. See - RFC2960 and - Sockets API Extensions for SCTP for the exact semantics of the fields values.

+
+#sctp_rtoinfo{
+      assoc_id = assoc_id(),
+      initial  = integer(),
+      max      = integer(),
+      min      = integer()
+}
+

Determines retransmission time-out parameters, in milliseconds, + for the association(s) specified by assoc_id.

+

assoc_id = 0 (default) indicates the whole endpoint. See + RFC + 2960 and + Sockets + API Extensions for SCTP + for the exact semantics of the field values.

{sctp_associnfo, #sctp_assocparams{}} -
  #sctp_assocparams{
-        assoc_id                 = assoc_id(),
-        asocmaxrxt               = integer(),
-        number_peer_destinations = integer(),
-        peer_rwnd                = integer(),
-        local_rwnd               = integer(),
-        cookie_life              = integer()
-  }        
-

Determines association parameters for the association(s) given by - assoc_id. assoc_id = 0 (default) indicates - the whole endpoint. See - Sockets API Extensions for SCTP for the discussion of their semantics. Rarely used.

+
+#sctp_assocparams{
+      assoc_id                 = assoc_id(),
+      asocmaxrxt               = integer(),
+      number_peer_destinations = integer(),
+      peer_rwnd                = integer(),
+      local_rwnd               = integer(),
+      cookie_life              = integer()
+}
+

Determines association parameters for the association(s) specified by + assoc_id.

+

assoc_id = 0 (default) indicates the whole endpoint. See + Sockets API Extensions for SCTP + for the discussion of their semantics. Rarely used.

{sctp_initmsg, #sctp_initmsg{}} -
  #sctp_initmsg{
-       num_ostreams   = integer(),
-       max_instreams  = integer(),
-       max_attempts   = integer(),
-       max_init_timeo = integer()
-  }        
-

Determines the default parameters which this socket attempts +

+#sctp_initmsg{
+     num_ostreams   = integer(),
+     max_instreams  = integer(),
+     max_attempts   = integer(),
+     max_init_timeo = integer()
+}
+

Determines the default parameters that this socket tries to negotiate with its peer while establishing an association with it. - Should be set after open/* but before the first - connect/*. #sctp_initmsg{} can also be used - as ancillary data with the first call of send/* to + Is to be set after + open/* + but before the first + connect/*. + #sctp_initmsg{} can also be used + as ancillary data with the first call of + send/* to a new peer (when a new association is created).

- - -

num_ostreams: number of outbound streams;

-
- -

max_instreams: max number of in-bound streams;

-
- -

max_attempts: max re-transmissions while - establishing an association;

-
- -

max_init_timeo: time-out in milliseconds - for establishing an association.

-
-
+ + num_ostreams + Number of outbound streams + max_instreams + Maximum number of inbound streams + max_attempts + Maximum retransmissions while establishing an association + max_init_timeo + Time-out, in milliseconds, for establishing an association +
{sctp_autoclose, integer() >= 0} -

Determines the time (in seconds) after which an idle association is +

Determines the time, in seconds, after which an idle association is automatically closed. 0 means that the association is never automatically closed.

{sctp_nodelay, true|false}

Turns on|off the Nagle algorithm for merging small packets - into larger ones (which improves throughput at the expense - of latency).

+ into larger ones. This improves throughput at the expense + of latency.

{sctp_disable_fragments, true|false}

If true, induces an error on an attempt to send - a message which is larger than the current PMTU size - (which would require fragmentation/re-assembling). - Note that message fragmentation does not affect + a message larger than the current PMTU size + (which would require fragmentation/reassembling). + Notice that message fragmentation does not affect the logical atomicity of its delivery; this option is provided for performance reasons only.

{sctp_i_want_mapped_v4_addr, true|false}

Turns on|off automatic mapping of IPv4 addresses into IPv6 ones - (if the socket address family is AF_INET6).

+ (if the socket address family is AF_INET6).

{sctp_maxseg, integer()} @@ -695,176 +721,171 @@ {sctp_primary_addr, #sctp_prim{}} -
  #sctp_prim{
-        assoc_id = assoc_id(),
-        addr     = {IP, Port}
-  }
-  IP = ip_address()
-  Port = port_number()        
-

For the association given by assoc_id, - {IP,Port} must be one of the peer's addresses. - This option determines that the given address is - treated by the local SCTP stack as the peer's primary address.

+
+#sctp_prim{
+      assoc_id = assoc_id(),
+      addr     = {IP, Port}
+}
+ IP = ip_address()
+ Port = port_number()
+

For the association specified by assoc_id, + {IP,Port} must be one of the peer addresses. + This option determines that the specified address is treated by + the local SCTP stack as the primary address of the peer.

{sctp_set_peer_primary_addr, #sctp_setpeerprim{}} -
  #sctp_setpeerprim{
-        assoc_id = assoc_id(),
-        addr     = {IP, Port}
-  }
-  IP = ip_address()
-  Port = port_number()        
-

When set, informs the peer that it should use {IP, Port} +

+#sctp_setpeerprim{
+      assoc_id = assoc_id(),
+      addr     = {IP, Port}
+}
+ IP = ip_address()
+ Port = port_number()
+

When set, informs the peer to use {IP, Port} as the primary address of the local endpoint for the association - given by assoc_id.

+ specified by assoc_id.

{sctp_adaptation_layer, #sctp_setadaptation{}} -
  #sctp_setadaptation{
-        adaptation_ind = integer()
-  }        
-

When set, requests that the local endpoint uses the value given by - adaptation_ind as the Adaptation Indication parameter for - establishing new associations. See - RFC2960 and - Sockets API Extenstions for SCTP for more details.

+
+#sctp_setadaptation{
+      adaptation_ind = integer()
+}
+

When set, requests that the local endpoint uses the value specified + by adaptation_ind as the Adaptation Indication parameter for + establishing new associations. For details, see + RFC 2960 + and + Sockets + API Extenstions for SCTP.

{sctp_peer_addr_params, #sctp_paddrparams{}} -
  #sctp_paddrparams{
-        assoc_id   = assoc_id(),
-        address    = {IP, Port},
-        hbinterval = integer(),
-        pathmaxrxt = integer(),
-        pathmtu    = integer(),
-        sackdelay  = integer(),
-        flags      = list()
-  }
-  IP = ip_address()
-  Port = port_number()        
-

This option determines various per-address parameters for - the association given by assoc_id and the peer address - address (the SCTP protocol supports multi-homing, - so more than 1 address can correspond to a given association).

- - -

hbinterval: heartbeat interval, in milliseconds;

-
- -

pathmaxrxt: max number of retransmissions - before this address is considered unreachable (and an - alternative address is selected);

-
- -

pathmtu: fixed Path MTU, if automatic discovery is - disabled (see flags below);

-
- -

sackdelay: delay in milliseconds for SAC messages - (if the delay is enabled, see flags below);

-
- -

flags: the following flags are available:

- - -

hb_enable: enable heartbeat;

-
- -

hb_disable: disable heartbeat;

-
- -

hb_demand: initiate heartbeat immediately;

-
- -

pmtud_enable: enable automatic Path MTU discovery;

-
- -

pmtud_disable: disable automatic Path MTU discovery;

-
- -

sackdelay_enable: enable SAC delay;

-
- -

sackdelay_disable: disable SAC delay.

-
-
+
+#sctp_paddrparams{
+      assoc_id   = assoc_id(),
+      address    = {IP, Port},
+      hbinterval = integer(),
+      pathmaxrxt = integer(),
+      pathmtu    = integer(),
+      sackdelay  = integer(),
+      flags      = list()
+}
+IP = ip_address()
+Port = port_number()
+

Determines various per-address parameters for + the association specified by assoc_id and the peer address + address (the SCTP protocol supports multi-homing, so + more than one address can correspond to a specified association).

+ + hbinterval +

Heartbeat interval, in milliseconds

+ pathmaxrxt +

Maximum number of retransmissions before this address is + considered unreachable (and an alternative address is selected)

-
+ pathmtu +

Fixed Path MTU, if automatic discovery is disabled (see + flags below)

+ sackdelay +

Delay, in milliseconds, for SAC messages (if the delay is + enabled, see flags below)

+ flags +

The following flags are available:

+ + hb_enable + Enables heartbeat + hb_disable + Disables heartbeat + hb_demand + Initiates heartbeat immediately + pmtud_enable + Enables automatic Path MTU discovery + pmtud_disable + Disables automatic Path MTU discovery + sackdelay_enable + Enables SAC delay + sackdelay_disable + Disables SAC delay +
+
{sctp_default_send_param, #sctp_sndrcvinfo{}} -
  #sctp_sndrcvinfo{
-        stream     = integer(),
-        ssn        = integer(),
-        flags      = list(),
-        ppid       = integer(),
-        context    = integer(),
-        timetolive = integer(),
-        tsn        = integer(),
-        cumtsn     = integer(),
-        assoc_id   = assoc_id()
-  }        
+
+#sctp_sndrcvinfo{
+      stream     = integer(),
+      ssn        = integer(),
+      flags      = list(),
+      ppid       = integer(),
+      context    = integer(),
+      timetolive = integer(),
+      tsn        = integer(),
+      cumtsn     = integer(),
+      assoc_id   = assoc_id()
+}

#sctp_sndrcvinfo{} is used both in this socket option, and as ancillary data while sending or receiving SCTP messages. When - set as an option, it provides a default values for subsequent - gen_sctp:sendcalls on the association given by - assoc_id. assoc_id = 0 (default) indicates - the whole endpoint. The following fields typically need - to be specified by the sender:

- - -

sinfo_stream: stream number (0-base) within the association - to send the messages through;

-
- -

sinfo_flags: the following flags are recognised:

- - -

unordered: the message is to be sent unordered;

-
- -

addr_over: the address specified in - gen_sctp:send overwrites the primary peer address;

-
- -

abort: abort the current association without - flushing any unsent data;

-
- -

eof: gracefully shut down the current - association, with flushing of unsent data.

-
-
-

Other fields are rarely used. See - RFC2960 and - Sockets API Extensions for SCTP for full information.

-
-
+ set as an option, it provides default values for subsequent + send + calls on the association specified by + assoc_id.

+

assoc_id = 0 (default) indicates + the whole endpoint.

+

The following fields typically must be specified by the sender:

+ + sinfo_stream +

Stream number (0-base) within the association + to send the messages through;

+ sinfo_flags +

The following flags are recognised:

+ + unordered + The message is to be sent unordered + addr_over + The address specified in + send + overwrites the primary peer address + abort + Aborts the current association without flushing any unsent + data + eof + Gracefully shuts down the current association, with + flushing of unsent data + +

Other fields are rarely used. For complete information, see + RFC 2960 + and + Sockets + API Extensions for SCTP.

+
{sctp_events, #sctp_event_subscribe{}} -
  #sctp_event_subscribe{
-          data_io_event          = true | false,
-          association_event      = true | false,
-          address_event          = true | false,
-          send_failure_event     = true | false,
-          peer_error_event       = true | false,
-          shutdown_event         = true | false,
-          partial_delivery_event = true | false,
-          adaptation_layer_event = true | false
-    }        
+
+#sctp_event_subscribe{
+        data_io_event          = true | false,
+        association_event      = true | false,
+        address_event          = true | false,
+        send_failure_event     = true | false,
+        peer_error_event       = true | false,
+        shutdown_event         = true | false,
+        partial_delivery_event = true | false,
+        adaptation_layer_event = true | false
+}

This option determines which SCTP Events are to be - received (via recv/*) - along with the data. The only - exception is data_io_event which enables or disables - receiving of - #sctp_sndrcvinfo{} + received (through + recv/*) + along with the data. The only exception is data_io_event, + which enables or disables receiving of + #sctp_sndrcvinfo{} ancillary data, not events. By default, all flags except adaptation_layer_event are enabled, although sctp_data_io_event and @@ -873,201 +894,185 @@ {sctp_delayed_ack_time, #sctp_assoc_value{}} -

  #sctp_assoc_value{
-        assoc_id    = assoc_id(),
-        assoc_value = integer()
-  }        
+
+#sctp_assoc_value{
+      assoc_id    = assoc_id(),
+      assoc_value = integer()
+}

Rarely used. Determines the ACK time - (given by assoc_value in milliseconds) for - the given association or the whole endpoint + (specified by assoc_value, in milliseconds) for + the specified association or the whole endpoint if assoc_value = 0 (default).

{sctp_status, #sctp_status{}} -
  #sctp_status{
-        assoc_id            = assoc_id(),
-        state               = atom(),
-        rwnd                = integer(),
-        unackdata           = integer(),
-        penddata            = integer(),
-        instrms             = integer(),
-        outstrms            = integer(),
-        fragmentation_point = integer(),
-        primary             = #sctp_paddrinfo{}
-  }        
+
+#sctp_status{
+      assoc_id            = assoc_id(),
+      state               = atom(),
+      rwnd                = integer(),
+      unackdata           = integer(),
+      penddata            = integer(),
+      instrms             = integer(),
+      outstrms            = integer(),
+      fragmentation_point = integer(),
+      primary             = #sctp_paddrinfo{}
+}

This option is read-only. It determines the status of - the SCTP association given by assoc_id. Possible values of - state follows. The state designations are mostly - self-explanatory. state_empty is the default which means - that no other state is active:

- - -

sctp_state_empty

-
- -

sctp_state_closed

-
- -

sctp_state_cookie_wait

-
- -

sctp_state_cookie_echoed

-
- -

sctp_state_established

-
- -

sctp_state_shutdown_pending

-
- -

sctp_state_shutdown_sent

-
- -

sctp_state_shutdown_received

-
- -

sctp_state_shutdown_ack_sent

-
-
-

The semantics of other fields is the following:

- - -

sstat_rwnd: the association peer's current receiver - window size;

-
- -

sstat_unackdata: number of unacked data chunks;

-
- -

sstat_penddata: number of data chunks pending receipt;

-
- -

sstat_instrms: number of inbound streams;

-
- -

sstat_outstrms: number of outbound streams;

-
- -

sstat_fragmentation_point: message size at which SCTP - fragmentation will occur;

-
- -

sstat_primary: information on the current primary peer - address (see below for the format of #sctp_paddrinfo{}).

-
-
+ the SCTP association specified by assoc_id. + The following are the + possible values of state (the state designations are mostly + self-explanatory):

+ + sctp_state_empty + Default. Means that no other state is active. + sctp_state_closed + + sctp_state_cookie_wait + + sctp_state_cookie_echoed + + sctp_state_established + + sctp_state_shutdown_pending + + sctp_state_shutdown_sent + + sctp_state_shutdown_received + + sctp_state_shutdown_ack_sent + + +

Semantics of the other fields:

+ + sstat_rwnd + Current receiver window size of the association + sstat_unackdata + Number of unacked data chunks + sstat_penddata + Number of data chunks pending receipt + sstat_instrms + Number of inbound streams + sstat_outstrms + Number of outbound streams + sstat_fragmentation_point + Message size at which SCTP fragmentation occurs + sstat_primary + Information on the current primary peer address (see below for + the format of #sctp_paddrinfo{}) +
{sctp_get_peer_addr_info, #sctp_paddrinfo{}} -
  #sctp_paddrinfo{
-        assoc_id  = assoc_id(),
-        address   = {IP, Port},
-        state     = inactive | active | unconfirmed,
-        cwnd      = integer(),
-        srtt      = integer(),
-        rto       = integer(),
-        mtu       = integer()
-  }
-  IP = ip_address()
-  Port = port_number()        
+
+#sctp_paddrinfo{
+      assoc_id  = assoc_id(),
+      address   = {IP, Port},
+      state     = inactive | active | unconfirmed,
+      cwnd      = integer(),
+      srtt      = integer(),
+      rto       = integer(),
+      mtu       = integer()
+}
+IP = ip_address()
+Port = port_number()

This option is read-only. It determines the parameters specific to - the peer's address given by address within the association - given by assoc_id. The address field must be set by the + the peer address specified by address within the association + specified by assoc_id. Field address fmust be set by the caller; all other fields are filled in on return. If assoc_id = 0 (default), the address is automatically translated into the corresponding - association ID. This option is rarely used; see - RFC2960 and - Sockets API Extensions for SCTP for the semantics of all fields.

+ association ID. This option is rarely used. + For the semantics of all fields, see + RFC 2960 + and + Sockets + API Extensions for SCTP.

- SCTP EXAMPLES - - -

Example of an Erlang SCTP Server which receives SCTP messages and - prints them on the standard output:

-
  -module(sctp_server).
-  
-  -export([server/0,server/1,server/2]).
-  -include_lib("kernel/include/inet.hrl").
-  -include_lib("kernel/include/inet_sctp.hrl").
-  
-  server() ->
-      server(any, 2006).
-  
-  server([Host,Port]) when is_list(Host), is_list(Port) ->
-      {ok, #hostent{h_addr_list = [IP|_]}} = inet:gethostbyname(Host),
-      io:format("~w -> ~w~n", [Host, IP]),
-      server([IP, list_to_integer(Port)]).
-  
-  server(IP, Port) when is_tuple(IP) orelse IP == any orelse IP == loopback,
-                        is_integer(Port) ->
-      {ok,S} = gen_sctp:open(Port, [{recbuf,65536}, {ip,IP}]),
-      io:format("Listening on ~w:~w. ~w~n", [IP,Port,S]),
-      ok     = gen_sctp:listen(S, true),
-      server_loop(S).
-  
-  server_loop(S) ->
-      case gen_sctp:recv(S) of
-      {error, Error} ->
-          io:format("SCTP RECV ERROR: ~p~n", [Error]);
-      Data ->
-          io:format("Received: ~p~n", [Data])
-      end,
-      server_loop(S).        
-
- -

Example of an Erlang SCTP Client which interacts with the above Server. - Note that in this example, the Client creates an association with - the Server with 5 outbound streams. For this reason, sending of - "Test 0" over Stream 0 succeeds, but sending of "Test 5" - over Stream 5 fails. The client then aborts the association, - which results in the corresponding Event being received on - the Server side.

-
  -module(sctp_client).
-  
-  -export([client/0, client/1, client/2]).
-  -include_lib("kernel/include/inet.hrl").
-  -include_lib("kernel/include/inet_sctp.hrl").
+    SCTP Examples
+      

Example of an Erlang SCTP server that receives SCTP messages and + prints them on the standard output:

+
+-module(sctp_server).
+
+-export([server/0,server/1,server/2]).
+-include_lib("kernel/include/inet.hrl").
+-include_lib("kernel/include/inet_sctp.hrl").
+
+server() ->
+    server(any, 2006).
+
+server([Host,Port]) when is_list(Host), is_list(Port) ->
+    {ok, #hostent{h_addr_list = [IP|_]}} = inet:gethostbyname(Host),
+    io:format("~w -> ~w~n", [Host, IP]),
+    server([IP, list_to_integer(Port)]).
+
+server(IP, Port) when is_tuple(IP) orelse IP == any orelse IP == loopback,
+                      is_integer(Port) ->
+    {ok,S} = gen_sctp:open(Port, [{recbuf,65536}, {ip,IP}]),
+    io:format("Listening on ~w:~w. ~w~n", [IP,Port,S]),
+    ok     = gen_sctp:listen(S, true),
+    server_loop(S).
+
+server_loop(S) ->
+    case gen_sctp:recv(S) of
+    {error, Error} ->
+        io:format("SCTP RECV ERROR: ~p~n", [Error]);
+    Data ->
+        io:format("Received: ~p~n", [Data])
+    end,
+    server_loop(S).
+

Example of an Erlang SCTP client interacting with the above server. + Notice that in this example the client creates an association with + the server with 5 outbound streams. Therefore, sending of + "Test 0" over stream 0 succeeds, but sending of "Test 5" + over stream 5 fails. The client then aborts the association, + which results in that the corresponding event is received on + the server side.

+
+-module(sctp_client).
+
+-export([client/0, client/1, client/2]).
+-include_lib("kernel/include/inet.hrl").
+-include_lib("kernel/include/inet_sctp.hrl").
+
+client() ->
+    client([localhost]).
+
+client([Host]) ->
+    client(Host, 2006);
  
-  client() ->
-      client([localhost]).
-  
-  client([Host]) ->
-      client(Host, 2006);
-  
-  client([Host, Port]) when is_list(Host), is_list(Port) ->
-      client(Host,list_to_integer(Port)),
-      init:stop().
-  
-  client(Host, Port) when is_integer(Port) ->
-      {ok,S}     = gen_sctp:open(),
-      {ok,Assoc} = gen_sctp:connect
-          (S, Host, Port, [{sctp_initmsg,#sctp_initmsg{num_ostreams=5}}]),
-      io:format("Connection Successful, Assoc=~p~n", [Assoc]),
-      
-      io:write(gen_sctp:send(S, Assoc, 0, <<"Test 0">>)),
-      io:nl(),
-      timer:sleep(10000),
-      io:write(gen_sctp:send(S, Assoc, 5, <<"Test 5">>)),
-      io:nl(),
-      timer:sleep(10000),
-      io:write(gen_sctp:abort(S, Assoc)),
-      io:nl(),
-      
-      timer:sleep(1000),
-      gen_sctp:close(S).        
- - -

A very simple Erlang SCTP Client which uses the - connect_init API.

-
-module(ex3).
+client([Host, Port]) when is_list(Host), is_list(Port) ->
+    client(Host,list_to_integer(Port)),
+    init:stop().
+
+client(Host, Port) when is_integer(Port) ->
+    {ok,S}     = gen_sctp:open(),
+    {ok,Assoc} = gen_sctp:connect
+        (S, Host, Port, [{sctp_initmsg,#sctp_initmsg{num_ostreams=5}}]),
+    io:format("Connection Successful, Assoc=~p~n", [Assoc]),
+
+    io:write(gen_sctp:send(S, Assoc, 0, <<"Test 0">>)),
+    io:nl(),
+    timer:sleep(10000),
+    io:write(gen_sctp:send(S, Assoc, 5, <<"Test 5">>)),
+    io:nl(),
+    timer:sleep(10000),
+    io:write(gen_sctp:abort(S, Assoc)),
+    io:nl(),
+
+    timer:sleep(1000),
+    gen_sctp:close(S).
+

A simple Erlang SCTP client that uses the connect_init API:

+
+-module(ex3).
 
 -export([client/4]).
 -include_lib("kernel/include/inet.hrl").
@@ -1099,7 +1104,7 @@ client_loop(S, Peer1, Port1, AssocId1, Peer2, Port2, AssocId2) ->
             io:format("Association 2 connect result: ~p. AssocId: ~p~n",
                       [SAC#sctp_assoc_change.state, SAC#sctp_assoc_change.assoc_id]),
             client_loop(S, Peer1, Port1, AssocId1, Peer2, Port2,
-                        SAC#sctp_assoc_change.assoc_id);
+                       SAC#sctp_assoc_change.assoc_id);
 
         {sctp, S, Peer1, Port1, Data} ->
             io:format("Association 1: received ~p~n", [Data]),
@@ -1118,20 +1123,19 @@ client_loop(S, Peer1, Port1, AssocId1, Peer2, Port2, AssocId2) ->
 
     after 5000 ->
             ok
-    end.
-
-
- + end.
- SEE ALSO -

inet(3), - gen_tcp(3), - gen_udp(3), - RFC2960 (Stream Control Transmission Protocol), - Sockets API Extensions for SCTP.

+ See Also +

gen_tcp(3), + gen_udp(3), + inet(3), + RFC 2960 + (Stream Control Transmission Protocol), + Sockets + API Extensions for SCTP

diff --git a/lib/kernel/doc/src/gen_tcp.xml b/lib/kernel/doc/src/gen_tcp.xml index 6a19e76c4f..3212d6b5dd 100644 --- a/lib/kernel/doc/src/gen_tcp.xml +++ b/lib/kernel/doc/src/gen_tcp.xml @@ -21,7 +21,6 @@ limitations under the License. - gen_tcp tony@erix.ericsson.se @@ -29,13 +28,13 @@ A gen_tcp - Interface to TCP/IP sockets + Interface to TCP/IP sockets. -

The gen_tcp module provides functions for communicating +

This module provides functions for communicating with sockets using the TCP/IP protocol.

-

The following code fragment provides a simple example of +

The following code fragment is a simple example of a client connecting to a server at port 5678, transferring a - binary and closing the connection:

+ binary, and closing the connection:

client() -> SomeHostInNet = "localhost", % to make it runnable on one machine @@ -43,8 +42,8 @@ client() -> [binary, {packet, 0}]), ok = gen_tcp:send(Sock, "Some Data"), ok = gen_tcp:close(Sock). -

At the other end a server is listening on port 5678, accepts - the connection and receives the binary:

+

At the other end, a server is listening on port 5678, accepts + the connection, and receives the binary:

server() -> {ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0}, @@ -61,7 +60,8 @@ do_recv(Sock, Bs) -> {error, closed} -> {ok, list_to_binary(Bs)} end. -

For more examples, see the examples section.

+

For more examples, see section + Examples.

@@ -79,295 +79,267 @@ do_recv(Sock, Bs) ->
socket() - -

- As returned by accept/1,2 and connect/3,4.

+

+ As returned by + accept/1,2 and + connect/3,4.

+ + + + Accept an incoming connection request on a listening socket. + Returned by + listen/2. + + +

Accepts an incoming connection request on a listening socket. + Socket must be a socket returned from + listen/2. + Timeout specifies a time-out value in + milliseconds. Defaults to infinity.

+

Returns:

+ +

{ok, Socket} if a connection is + established

+

{error, closed} if ListenSocket + is closed

+

{error, timeout} if no connection is established + within the specified time

+

{error, system_limit} if all available ports in the + Erlang emulator are in use

+

A POSIX error value if something else goes wrong, see + inet(3) for possible + error values

+
+

Packets can be sent to the returned socket Socket + using + send/2. + Packets sent from the peer are delivered as messages (unless + {active, false} is specified in the option list for the + listening socket, in which case packets are retrieved by calling + recv/2):

+ +{tcp, Socket, Data} + +

The accept call does + not have to be issued from the socket owner + process. Using version 5.5.3 and higher of the emulator, + multiple simultaneous accept calls can be issued from + different processes, which allows for a pool of acceptor + processes handling incoming connections.

+
+
+
+ + + + Close a TCP socket. + +

Closes a TCP socket.

+
+
+ - Connect to a TCP port + Connect to a TCP port.

Connects to a server on TCP port Port on the host - with IP address Address. The Address argument - can be either a hostname, or an IP address.

-

The available options are:

+ with IP address Address. Argument + Address can be a hostname or an IP address.

+

The following options are available:

- {ip, ip_address()} - -

If the host has several network interfaces, this option - specifies which one to use.

+ {ip, ip_address()} +

If the host has many network interfaces, this option + specifies which one to use.

+ {ifaddr, ip_address()} +

Same as {ip, ip_address()}. If the host has many + network interfaces, this option specifies which one to use.

- - {ifaddr, ip_address()} - -

Same as {ip, ip_address()}. If the host has several network interfaces, this option - specifies which one to use.

-
- {fd, integer() >= 0} - -

If a socket has somehow been connected without using - gen_tcp, use this option to pass the file - descriptor for it. If {ip, ip_address()} - and/or {port, port_number()} is combined with - this option the fd will be bound to the given interface - and port before connecting. If these options are not given - it is assumed that the fd is already bound appropriately. -

-
- +

If a socket has somehow been connected without using + gen_tcp, use this option to pass the file descriptor + for it. If {ip, ip_address()} and/or + {port, port_number()} is combined with this option, the + fd is bound to the specified interface and port before + connecting. If these options are not specified, it is assumed that + the fd is already bound appropriately.

inet - -

Set up the socket for IPv4.

-
- - inet6 - -

Set up the socket for IPv6.

-
- +

Sets up the socket for IPv4.

+ inet6 +

Sets up the socket for IPv6.

{port, Port} - -

Specify which local port number to use.

-
- - {tcp_module, module()} -

- Override which callback module is used. Defaults to - inet_tcp for IPv4 and inet6_tcp for IPv6. -

-
- +

Specifies which local port number to use.

+ {tcp_module, module()} +

Overrides which callback module is used. Defaults to + inet_tcp for IPv4 and inet6_tcp for IPv6.

Opt - -

See - inet:setopts/2.

+

See + inet:setopts/2.

Packets can be sent to the returned socket Socket - using send/2. Packets sent from the peer are delivered - as messages:

+ using send/2. + Packets sent from the peer are delivered as messages:

{tcp, Socket, Data} -

If the socket is in {active, N} mode (see - inet:setopts/2 for details) and its message counter - drops to 0, the following message is delivered to indicate that the +

If the socket is in {active, N} mode (see + inet:setopts/2 + for details) and its message counter drops to 0, the following + message is delivered to indicate that the socket has transitioned to passive ({active, false}) mode:

{tcp_passive, Socket}

If the socket is closed, the following message is delivered:

{tcp_closed, Socket} -

If an error occurs on the socket, the following message is - delivered:

+

If an error occurs on the socket, the following message is delivered + (unless {active, false} is specified in the option list for + the socket, in which case packets are retrieved by calling + recv/2):

{tcp_error, Socket, Reason} -

unless {active, false} is specified in the option list - for the socket, in which case packets are retrieved by - calling recv/2.

-

The optional Timeout parameter specifies a timeout in - milliseconds. The default value is infinity.

+

The optional Timeout parameter specifies a + time-out in milliseconds. Defaults to infinity.

-

The default values for options given to connect can - be affected by the Kernel configuration parameter - inet_default_connect_options. See - inet(3) for details.

+

The default values for options specified to connect can + be affected by the Kernel configuration parameter + inet_default_connect_options. For details, see + inet(3).

+ + + + Change controlling process of a socket. + +

Assigns a new controlling process Pid to + Socket. The controlling process is the process + that receives messages from the socket. If called by any other + process than the current controlling process, + {error, not_owner} is returned.

+
+
+ - Set up a socket to listen on a port + Set up a socket to listen on a port. -

Sets up a socket to listen on the port Port on +

Sets up a socket to listen on port Port on the local host.

-

If Port == 0, the underlying OS assigns an available - port number, use inet:port/1 to retrieve it.

-

The available options are:

+

If Port == 0, the underlying OS assigns an + available port number, use + inet:port/1 + to retrieve it.

+

The following options are available:

list - -

Received Packet is delivered as a list.

-
+

Received Packet is delivered as a list.

binary - -

Received Packet is delivered as a binary.

-
+

Received Packet is delivered as a binary.

{backlog, B} - -

B is an integer >= 0. The backlog value defaults - to 5. The backlog value defines the maximum length that - the queue of pending connections may grow to.

-
+

B is an integer >= 0. The backlog value + defines the maximum length that the queue of pending connections + can grow to. Defaults to 5.

{ip, ip_address()} - -

If the host has several network interfaces, this option - specifies which one to listen on.

-
+

If the host has many network interfaces, this option + specifies which one to listen on.

{port, Port} - -

Specify which local port number to use.

-
+

Specifies which local port number to use.

{fd, Fd} - -

If a socket has somehow been connected without using - gen_tcp, use this option to pass the file - descriptor for it.

+

If a socket has somehow been connected without using + gen_tcp, use this option to pass the file + descriptor for it.

+ {ifaddr, ip_address()} +

Same as {ip, ip_address()}. If the host has many + network interfaces, this option specifies which one to use.

- - {ifaddr, ip_address()} - -

Same as {ip, ip_address()}. If the host has several network interfaces, this option - specifies which one to use.

-
- inet6 - -

Set up the socket for IPv6.

-
+

Sets up the socket for IPv6.

inet - -

Set up the socket for IPv4.

-
- - {tcp_module, module()} -

- Override which callback module is used. Defaults to - inet_tcp for IPv4 and inet6_tcp for IPv6. -

-
- +

Sets up the socket for IPv4.

+ {tcp_module, module()} +

Overrides which callback module is used. Defaults to + inet_tcp for IPv4 and inet6_tcp for IPv6.

Opt - -

See - inet:setopts/2.

-
+

See + inet:setopts/2. +

-

The returned socket ListenSocket can only be used in - calls to accept/1,2.

+

The returned socket ListenSocket can only be + used in calls to + accept/1,2.

-

The default values for options given to listen can - be affected by the Kernel configuration parameter - inet_default_listen_options. See - inet(3) for details.

+

The default values for options specified to listen can + be affected by the Kernel configuration parameter + inet_default_listen_options. For details, see + inet(3).

- - - - Accept an incoming connection request on a listen socket - Returned by listen/2. - - -

Accepts an incoming connection request on a listen socket. - Socket must be a socket returned from listen/2. - Timeout specifies a timeout value in ms, defaults to - infinity.

-

Returns {ok, Socket} if a connection is established, - or {error, closed} if ListenSocket is closed, - or {error, timeout} if no connection is established - within the specified time, - or {error, system_limit} if all available ports in the - Erlang emulator are in use. May also return a POSIX error - value if something else goes wrong, see inet(3) for possible - error values.

-

Packets can be sent to the returned socket Socket - using send/2. Packets sent from the peer are delivered - as messages:

- -{tcp, Socket, Data} -

unless {active, false} was specified in the option - list for the listen socket, in which case packets are - retrieved by calling recv/2.

- -

It is worth noting that the accept call does - not have to be issued from the socket owner - process. Using version 5.5.3 and higher of the emulator, - multiple simultaneous accept calls can be issued from - different processes, which allows for a pool of acceptor - processes handling incoming connections.

-
-
-
- - - Send a packet - -

Sends a packet on a socket.

-

There is no send call with timeout option, you use the - send_timeout socket option if timeouts are - desired. See the examples section.

-
-
+ - Receive a packet from a passive socket + Receive a packet from a passive socket. See the description of - HttpPacket in - erlang:decode_packet/3. + HttpPacket in + erlang:decode_packet/3 + in ERTS. -

This function receives a packet from a socket in passive - mode. A closed socket is indicated by a return value +

Receives a packet from a socket in passive + mode. A closed socket is indicated by return value {error, closed}.

-

The Length argument is only meaningful when +

Argument Length is only meaningful when the socket is in raw mode and denotes the number of - bytes to read. If Length = 0, all available bytes are - returned. If Length > 0, exactly Length - bytes are returned, or an error; possibly discarding less - than Length bytes of data when the socket gets closed - from the other side.

-

The optional Timeout parameter specifies a timeout in - milliseconds. The default value is infinity.

-
-
- - - Change controlling process of a socket - -

Assigns a new controlling process Pid to - Socket. The controlling process is the process which - receives messages from the socket. If called by any other - process than the current controlling process, - {error, not_owner} is returned.

+ bytes to read. If Length is 0, all + available bytes are returned. + If Length > 0, exactly + Length bytes are returned, or an error; + possibly discarding less than Length bytes of + data when the socket is closed from the other side.

+

The optional Timeout parameter specifies a + time-out in milliseconds. Defaults to infinity.

+ - - Close a TCP socket + + Send a packet. -

Closes a TCP socket.

+

Sends a packet on a socket.

+

There is no send call with a time-out option, use socket + option send_timeout if time-outs are desired. See section + Examples.

+ - Asynchronously close a socket + Asynchronously close a socket. -

Close a socket in one or two directions.

-

How == write means closing the socket for writing, - reading from it is still possible.

-

If How == read, or there is no outgoing +

Closes a socket in one or two directions.

+

How == write means closing the socket for + writing, reading from it is still possible.

+

If How == read or there is no outgoing data buffered in the Socket port, - then the socket is shutdown immediately and any error encountered + the socket is shut down immediately and any error encountered is returned in Reason.

-

If there is data buffered in the socket port, then the attempt +

If there is data buffered in the socket port, the attempt to shutdown the socket is postponed until that data is written to the - kernel socket send buffer. Any errors encountered will result - in the socket being closed and {error, closed} being returned - on the next - recv/2 or - send/2.

-

To be able to handle that the peer has done a shutdown on - the write side, the {exit_on_close, false} option - is useful.

+ kernel socket send buffer. If any errors are encountered, the socket + is closed and {error, closed} is returned on the next + recv/2 or + send/2.

+

Option {exit_on_close, false} is useful if the peer has done + a shutdown on the write side.

@@ -375,14 +347,14 @@ do_recv(Sock, Bs) ->
Examples -

The following example illustrates usage of the {active,once} - option and multiple accepts by implementing a server as a - number of worker processes doing accept on one single listen - socket. The start/2 function takes the number of worker - processes as well as a port number to listen for incoming - connections on. If LPort is specified as 0, an - ephemeral portnumber is used, why the start function returns - the actual portnumber allocated:

+

The following example illustrates use of option + {active,once} and multiple accepts by implementing a server + as a number of worker processes doing accept on a single listening + socket. Function start/2 takes the number of worker + processes and the port number on which to listen for incoming + connections. If LPort is specified as 0, an + ephemeral port number is used, which is why the start function + returns the actual port number allocated:

start(Num,LPort) -> case gen_tcp:listen(LPort,[{active, false},{packet,2}]) of @@ -421,7 +393,7 @@ loop(S) -> io:format("Socket ~w closed [~w]~n",[S,self()]), ok end. -

A simple client could look like this:

+

Example of a simple client:

client(PortNo,Message) -> {ok,Sock} = gen_tcp:connect("localhost",PortNo,[{active,false}, @@ -430,30 +402,29 @@ client(PortNo,Message) -> A = gen_tcp:recv(Sock,0), gen_tcp:close(Sock), A. -

The fact that the send call does not accept a timeout - option, is because timeouts on send is handled through the socket +

The send call does not accept a time-out + option because time-outs on send is handled through socket option send_timeout. The behavior of a send operation with - no receiver is in a very high degree defined by the underlying TCP - stack, as well as the network infrastructure. If one wants to write - code that handles a hanging receiver that might eventually cause - the sender to hang on a send call, one writes code like - the following.

-

Consider a process that receives data from a client process that - is to be forwarded to a server on the network. The process has - connected to the server via TCP/IP and does not get any acknowledge - for each message it sends, but has to rely on the send timeout - option to detect that the other end is unresponsive. We could use - the send_timeout option when connecting:

+ no receiver is mainly defined by the underlying TCP + stack and the network infrastructure. To write + code that handles a hanging receiver that can eventually cause + the sender to hang on a send do like the following.

+

Consider a process that receives data from a client process + to be forwarded to a server on the network. The process is + connected to the server through TCP/IP and does not get any acknowledge + for each message it sends, but has to rely on the send time-out + option to detect that the other end is unresponsive. Option + send_timeout can be used when connecting:

- ... - {ok,Sock} = gen_tcp:connect(HostAddress, Port, - [{active,false}, - {send_timeout, 5000}, - {packet,2}]), - loop(Sock), % See below - ... -

In the loop where requests are handled, we can now detect send - timeouts:

+... +{ok,Sock} = gen_tcp:connect(HostAddress, Port, + [{active,false}, + {send_timeout, 5000}, + {packet,2}]), + loop(Sock), % See below +... +

In the loop where requests are handled, send time-outs can now be + detected:

loop(Sock) -> receive @@ -477,11 +448,11 @@ loop(Sock) -> Client ! {self(), data_sent}, loop(Sock) end - end. -

Usually it would suffice to detect timeouts on receive, as most + end. +

Usually it suffices to detect time-outs on receive, as most protocols include some sort of acknowledgment from the server, - but if the protocol is strictly one way, the send_timeout - option comes in handy!

+ but if the protocol is strictly one way, option send_timeout + comes in handy.

diff --git a/lib/kernel/doc/src/gen_udp.xml b/lib/kernel/doc/src/gen_udp.xml index 79cd87dcef..67789d8555 100644 --- a/lib/kernel/doc/src/gen_udp.xml +++ b/lib/kernel/doc/src/gen_udp.xml @@ -29,9 +29,9 @@ A gen_udp - Interface to UDP sockets + Interface to UDP sockets. -

The gen_udp module provides functions for communicating +

This module provides functions for communicating with sockets using the UDP protocol.

@@ -45,175 +45,140 @@ socket() -

As returned by open/1,2.

+ +

As returned by + open/1,2.

+ + + Close a UDP socket. + +

Closes a UDP socket.

+
+
+ + + + Change controlling process of a socket. + +

Assigns a new controlling process Pid to + Socket. The controlling process is the process + that receives messages from the socket. If called by any other + process than the current controlling process, + {error, not_owner} is returned.

+
+
+ - Associate a UDP port number with the process calling it + Associate a UDP port number with the process calling it. -

Associates a UDP port number (Port) with the calling - process.

-

The available options are:

+

Associates a UDP port number (Port) with the + calling process.

+

The following options are available:

list - -

Received Packet is delivered as a list.

-
+

Received Packet is delivered as a list.

binary - -

Received Packet is delivered as a binary.

-
+

Received Packet is delivered as a binary.

{ip, ip_address()} - -

If the host has several network interfaces, this option - specifies which one to use.

-
- - {ifaddr, ip_address()} - -

Same as {ip, ip_address()}. If the host has several network interfaces, this option - specifies which one to use.

-
- - +

If the host has many network interfaces, this option + specifies which one to use.

+ {ifaddr, ip_address()} +

Same as {ip, ip_address()}. If the host has many + network interfaces, this option specifies which one to + use.

{fd, integer() >= 0} - -

If a socket has somehow been opened without using - gen_udp, use this option to pass the file - descriptor for it. If Port is not set to 0 - and/or {ip, ip_address()} is combined with this option - the fd will be bound to the given interface and port after being - opened. If these options are not given it is assumed that the fd - is already bound appropriately. -

-
+

If a socket has somehow been opened without using + gen_udp, use this option to pass the file descriptor + for it. If Port is not set to 0 and/or + {ip, ip_address()} is combined with this option, the + fd is bound to the specified interface and port after it is + being opened. If these options are not specified, it is assumed that + the fd is already bound appropriately.

inet6 - -

Set up the socket for IPv6.

-
+

Sets up the socket for IPv6.

inet - -

Set up the socket for IPv4.

-
- - {udp_module, module()} -

- Override which callback module is used. Defaults to - inet_udp for IPv4 and inet6_udp for IPv6. -

-
- +

Sets up the socket for IPv4.

+ {udp_module, module()} +

Overrides which callback module is used. Defaults to + inet_udp for IPv4 and inet6_udp for IPv6.

{multicast_if, Address} - -

Set the local device for a multicast socket.

-
- +

Sets the local device for a multicast socket.

{multicast_loop, true | false} - -

- When true sent multicast packets will be looped back to the local - sockets. -

-
- +

When true, sent multicast packets are looped back to + the local sockets.

{multicast_ttl, Integer} - -

- The multicast_ttl option changes the time-to-live (TTL) for - outgoing multicast datagrams in order to control the scope of the - multicasts. -

-

- Datagrams with a TTL of 1 are not forwarded beyond the local - network. -
Default: 1 -

-
- - {add_membership, {MultiAddress, InterfaceAddress}} - -

Join a multicast group.

-
- - {drop_membership, {MultiAddress, InterfaceAddress}} - -

Leave multicast group.

-
- +

Option multicast_ttl changes the time-to-live (TTL) + for outgoing multicast datagrams to control the scope of the + multicasts.

+

Datagrams with a TTL of 1 are not forwarded beyond the local + network. Defaults to 1.

+ {add_membership, {MultiAddress, InterfaceAddress}} +

Joins a multicast group.

+ {drop_membership, {MultiAddress, InterfaceAddress}} +

Leaves a multicast group.

Opt - -

See - inet:setopts/2.

-
+

See + inet:setopts/2. +

The returned socket Socket is used to send - packets from this port with send/4. When UDP packets arrive - at the opened port, if the socket is in an active mode the packets + packets from this port with + send/4. + When UDP packets arrive + at the opened port, if the socket is in an active mode, the packets are delivered as messages to the controlling process:

{udp, Socket, IP, InPortNo, Packet}

If the socket is not in an active mode, data can be - retrieved via the recv/2,3 calls. - Note that arriving UDP packets that are longer than - the receive buffer option specifies, might be truncated + retrieved through the + recv/2,3 calls. + Notice that arriving UDP packets that are longer than + the receive buffer option specifies can be truncated without warning.

-

When a socket in {active, N} mode (see - inet:setopts/2 for details) transitions to passive - ({active, false}) mode, the controlling process is notified by a - message of the following form:

+

When a socket in {active, N} mode (see + inet:setopts/2 + for details), transitions to passive ({active, false}) mode, + the controlling process is notified by a message of the following + form:

{udp_passive, Socket}

IP and InPortNo define the address from which - Packet came. Packet is a list of bytes if - the option list was specified. Packet is a - binary if the option binary was specified.

+ Packet comes. Packet is a list of bytes if + option list is specified. Packet is a + binary if option binary is specified.

Default value for the receive buffer option is {recbuf, 8192}.

-

If Port == 0, the underlying OS assigns a free UDP - port, use inet:port/1 to retrieve it.

-
-
- - - Send a packet - -

Sends a packet to the specified address and port. - The Address argument can be either a hostname, or an - IP address.

+

If Port == 0, the underlying OS assigns a free + UDP port, use + inet:port/1 + to retrieve it.

+ - Receive a packet from a passive socket - -

This function receives a packet from a socket in passive - mode.

-

The optional Timeout parameter specifies a timeout in - milliseconds. The default value is infinity.

-
-
- - - Change controlling process of a socket + Receive a packet from a passive socket. -

Assigns a new controlling process Pid to - Socket. The controlling process is the process which - receives messages from the socket. If called by any other - process than the current controlling process, - {error, not_owner} is returned.

+

Receives a packet from a socket in passive mode. Optional parameter + Timeout specifies a time-out in milliseconds. + Defaults to infinity.

+ - - Close a UDP socket + + Send a packet. -

Closes a UDP socket.

+

Sends a packet to the specified address and port. Argument + Address can be a hostname or an IP address.

diff --git a/lib/kernel/doc/src/global.xml b/lib/kernel/doc/src/global.xml index bd75945115..4442741f54 100644 --- a/lib/kernel/doc/src/global.xml +++ b/lib/kernel/doc/src/global.xml @@ -4,7 +4,7 @@
- 19962013 + 19962016 Ericsson AB. All Rights Reserved. @@ -29,82 +29,67 @@
global - A Global Name Registration Facility + A global name registration facility. -

This documentation describes the Global module which consists - of the following functionalities:

- +

This module consists of the following services:

- registration of global names; - global locks; - maintenance of the fully connected network. + Registration of global names + Global locks + Maintenance of the fully connected network - -

These services are controlled via the process - global_name_server which exists on every node. The global - name server is started automatically when a node is started. +

These services are controlled through the process + global_name_server that exists on every node. The global + name server starts automatically when a node is started. With the term global is meant over a system consisting - of several Erlang nodes.

- + of many Erlang nodes.

The ability to globally register names is a central concept in the programming of distributed Erlang systems. In this module, the equivalent of the register/2 and whereis/1 - BIFs (for local name registration) are implemented, but for a + BIFs (for local name registration) are provided, but for a network of Erlang nodes. A registered name is an alias for a process identifier (pid). The global name server monitors - globally registered pids. If a process terminates, the name will - also be globally unregistered.

- + globally registered pids. If a process terminates, the name is + also globally unregistered.

The registered names are stored in replica global name tables on every node. There is no central storage point. Thus, the translation of a name to a pid is fast, as it is always done - locally. When any action in taken which results in a change to - the global name table, all tables on other nodes are automatically - updated.

- + locally. For any action resulting in a change to the global name table, + all tables on other nodes are automatically updated.

Global locks have lock identities and are set on a specific - resource. For instance, the specified resource could be a pid. + resource. For example, the specified resource can be a pid. When a global lock is set, access to the locked resource is - denied for all other resources other than the lock requester.

- -

Both the registration and lock functionalities are atomic. All - nodes involved in these actions will have the same view of + denied for all resources other than the lock requester.

+

Both the registration and lock services are atomic. + All nodes involved in these actions have the same view of the information.

-

The global name server also performs the critical task of - continuously monitoring changes in node configuration: if a node - which runs a globally registered process goes down, the name - will be globally unregistered. To this end the global name + continuously monitoring changes in node configuration. If a node + that runs a globally registered process goes down, the name + is globally unregistered. To this end, the global name server subscribes to nodeup and nodedown messages - sent from the net_kernel module. Relevant Kernel + sent from module net_kernel. Relevant Kernel application variables in this context are net_setuptime, net_ticktime, and dist_auto_connect. See also - kernel(6).

- -

The name server will also maintain a fully connected network. For + kernel(6).

+

The name server also maintains a fully connected network. For example, if node N1 connects to node N2 (which is already connected to N3), the global name servers on the - nodes N1 and N3 will make sure that also N1 - and N3 are connected. If this is not desired, the command - line flag -connect_all false can be used (see also - erl(1)). In - this case the name registration facility cannot be used, but the - lock mechanism will still work.

- + nodes N1 and N3 ensure that also N1 + and N3 are connected. If this is not desired, + command-line flag -connect_all false can be used (see also + erl(1)). + In this case, the name registration service cannot be used, but the + lock mechanism still works.

If the global name server fails to connect nodes (N1 and - N3 in the example above) a warning event is sent to the + N3 in the example), a warning event is sent to the error logger. The presence of such an event does not exclude the - possibility that the nodes will later connect--one can for - example try the command rpc:call(N1, net_adm, ping, [N2]) in - the Erlang shell--but it indicates some kind of problem with - the network.

- + nodes to connect later (you can, for + example, try command rpc:call(N1, net_adm, ping, [N2]) in + the Erlang shell), but it indicates a network problem.

-

If the fully connected network is not set up properly, the - first thing to try is to increase the value of - net_setuptime.

+

If the fully connected network is not set up properly, try + first to increase the value of net_setuptime.

-
@@ -117,7 +102,7 @@ - Delete a lock + Delete a lock.

Deletes the lock Id synchronously.

@@ -125,11 +110,13 @@ - Name resolving function that notifies both pids + Name resolving function that notifies both pids. -

This function can be used as a name resolving function for - register_name/3 and re_register_name/3. It - unregisters both pids, and sends the message +

Can be used as a name resolving function for + register_name/3 + and + re_register_name/3.

+

The function unregisters both pids and sends the message {global_name_conflict, Name, OtherPid} to both processes.

@@ -137,85 +124,97 @@ - Name resolving function that kills one pid + Name resolving function that kills one pid. -

This function can be used as a name resolving function for - register_name/3 and re_register_name/3. It - randomly chooses one of the pids for registration and kills - the other one.

+

Can be used as a name resolving function for + register_name/3 + and + re_register_name/3.

+

The function randomly selects one of the pids for registration and + kills the other one.

- Name resolving function that notifies one pid + Name resolving function that notifies one pid. -

This function can be used as a name resolving function for - register_name/3 and re_register_name/3. It - randomly chooses one of the pids for registration, and sends - the message {global_name_conflict, Name} to the other - pid.

+

Can be used as a name resolving function for + register_name/3 + and + re_register_name/3.

+

The function randomly selects one of the pids for registration, and + sends the message {global_name_conflict, Name} to + the other pid.

+
+
+ + + + + Atomically re-register a name. + + {Module, Function} + is also allowed. + + +

Atomically changes the registered name Name on + all nodes to refer to Pid.

+

Function Resolve has the same behavior as in + register_name/2,3. +

- Globally register a name for a pid + Globally register a name for a pid. - {Module, Function} - is currently also allowed for backward compatibility, but its use is - deprecated + {Module, Function} is also + allowed for backward compatibility, but its use is deprecated. -

Globally associates the name Name with a pid, that is, - Globally notifies all nodes of a new global name in a network +

Globally associates name Name with a pid, that + is, globally notifies all nodes of a new global name in a network of Erlang nodes.

-

When new nodes are added to the network, they are informed of the globally registered names that already exist. The network is also informed of any global names in newly connected nodes. If any name clashes are discovered, - the Resolve function is called. Its purpose is to + function Resolve is called. Its purpose is to decide which pid is correct. If the function crashes, or returns anything other than one of the pids, the name is unregistered. This function is called once for each name clash.

-

If you plan to change code without restarting your system, you must use an external fun (fun Module:Function/Arity) - as the Resolve function; if you use a - local fun you can never replace the code for the module that - the fun belongs to. -

+ as function Resolve. If you use a + local fun, you can never replace the code for the module that + the fun belongs to.

- -

There are three pre-defined resolve functions: +

Three predefined resolve functions exist: random_exit_name/3, random_notify_name/3, and - notify_all_name/3. If no Resolve function is - defined, random_exit_name is used. This means that one - of the two registered processes will be selected as correct + notify_all_name/3. If no Resolve function + is defined, random_exit_name is used. This means that one + of the two registered processes is selected as correct while the other is killed.

- -

This function is completely synchronous. This means that +

This function is completely synchronous, that is, when this function returns, the name is either registered on all nodes or none.

-

The function returns yes if successful, no if it fails. For example, no is returned if an attempt is made to register an already registered process or to register a process with a name that is already in use.

- -

Releases up to and including OTP R10 did not check if the - process was already registered. As a consequence the - global name table could become inconsistent. The old +

Releases up to and including Erlang/OTP R10 did not check if the + process was already registered. The global name table could + therefore become inconsistent. The old (buggy) behavior can be chosen by giving the Kernel application variable global_multi_name_action the value allow.

-

If a process with a registered name dies, or the node goes down, the name is unregistered on all nodes.

@@ -223,38 +222,20 @@ - All globally registered names - -

Returns a lists of all globally registered names.

-
-
- - - - - Atomically re-register a name - - {Module, Function} - is also allowed - + All globally registered names. -

Atomically changes the registered name Name on all - nodes to refer to Pid.

- -

The Resolve function has the same behavior as in - register_name/2,3.

+

Returns a list of all globally registered names.

- Send a message to a globally registered pid + Send a message to a globally registered pid. -

Sends the message Msg to the pid globally registered +

Sends message Msg to the pid globally registered as Name.

- -

Failure: If Name is not a globally registered - name, the calling function will exit with reason +

If Name is not a globally registered + name, the calling function exits with reason {badarg, {Name, Msg}}.

@@ -263,7 +244,7 @@ - Set a lock on the specified nodes + Set a lock on the specified nodes. @@ -271,50 +252,48 @@ are specified) on ResourceId for LockRequesterId. If a lock already exists on ResourceId for another requester than - LockRequesterId, and Retries is not equal to 0, - the process sleeps for a while and will try to execute - the action later. When Retries attempts have been made, - false is returned, otherwise true. If - Retries is infinity, true is eventually - returned (unless the lock is never released).

- -

If no value for Retries is given, infinity is - used.

- + LockRequesterId, and Retries + is not equal to 0, the process sleeps for a while and tries + to execute the action later. When Retries + attempts have been made, false is returned, otherwise + true. If Retries is infinity, + true is eventually returned (unless the lock is never + released).

+

If no value for Retries is specified, + infinity is used.

This function is completely synchronous.

- -

If a process which holds a lock dies, or the node goes +

If a process that holds a lock dies, or the node goes down, the locks held by the process are deleted.

-

The global name server keeps track of all processes sharing the same lock, that is, if two processes set the same lock, both processes must delete the lock.

-

This function does not address the problem of a deadlock. A deadlock can never occur as long as processes only lock one - resource at a time. But if some processes try to lock two or - more resources, a deadlock may occur. It is up to the + resource at a time. A deadlock can occur if some processes + try to lock two or more resources. It is up to the application to detect and rectify a deadlock.

- -

Some values of ResourceId should be avoided or - Erlang/OTP will not work properly. A list of resources to - avoid: global, dist_ac, - mnesia_table_lock, mnesia_adjust_log_writes, - pg2.

+

Avoid the following values of ResourceId, + otherwise Erlang/OTP does not work properly:

+ + dist_ac + global + mnesia_adjust_log_writes + mnesia_table_lock + pg2 +
-
- Synchronize the global name server + Synchronize the global name server.

Synchronizes the global name server with all nodes known to - this node. These are the nodes which are returned from + this node. These are the nodes that are returned from erlang:nodes(). When this function returns, - the global name server will receive global information from + the global name server receives global information from all nodes. This function can be called when new nodes are added to the network.

The only possible error reason Reason is @@ -326,24 +305,25 @@ - Micro transaction facility + Micro transaction facility. -

Sets a lock on Id (using set_lock/3). If this - succeeds, Fun() is evaluated and the result Res - is returned. Returns aborted if the lock attempt - failed. If Retries is set to infinity, - the transaction will not abort.

- -

infinity is the default setting and will be used if - no value is given for Retries.

+

Sets a lock on Id (using + set_lock/3). + If this succeeds, Fun() is evaluated and the + result Res + is returned. Returns aborted if the lock attempt fails. + If Retries is set to infinity, + the transaction does not abort.

+

infinity is the default setting and is used if + no value is specified for Retries.

- Remove a globally registered name for a pid + Remove a globally registered name for a pid.

Removes the globally registered name Name from the network of Erlang nodes.

@@ -352,7 +332,7 @@ - Get the pid with a given globally registered name + Get the pid with a specified globally registered name.

Returns the pid with the globally registered name Name. Returns undefined if the name is not @@ -363,8 +343,8 @@

See Also -

global_group(3), - net_kernel(3)

+

global_group(3), + net_kernel(3)

diff --git a/lib/kernel/doc/src/global_group.xml b/lib/kernel/doc/src/global_group.xml index 4b21b0a14a..8f947b9adf 100644 --- a/lib/kernel/doc/src/global_group.xml +++ b/lib/kernel/doc/src/global_group.xml @@ -4,7 +4,7 @@
- 19982013 + 19982016 Ericsson AB. All Rights Reserved. @@ -26,22 +26,22 @@ Esko Vierumäki 1998-12-18 - b + B
global_group - Grouping Nodes to Global Name Registration Groups + Grouping nodes to global name registration groups. -

The global group function makes it possible to group the nodes - in a system into partitions, each partition having its own global - name space, refer to global(3). These partitions are - called global groups.

-

The main advantage of dividing systems to global groups is that +

This module makes it possible to partition the nodes of a + system into global groups. Each global group has its own + global namespace, see + global(3).

+

The main advantage of dividing systems into global groups is that the background load decreases while the number of nodes to be updated is reduced when manipulating globally registered names.

The Kernel configuration parameter global_groups defines the global groups (see also - kernel(6), - config(4):

+ kernel(6) + and config(4)):

{global_groups, [GroupTuple :: group_tuple()]}

For the processes and nodes to run smoothly using the global @@ -54,22 +54,24 @@

All involved nodes must agree on the global group definition, - or the behavior of the system is undefined.

+ otherwise the behavior of the system is undefined.

-

All nodes in the system should belong to exactly +

All nodes in the system must belong to exactly one global group.

-

In the following description, a group node is a node +

In the following descriptions, a group node is a node belonging to the same global group as the local node.

- + +

A GroupTuple without PublishType is the same as a - GroupTuple with PublishType == normal.

+ GroupTuple with PublishType equal to normal. +

@@ -78,52 +80,57 @@ -

A node started with the command line flag -hidden, see - erl(1), is said to be a - hidden node. A hidden node will establish hidden +

A node started with command-line flag -hidden (see + erl(1)) is said + to be a hidden node. A hidden node establishes hidden connections to nodes not part of the same global group, but normal (visible) connections to nodes part of the same global group.

-

A global group defined with PublishType == hidden, is - said to be a hidden global group. All nodes in a hidden global - group are hidden nodes, regardless if they are started with - the -hidden command line flag or not.

+

A global group defined with PublishType equal to + hidden is said to be a hidden global group. + All nodes in a hidden global + group are hidden nodes, whether they are started with + command-line flag -hidden or not.

A registered name.

+
+ - Return the global group names + Return the global group names. -

Returns a tuple containing the name of the global group +

Returns a tuple containing the name of the global group that the local node belongs to, and the list of all other known group names. Returns undefined if no global groups are defined.

+ - Information about global groups + Information about global groups.

Returns a list containing information about the global - groups. Each element of the list is a tuple. The order of - the tuples is not defined.

+ groups. Each list element is a tuple. The order of + the tuples is undefined.

{state, State}

If the local node is part of a global group, - State == synced. If no global groups are defined, - State == no_conf.

+ State is equal to synced. + If no global groups are defined, + State is equal to no_conf.

{own_group_name, GroupName} @@ -152,117 +159,131 @@ {other_groups, Groups}

Groups is a list of tuples - {GroupName, Nodes}, specifying the name and nodes + {GroupName, Nodes}, + specifying the name and nodes of the other global groups.

{monitoring, Pids} -

A list of pids, specifying the processes which have +

A list of pids, specifying the processes that have subscribed to nodeup and nodedown messages.

+ - Subscribe to node status changes + Subscribe to node status changes. -

Depending on Flag, the calling process starts - subscribing (Flag == true) or stops subscribing - (Flag == false) to node status change messages.

-

A process which has subscribed will receive the messages +

Depending on Flag, the calling process + starts subscribing (Flag equal to + true) or stops subscribing (Flag + equal to false) to node status change messages.

+

A process that has subscribed receives the messages {nodeup, Node} and {nodedown, Node} when a group node connects or disconnects, respectively.

+ - Return the group nodes + Return the group nodes.

Returns the names of all group nodes, regardless of their current status.

+ - Return globally registered names + Return globally registered names. -

Returns a list of all names which are globally registered +

Returns a list of all names that are globally registered on the specified node or in the specified global group.

+ - Send a message to a globally registered pid + Send a message to a globally registered pid.

Searches for Name, globally registered on - the specified node or in the specified global group, or -- - if the Where argument is not provided -- in any global - group. The global groups are searched in the order in which - they appear in the value of the global_groups - configuration parameter.

-

If Name is found, the message Msg is sent to + the specified node or in the specified global group, or + (if argument Where is not provided) in any + global group. The global groups are searched in the order that + they appear in the value of configuration parameter + global_groups.

+

If Name is found, message + Msg is sent to the corresponding pid. The pid is also the return value of the function. If the name is not found, the function returns {badarg, {Name, Msg}}.

+ - Synchronize the group nodes + Synchronize the group nodes.

Synchronizes the group nodes, that is, the global name - servers on the group nodes. Also check the names globally + servers on the group nodes. Also checks the names globally registered in the current global group and unregisters them on any known node not part of the group.

If synchronization is not possible, an error report is sent - to the error logger (see also error_logger(3)).

-

Failure: - {error, {'invalid global_groups definition', Bad}} if - the global_groups configuration parameter has an + to the error logger (see also + error_logger(3). +

+

Returns {error, {'invalid global_groups definition', Bad}} + if configuration parameter global_groups has an invalid value Bad.

+ - Get the pid with a given globally registered name + Get the pid with a specified globally registered name.

Searches for Name, globally registered on - the specified node or in the specified global group, or -- if - the Where argument is not provided -- in any global - group. The global groups are searched in the order in which - they appear in the value of the global_groups - configuration parameter.

-

If Name is found, the corresponding pid is returned. - If the name is not found, the function returns + the specified node or in the specified global group, or + (if argument Where is not provided) in any global + group. The global groups are searched in the order that + they appear in the value of configuration parameter + global_groups.

+

If Name is found, the corresponding pid is + returned. If the name is not found, the function returns undefined.

- NOTE -

In the situation where a node has lost its connections to other - nodes in its global group, but has connections to nodes in other - global groups, a request from another global group may produce an - incorrect or misleading result. For example, the isolated node may - not have accurate information about registered names in its - global group.

-

Note also that the send/2,3 function is not secure.

-

Distribution of applications is highly dependent of the global - group definitions. It is not recommended that an application is - distributed over several global groups of the obvious reason that - the registered names may be moved to another global group at - failover/takeover. There is nothing preventing doing this, but - the application code must in such case handle the situation.

+ Notes + +

In the situation where a node has lost its connections to other + nodes in its global group, but has connections to nodes in other + global groups, a request from another global group can produce an + incorrect or misleading result. For example, the isolated node can + have inaccurate information about registered names in its + global group.

+

Function + send/2,3 + is not secure.

+

Distribution of applications is highly dependent of the global + group definitions. It is not recommended that an application is + distributed over many global groups, as + the registered names can be moved to another global group at + failover/takeover. Nothing prevents this to be done, but + the application code must then handle the situation.

+
- SEE ALSO -

erl(1), - global(3)

+ See Also +

global(3), + erl(1)

diff --git a/lib/kernel/doc/src/heart.xml b/lib/kernel/doc/src/heart.xml index 9da4773f2d..7c37c5ea00 100644 --- a/lib/kernel/doc/src/heart.xml +++ b/lib/kernel/doc/src/heart.xml @@ -29,93 +29,80 @@ A heart - Heartbeat Monitoring of an Erlang Runtime System + Heartbeat monitoring of an Erlang runtime system.

This modules contains the interface to the heart process. heart sends periodic heartbeats to an external port program, which is also named heart. The purpose of - the heart port program is to check that the Erlang runtime system + the heart port program is to check that the Erlang runtime system it is supervising is still running. If the port program has not received any heartbeats within HEART_BEAT_TIMEOUT seconds - (default is 60 seconds), the system can be rebooted. Also, if + (defaults to 60 seconds), the system can be rebooted. Also, if the system is equipped with a hardware watchdog timer and is running Solaris, the watchdog can be used to supervise the entire system.

-

An Erlang runtime system to be monitored by a heart program, - should be started with the command line flag -heart (see - also erl(1)). The heart - process is then started automatically:

+

An Erlang runtime system to be monitored by a heart program + is to be started with command-line flag -heart (see + also erl(1)). + The heart process is then started automatically:

 % erl -heart ...
-

If the system should be rebooted because of missing heart-beats, - or a terminated Erlang runtime system, the environment variable - HEART_COMMAND has to be set before the system is started. - If this variable is not set, a warning text will be printed but - the system will not reboot. However, if the hardware watchdog is - used, it will trigger a reboot HEART_BEAT_BOOT_DELAY - seconds later nevertheless (default is 60).

-

To reboot on the WINDOWS platform HEART_COMMAND can be +

If the system is to be rebooted because of missing heartbeats, + or a terminated Erlang runtime system, environment variable + HEART_COMMAND must be set before the system is started. + If this variable is not set, a warning text is printed but + the system does not reboot. However, if the hardware watchdog is + used, it still triggers a reboot HEART_BEAT_BOOT_DELAY + seconds later (defaults to 60 seconds).

+

To reboot on Windows, HEART_COMMAND can be set to heart -shutdown (included in the Erlang delivery) - or of course to any other suitable program which can activate a - reboot.

-

The hardware watchdog will not be started under Solaris if - the environment variable HW_WD_DISABLE is set.

-

The HEART_BEAT_TIMEOUT and HEART_BEAT_BOOT_DELAY - environment variables can be used to configure the heart timeouts, - they can be set in the operating system shell before Erlang is - started or be specified at the command line:

+ or to any other suitable program that can activate a reboot.

+

The hardware watchdog is not started under Solaris if + environment variable HW_WD_DISABLE is set.

+

The environment variables HEART_BEAT_TIMEOUT and + HEART_BEAT_BOOT_DELAY can be used to configure the heart + time-outs; they can be set in the operating system shell before Erlang + is started or be specified at the command line:

 % erl -heart -env HEART_BEAT_TIMEOUT 30 ...

The value (in seconds) must be in the range 10 < X <= 65535.

-

It should be noted that if the system clock is adjusted with - more than HEART_BEAT_TIMEOUT seconds, heart will - timeout and try to reboot the system. This can happen, for - example, if the system clock is adjusted automatically by use of - NTP (Network Time Protocol).

- -

If a crash occurs, an will not be written - unless the environment variable is set. -

- +

Notice that if the system clock is adjusted with + more than HEART_BEAT_TIMEOUT seconds, heart + times out and tries to reboot the system. This can occur, for + example, if the system clock is adjusted automatically by use of the + Network Time Protocol (NTP).

+

If a crash occurs, an is not + written unless environment variable + is set:

 % erl -heart -env ERL_CRASH_DUMP_SECONDS 10 ...
- -

If a regular core dump is wanted, let heart know by setting the kill signal to abort - using the environment variable . - If unset, or not set to , the default behaviour will be a kill - signal using . -

- +

If a regular core dump is wanted, let heart know by setting + the kill signal to abort using environment variable + . If unset, or not set to + , the default behavior is a kill signal using + :

 % erl -heart -env HEART_KILL_SIGNAL SIGABRT ...
- -

- Furthermore, has the following behaviour on - heart: -

- - -

- Suppresses the writing a crash dump file entirely, - thus rebooting the runtime system immediately. - This is the same as not setting the environment variable. -

-
- -

Setting the environment variable to a negative value will not reboot - the runtime system until the crash dump file has been completly written. -

-
- -

- Heart will wait for S seconds to let the crash dump file be written. - After S seconds heart will reboot the runtime system regardless of - the crash dump file has been written or not. -

-
-
- -

In the following descriptions, all function fails with reason +

Furthermore, has the + following behavior on heart:

+ + +

Suppresses the writing of a crash dump file entirely, + thus rebooting the runtime system immediately. + This is the same as not setting the environment variable.

+
+ +

Setting the environment variable to a negative value does not + reboot the runtime system until the crash dump file is completly + written.

+
+ +

heart waits for S seconds to let the crash dump + file be written. After S seconds, heart reboots the + runtime system, whether the crash dump file is written or not.

+
+
+

In the following descriptions, all functions fail with reason badarg if heart is not started.

@@ -128,37 +115,36 @@ - Set a temporary reboot command + Set a temporary reboot command. -

Sets a temporary reboot command. This command is used if +

Sets a temporary reboot command. This command is used if a HEART_COMMAND other than the one specified with - the environment variable should be used in order to reboot - the system. The new Erlang runtime system will (if it - misbehaves) use the environment variable - HEART_COMMAND to reboot.

- -

Limitations: The Cmd command string - will be sent to the heart program as a ISO-latin-1 or UTF-8 - encoded binary depending on the file name encoding mode of the - emulator (see - file:native_name_encoding/0). - The size of the encoded binary must be less than 2047 bytes.

+ the environment variable is to be used to reboot + the system. The new Erlang runtime system uses (if it misbehaves) + environment variable HEART_COMMAND to reboot.

+

Limitations: Command string Cmd is sent to the + heart program as an ISO Latin-1 or UTF-8 encoded binary, + depending on the filename encoding mode of the emulator (see + file:native_name_encoding/0). + The size of the encoded binary must be less than 2047 bytes.

+ - Clear the temporary boot command + Clear the temporary boot command.

Clears the temporary boot command. If the system terminates, the normal HEART_COMMAND is used to reboot.

+ - Get the temporary reboot command + Get the temporary reboot command. -

Get the temporary reboot command. If the command is cleared, - the empty string will be returned.

+

Gets the temporary reboot command. If the command is cleared, + the empty string is returned.

@@ -166,12 +152,12 @@ Set a validation callback -

This validation callback will be executed before any heartbeat sent - to the port program. For the validation to succeed it needs to return - with the value ok. +

This validation callback will be executed before any + heartbeat is sent to the port program. For the validation to + succeed it needs to return with the value ok.

-

An exception within the callback will be treated as a validation failure.

-

The callback will be removed if the system reboots.

+

An exception within the callback will be treated as a validation failure.

+

The callback will be removed if the system reboots.

diff --git a/lib/kernel/doc/src/inet.xml b/lib/kernel/doc/src/inet.xml index 088d78c1d6..cfff393b8c 100644 --- a/lib/kernel/doc/src/inet.xml +++ b/lib/kernel/doc/src/inet.xml @@ -29,43 +29,47 @@ A inet - Access to TCP/IP Protocols + Access to TCP/IP protocols. -

Provides access to TCP/IP protocols.

-

See also ERTS User's Guide, Inet configuration for more - information on how to configure an Erlang runtime system for IP - communication.

-

Two Kernel configuration parameters affect the behaviour of all - sockets opened on an Erlang node: - inet_default_connect_options can contain a list of default - options used for all sockets returned when doing connect, - and inet_default_listen_options can contain a list of - default options used when issuing a listen call. When - accept is issued, the values of the listensocket options - are inherited, why no such application variable is needed for +

This module provides access to TCP/IP protocols.

+

See also + ERTS User's Guide: + Inet Configuration for more information about how to + configure an Erlang runtime system for IP communication.

+

The following two Kernel configuration parameters affect the + behavior of all sockets opened on an Erlang node:

+ +

inet_default_connect_options can contain a list of + default options used for all sockets returned when doing + connect.

+

inet_default_listen_options can contain a list of + default options used when issuing a listen call.

+
+

When accept is issued, the values of the listening socket options + are inherited. No such application variable is therefore needed for accept.

-

Using the Kernel configuration parameters mentioned above, one - can set default options for all TCP sockets on a node. This should - be used with care, but options like {delay_send,true} - might be specified in this way. An example of starting an Erlang - node with all sockets using delayed send could look like this:

+

Using the Kernel configuration parameters above, one + can set default options for all TCP sockets on a node, but use this + with care. Options such as {delay_send,true} can be + specified in this way. The following is an example of starting an Erlang + node with all sockets using delayed send:

 $ erl -sname test -kernel \
 inet_default_connect_options '[{delay_send,true}]' \
 inet_default_listen_options '[{delay_send,true}]'
-

Note that the default option {active, true} currently +

Notice that default option {active, true} cannot be changed, for internal reasons.

Addresses as inputs to functions can be either a string or a - tuple. For instance, the IP address 150.236.20.73 can be passed to - gethostbyaddr/1 either as the string "150.236.20.73" - or as the tuple {150, 236, 20, 73}.

-

IPv4 address examples:

+ tuple. For example, the IP address 150.236.20.73 can be passed to + gethostbyaddr/1, either as string "150.236.20.73" + or as tuple {150, 236, 20, 73}.

+

IPv4 address examples:

Address ip_address() ------- ------------ 127.0.0.1 {127,0,0,1} 192.168.42.2 {192,168,42,2} -

IPv6 address examples:

+

IPv6 address examples:

Address ip_address() ------- ------------ @@ -77,7 +81,9 @@ FFFF::192.168.42.2 {16#3ffe,16#b80,16#1f8d,16#2,16#204,16#acff,16#fe17,16#bf38} fe80::204:acff:fe17:bf38 {16#fe80,0,0,0,0,16#204,16#acff,16#fe17,16#bf38} -

A function that may be useful is parse_address/1:

+

Function + parse_address/1 + can be useful:

 1> inet:parse_address("192.168.42.2").
 {ok,{192,168,42,2}}
@@ -89,9 +95,12 @@ fe80::204:acff:fe17:bf38
     
       
       
-        

The record is defined in the Kernel include file "inet.hrl". - Add the following directive to the module:

--include_lib("kernel/include/inet.hrl").
+

The record is defined in the Kernel include file + "inet.hrl".

+

Add the following directive to the module:

+ +-include_lib("kernel/include/inet.hrl"). +
@@ -110,17 +119,20 @@ fe80::204:acff:fe17:bf38 -

An atom which is named from the Posix error codes - used in Unix, and in the runtime libraries of most - C compilers. See + +

An atom that is named from the POSIX error codes used in Unix, + and in the runtime libraries of most C compilers. See section POSIX Error Codes.

socket() -

- See gen_tcp(3) - and gen_udp(3).

+ +

See + gen_tcp:type-socket + and + gen_udp:type-socket. +

@@ -131,443 +143,415 @@ fe80::204:acff:fe17:bf38 - Close a socket of any type + Close a socket of any type.

Closes a socket of any type.

+ - - Return a list of IP configuration parameters + + Return a descriptive string for an error reason. -

Returns the state of the Inet configuration database in - form of a list of recorded configuration parameters. (See the - ERTS User's Guide, Inet configuration, for more information). - Only parameters with other than default values are returned.

+

Returns a diagnostic error string. For possible POSIX values and + corresponding strings, see section + POSIX Error Codes.

+ - - Return a descriptive string for an error reason + + Return a list of IP configuration parameters. -

Returns a diagnostic error string. See the section below - for possible Posix values and the corresponding - strings.

+

Returns the state of the Inet configuration database in + form of a list of recorded configuration parameters. For more + information, see ERTS User's Guide: + Inet Configuration. + Only parameters with other than default values are returned.

+ - Return the IP-address for a host + Return the IP address for a host. -

Returns the IP-address for Host as a tuple of - integers. Host can be an IP-address, a single hostname - or a fully qualified hostname.

+

Returns the IP address for Host as a tuple of + integers. Host can be an IP address, a single + hostname, or a fully qualified hostname.

+ - Return the IP-addresses for a host + Return the IP addresses for a host. -

Returns a list of all IP-addresses for Host. - Host can be an IP-address, a single hostname or a fully - qualified hostname.

+

Returns a list of all IP addresses for Host. + Host can be an IP address, a single hostname, or + a fully qualified hostname.

+ - Return a hostent record for the host with the given address + Return a hostent record for the host with the specified + address. -

Returns a hostent record given an address.

-
+

Returns a hostent record for the host with the specified + address.

+ - Return a hostent record for the host with the given name + Return a hostent record for the host with the specified name. + -

Returns a hostent record given a hostname.

+

Returns a hostent record for the host with the specified + hostname.

+ - Return a hostent record for the host with the given name + Return a hostent record for the host with the specified name. + -

Returns a hostent record given a hostname, restricted - to the given address family.

+

Returns a hostent record for the host with the specified + name, restricted to the specified address family.

+ - Return the local hostname + Return the local hostname. -

Returns the local hostname. Will never fail.

+

Returns the local hostname. Never fails.

- Return a list of interfaces and their addresses - -

- Returns a list of 2-tuples containing interface names and the - interface's addresses. Ifname is a Unicode string. - Hwaddr is hardware dependent, e.g on Ethernet interfaces - it is the 6-byte Ethernet address (MAC address (EUI-48 address)). -

-

- The {addr,Addr}, {netmask,_} and {broadaddr,_} - tuples are repeated in the result list iff the interface has multiple - addresses. If you come across an interface that has - multiple {flag,_} or {hwaddr,_} tuples you have - a really strange interface or possibly a bug in this function. - The {flag,_} tuple is mandatory, all other optional. -

-

- Do not rely too much on the order of Flag atoms or - Ifopt tuples. There are some rules, though:

- - - Immediately after {addr,_} follows {netmask,_} - - - Immediately thereafter follows {broadaddr,_} if - the broadcast flag is not set and the - pointtopoint flag is set. - - - Any {netmask,_}, {broadaddr,_} or - {dstaddr,_} tuples that follow an {addr,_} - tuple concerns that address. - - -

- The {hwaddr,_} tuple is not returned on Solaris since the - hardware address historically belongs to the link layer and only - the superuser can read such addresses. -

-

- On Windows, the data is fetched from quite different OS API - functions, so the Netmask and Broadaddr - values may be calculated, just as some Flag values. - You have been warned. Report flagrant bugs. -

-
+ Return a list of interfaces and their addresses. + +

Returns a list of 2-tuples containing interface names and the + interface addresses. Ifname is a Unicode string. + Hwaddr is hardware dependent, for example, on + Ethernet interfaces + it is the 6-byte Ethernet address (MAC address (EUI-48 address)).

+

The tuples {addr,Addr}, {netmask,_}, and + {broadaddr,_} are repeated in the result list if the interface + has multiple addresses. If you come across an interface with + multiple {flag,_} or {hwaddr,_} tuples, you have + a strange interface or possibly a bug in this function. The tuple + {flag,_} is mandatory, all others are optional.

+

Do not rely too much on the order of Flag atoms + or Ifopt tuples. There are however some rules:

+ +

Immediately after + {addr,_} follows {netmask,_}.

+

Immediately thereafter follows {broadaddr,_} if flag + broadcast is not set and flag + pointtopoint is set.

+

Any {netmask,_}, {broadaddr,_}, or + {dstaddr,_} tuples that follow an {addr,_} + tuple concerns that address.

+
+

The tuple {hwaddr,_} is not returned on Solaris, as the + hardware address historically belongs to the link layer and only + the superuser can read such addresses.

+ +

On Windows, the data is fetched from different OS API functions, + so the Netmask and Broadaddr + values can be calculated, just as some Flag + values. Report flagrant bugs.

+
+
- Get one or more options for a socket + Get one or more options for a socket. -

Gets one or more options for a socket. - See setopts/2 - for a list of available options.

-

The number of elements in the returned OptionValues +

Gets one or more options for a socket. For a list of available + options, see + setopts/2.

+

The number of elements in the returned + OptionValues list does not necessarily correspond to the number of options asked for. If the operating system fails to support an option, - it is simply left out in the returned list. An error tuple is only - returned when getting options for the socket is impossible - (i.e. the socket is closed or the buffer size in a raw request + it is left out in the returned list. An error tuple is returned + only when getting options for the socket is impossible (that is, + the socket is closed or the buffer size in a raw request is too large). This behavior is kept for backward compatibility reasons.

-

A raw option request RawOptReq = {raw, Protocol, OptionNum, ValueSpec} can be used to get information about +

A raw option request + RawOptReq = {raw, Protocol, OptionNum, ValueSpec} + can be used to get information about socket options not (explicitly) supported by the emulator. The - use of raw socket options makes the code non portable, but + use of raw socket options makes the code non-portable, but allows the Erlang programmer to take advantage of unusual features present on the current platform.

-

The RawOptReq consists of the tag raw followed - by the protocol level, the option number and either a binary +

RawOptReq consists of tag raw followed + by the protocol level, the option number, and either a binary or the size, in bytes, of the - buffer in which the option value is to be stored. A binary - should be used when the underlying getsockopt requires - input - in the argument field, in which case the size of the binary - should correspond to the required buffer + buffer in which the option value is to be stored. A binary is to be + used when the underlying getsockopt requires input + in the argument field. In this case, the binary size + is to correspond to the required buffer size of the return value. The supplied values in a RawOptReq - correspond to the second, third and fourth/fifth parameters to the + correspond to the second, third, and fourth/fifth parameters to the getsockopt call in the C socket API. The value stored - in the buffer is returned as a binary ValueBin + in the buffer is returned as a binary ValueBin, where all values are coded in the native endianess.

-

Asking for and inspecting raw socket options require low - level information about the current operating system and TCP - stack.

-

As an example, consider a Linux machine where the - TCP_INFO option could be used to collect TCP statistics - for a socket. Lets say we're interested in the - tcpi_sacked field of the struct tcp_info - filled in when asking for TCP_INFO. To - be able to access this information, we need to know both the - numeric value of the protocol level IPPROTO_TCP, the - numeric value of the option TCP_INFO, the size of the - struct tcp_info and the size and offset of - the specific field. By inspecting the headers or writing a small C - program, we found IPPROTO_TCP to be 6, - TCP_INFO to be 11, the structure size to be 92 (bytes), - the offset of tcpi_sacked to be 28 bytes and the actual - value to be a 32 bit integer. We could use the following - code to retrieve the value:

+

Asking for and inspecting raw socket options require low-level + information about the current operating system and TCP stack.

+

Example:

+

Consider a Linux machine where option + TCP_INFO can be used to collect TCP statistics + for a socket. Assume you are interested in field + tcpi_sacked of struct tcp_info + filled in when asking for TCP_INFO. To be able to access + this information, you need to know the following:

+ + The numeric value of protocol level IPPROTO_TCP + The numeric value of option TCP_INFO + The size of struct tcp_info + The size and offset of the specific field + +

By inspecting the headers or writing a small C program, it is found + that IPPROTO_TCP is 6, TCP_INFO is 11, the structure + size is 92 (bytes), the offset of tcpi_sacked is 28 bytes, + and the value is a 32-bit integer. The following code can be used + to retrieve the value:

- {ok,[{raw,_,_,Info}]} = inet:getopts(Sock,[{raw,6,11,92}]), - <<_:28/binary,TcpiSacked:32/native,_/binary>> = Info, - TcpiSacked.]]> -

Preferably, you would check the machine type, the OS - and the kernel version prior to executing anything similar to the - code above.

+get_tcpi_sacked(Sock) -> + {ok,[{raw,_,_,Info}]} = inet:getopts(Sock,[{raw,6,11,92}]), + <<_:28/binary,TcpiSacked:32/native,_/binary>> = Info, + TcpiSacked.]]> +

Preferably, you would check the machine type, the operating system, + and the Kernel version before executing anything similar to + this code.

- Get one or more statistic options for a socket + Get one or more statistic options for a socket.

Gets one or more statistic options for a socket.

- -

getstat(Socket) is equivalent to - getstat(Socket, [recv_avg, recv_cnt, recv_dvi, - recv_max, recv_oct, send_avg, send_cnt, send_dvi, send_max, - send_oct]).

-

The following options are available:

+

getstat(Socket) is equivalent to + getstat(Socket, [recv_avg, recv_cnt, recv_dvi, + recv_max, recv_oct, send_avg, send_cnt, send_dvi, send_max, + send_oct]).

+

The following options are available:

- recv_avg - -

Average size of packets in bytes received by the socket.

-
- recv_cnt - + recv_avg + +

Average size of packets, in bytes, received by the socket.

+
+ recv_cnt +

Number of packets received by the socket.

-
- recv_dvi - -

Average packet size deviation in bytes received by the socket.

-
- recv_max - -

The size of the largest packet in bytes received by the socket.

-
- recv_oct - + + recv_dvi + +

Average packet size deviation, in bytes, received by the socket.

+
+ recv_max + +

Size of the largest packet, in bytes, received by the socket.

+
+ recv_oct +

Number of bytes received by the socket.

-
- - send_avg - -

Average size of packets in bytes sent from the socket.

-
- send_cnt - + + send_avg + +

Average size of packets, in bytes, sent from the socket.

+
+ send_cnt +

Number of packets sent from the socket.

-
- send_dvi - -

Average packet size deviation in bytes sent from the socket.

-
- send_max - -

The size of the largest packet in bytes sent from the socket.

-
- send_oct - + + send_dvi + +

Average packet size deviation, in bytes, sent from the socket.

+
+ send_max + +

Size of the largest packet, in bytes, sent from the socket.

+
+ send_oct +

Number of bytes sent from the socket.

-
+
+ - Convert IPv6 / IPV4 adress to ascii + Convert IPv6/IPV4 address to ASCII. + +

Parses an + ip_address() + and returns an IPv4 or IPv6 address string.

+
+
+ + + + Parse an IPv4 or IPv6 address. -

Parses an ip_address() and returns an IPv4 or IPv6 address string.

+

Parses an IPv4 or IPv6 address string and returns an + ip4_address() or + ip6_address(). + Accepts a shortened IPv4 address string.

+ - Parse an IPv4 address + Parse an IPv4 address. -

Parses an IPv4 address string and returns an ip4_address(). - Accepts a shortened IPv4 shortened address string.

+

Parses an IPv4 address string and returns an + ip4_address(). + Accepts a shortened IPv4 address string.

+ Parse an IPv4 address strict. -

Parses an IPv4 address string containing four fields, i.e not shortened, and returns an ip4_address().

+

Parses an IPv4 address string containing four fields, that is, + not shortened, and returns an + ip4_address(). +

+ - Parse an IPv6 address + Parse an IPv6 address. -

Parses an IPv6 address string and returns an ip6_address(). - If an IPv4 address string is passed, an IPv4-mapped IPv6 address is returned.

+

Parses an IPv6 address string and returns an + ip6_address(). + If an IPv4 address string is specified, an IPv4-mapped IPv6 address + is returned.

+ Parse an IPv6 address strict. -

Parses an IPv6 address string and returns an ip6_address(). - Does not accept IPv4 adresses.

-
-
- - - Parse an IPv4 or IPv6 address. - -

Parses an IPv4 or IPv6 address string and returns an ip4_address() or ip6_address(). Accepts a shortened IPv4 address string.

+

Parses an IPv6 address string and returns an + ip6_address(). + Does not accept IPv4 addresses.

+ Parse an IPv4 or IPv6 address strict. -

Parses an IPv4 or IPv6 address string and returns an ip4_address() or ip6_address(). Does not accept a shortened IPv4 address string.

+

Parses an IPv4 or IPv6 address string and returns an + ip4_address() or + ip6_address(). + Does not accept a shortened IPv4 address string.

+ - Return the address and port for the other end of a connection + Return the address and port for the other end of a connection. + -

- Returns the address and port for the other end of a - connection. -

-

- Note that for SCTP sockets this function only returns - one of the socket's peer addresses. The function - peernames/1,2 - returns all. -

+

Returns the address and port for the other end of a connection.

+

Notice that for SCTP sockets, this function returns only + one of the peer addresses of the socket. Function + peernames/1,2 + returns all.

+ - - Return all address/port numbers for the other end of a connection - + Return all address/port numbers for the other end of a + connection. -

- Equivalent to +

Equivalent to peernames(Socket, 0). - Note that this function's behaviour for an SCTP +

+

Notice that the behavior of this function for an SCTP one-to-many style socket is not defined by the - SCTP Sockets API Extensions. -

+ SCTP Sockets API Extensions.

+ - - Return all address/port numbers for the other end of a connection - + Return all address/port numbers for the other end of a + connection. -

- Returns a list of all address/port number pairs for the other end - of a socket's association Assoc. -

-

- This function can return multiple addresses for multihomed - sockets such as SCTP sockets. For other sockets it - returns a one element list. -

-

- Note that the Assoc parameter is by the +

Returns a list of all address/port number pairs for the other end + of an association Assoc of a socket.

+

This function can return multiple addresses for multihomed + sockets, such as SCTP sockets. For other sockets it + returns a one-element list.

+

Notice that parameter Assoc is by the SCTP Sockets API Extensions defined to be ignored for - one-to-one style sockets. What the special value 0 - means hence its behaviour for one-to-many style sockets - is unfortunately not defined. -

+ one-to-one style sockets. What the special value 0 + means, hence its behavior for one-to-many style sockets, + is unfortunately undefined.

+ - Return the local port number for a socket + Return the local port number for a socket.

Returns the local port number for a socket.

- - - Return the local address and port number for a socket - -

Returns the local address and port number for a socket.

-

- Note that for SCTP sockets this function only returns - one of the socket addresses. The function - socknames/1,2 - returns all. -

-
-
- - - Return all local address/port numbers for a socket - -

- Equivalent to - socknames(Socket, 0). -

-
-
- - - Return all local address/port numbers for a socket - -

- Returns a list of all local address/port number pairs for a socket - for the given association Assoc. -

-

- This function can return multiple addresses for multihomed - sockets such as SCTP sockets. For other sockets it - returns a one element list. -

-

- Note that the Assoc parameter is by the - SCTP Sockets API Extensions - defined to be ignored for one-to-one style sockets. - For one-to-many style sockets the special value 0 - is defined to mean that the returned addresses shall be - without regard to any particular association. - How different SCTP implementations interprets this varies somewhat. -

-
-
+ - Set one or more options for a socket + Set one or more options for a socket. -

Sets one or more options for a socket. The following options - are available:

+

Sets one or more options for a socket.

+

The following options are available:

{active, true | false | once | N}

If the value is true, which is the default, - everything received from the socket will be sent as - messages to the receiving process. If the value is - false (passive mode), the process must explicitly - receive incoming data by calling + everything received from the socket is sent as + messages to the receiving process.

+

If the value is false (passive mode), the process must + explicitly receive incoming data by calling gen_tcp:recv/2,3, - gen_udp:recv/2,3 + gen_udp:recv/2,3, or gen_sctp:recv/1,2 (depending on the type of socket).

If the value is once ({active, once}), - one data message from the socket will be sent - to the process. To receive one more message, - setopts/2 must be called again with the - {active, once} option.

+ one data message from the socket is sent + to the process. To receive one more message, + setopts/2 must be called again with option + {active, once}.

If the value is an integer N in the range -32768 to 32767 (inclusive), the value is added to the socket's count of data messages sent to the controlling process. A socket's default - message count is 0. If a negative value is specified and its - magnitude is equal to or greater than the socket's current - message count, the socket's message count is set to 0. Once - the socket's message count reaches 0, either due to sending + message count is 0. If a negative value is specified, and + its magnitude is equal to or greater than the socket's current + message count, the socket's message count is set to 0. + Once the socket's message count reaches 0, either because + of sending received data messages to the process or by being explicitly set, the process is then notified by a special message, specific to the type of socket, that the socket has entered passive @@ -575,339 +559,298 @@ fe80::204:acff:fe17:bf38 messages setopts/2 must be called again to set the socket back into an active mode.

When using {active, once} or {active, N}, the - socket changes behaviour automatically when data is received. - This can sometimes be confusing in combination with - connection-oriented sockets (i.e. gen_tcp) as a socket - with {active, false} behaviour reports closing + socket changes behavior automatically when data is received. + This can be confusing in combination with connection-oriented + sockets (that is, gen_tcp), as a socket + with {active, false} behavior reports closing differently than a socket with {active, true} - behaviour. To make programming easier, a socket where - the peer closed and this was detected while in - {active, false} mode, will still generate the - message + behavior. To simplify programming, a socket where + the peer closed, and this is detected while in + {active, false} mode, still generates message {tcp_closed,Socket} when set to {active, once}, - {active, true} or {active, N} mode. It is therefore - safe to assume that the message - {tcp_closed,Socket}, possibly followed by socket - port termination (depending on the exit_on_close - option) will eventually appear when a socket changes + {active, true}, or {active, N} mode. + It is therefore safe to assume that message + {tcp_closed,Socket}, possibly followed by socket port + termination (depending on option exit_on_close) + eventually appears when a socket changes back and forth between {active, true} and {active, false} mode. However, - when peer closing is detected is all up to the + when peer closing is detected it is all up to the underlying TCP/IP stack and protocol.

-

Note that {active, true} mode provides no flow - control; a fast sender could easily overflow the - receiver with incoming messages. The same is true of - {active, N} mode while the message count is greater - than zero. Use active mode only if +

Notice that {active, true} mode provides no flow + control; a fast sender can easily overflow the + receiver with incoming messages. The same is true for + {active, N} mode, while the message count is greater + than zero.

+

Use active mode only if your high-level protocol provides its own flow control - (for instance, acknowledging received messages) or the + (for example, acknowledging received messages) or the amount of data exchanged is small. {active, false} - mode, use of the {active, once} mode or {active, N} + mode, use of the {active, once} mode, or {active, N} mode with values of N appropriate for the application - provides flow control; the other side will not be able send + provides flow control. The other side cannot send faster than the receiver can read.

- - {broadcast, Boolean}(UDP sockets) + {broadcast, Boolean} (UDP sockets) -

Enable/disable permission to send broadcasts.

- +

Enables/disables permission to send broadcasts.

+ +
+ {buffer, Size} + +

The size of the user-level software buffer used by + the driver. Not to be confused with options sndbuf + and recbuf, which correspond to the + Kernel socket buffers. It is recommended + to have val(buffer) >= max(val(sndbuf),val(recbuf)) to + avoid performance issues because of unnecessary copying. + val(buffer) is automatically set to the above + maximum when values sndbuf or recbuf are set. + However, as the sizes set for sndbuf and recbuf + usually become larger, you are encouraged to use + getopts/2 + to analyze the behavior of your operating system.

- - {buffer, Size} - -

The size of the user-level software buffer used by - the driver. Not to be confused with sndbuf - and recbuf options which correspond to - the kernel socket buffers. It is recommended - to have val(buffer) >= max(val(sndbuf),val(recbuf)) to - avoid performance issues due to unnecessary copying. - In fact, the val(buffer) is automatically set to - the above maximum when sndbuf or recbuf values are set. - However, since the actual sizes set for sndbuf and recbuf - usually becomes larger, you are encouraged to use - inet:getopts/2 - to analyze the behavior of your operating system.

-
- {delay_send, Boolean}

Normally, when an Erlang process sends to a socket, - the driver will try to immediately send the data. If that - fails, the driver will use any means available to queue + the driver tries to send the data immediately. If that + fails, the driver uses any means available to queue up the message to be sent whenever the operating system says it can handle it. Setting {delay_send, true} - will make all messages queue up. This makes - the messages actually sent onto the network be larger but - fewer. The option actually affects the scheduling of send + makes all messages queue up. The messages sent + to the network are then larger but fewer. + The option affects the scheduling of send requests versus Erlang processes instead of changing any - real property of the socket. Needless to say it is an - implementation specific option. Default is false.

+ real property of the socket. The option is + implementation-specific. Defaults to false.

+
+ {deliver, port | term} + +

When {active, true}, data is delivered on the form + port : {S, {data, [H1,..Hsz | Data]}} or + term : {tcp, S, [H1..Hsz | Data]}.

- - {deliver, port | term} -

When {active, true} delivers data on the forms - port : {S, {data, [H1,..Hsz | Data]}} or - term : {tcp, S, [H1..Hsz | Data]}. -

-
- {dontroute, Boolean} -

Enable/disable routing bypass for outgoing messages.

+

Enables/disables routing bypass for outgoing messages.

- {exit_on_close, Boolean} -

By default this option is set to true.

+

This option is set to true by default.

The only reason to set it to false is if you want - to continue sending data to the socket after a close has - been detected, for instance if the peer has used - gen_tcp:shutdown/2 - to shutdown the write side.

+ to continue sending data to the socket after a close is + detected, for example, if the peer uses + gen_tcp:shutdown/2 + to shut down the write side.

- {header, Size} -

This option is only meaningful if the binary - option was specified when the socket was created. If - the header option is specified, the first +

This option is only meaningful if option binary + was specified when the socket was created. If option + header is specified, the first Size number bytes of data received from the socket - will be elements of a list, and the rest of the data will - be a binary given as the tail of the same list. If for - example Size == 2, the data received will match + are elements of a list, and the remaining data is + a binary specified as the tail of the same list. For example, + if Size == 2, the data received matches [Byte1,Byte2|Binary].

- {high_msgq_watermark, Size} -

The socket message queue will be set into a busy - state when the amount of data queued on the message - queue reaches this limit. Note that this limit only - concerns data that have not yet reached the ERTS internal - socket implementation. Default value used is 8 kB.

-

Senders of data to the socket will be suspended if - either the socket message queue is busy, or the socket - itself is busy.

-

For more information see the low_msgq_watermark, - high_watermark, and low_watermark options.

-

Note that distribution sockets will disable the use of - high_msgq_watermark and low_msgq_watermark, - and will instead use the - distribution - buffer busy limit which is a similar feature.

+

The socket message queue is set to a busy + state when the amount of data on the message + queue reaches this limit. Notice that this limit only + concerns data that has not yet reached the ERTS internal + socket implementation. Defaults to 8 kB.

+

Senders of data to the socket are suspended if + either the socket message queue is busy or the socket + itself is busy.

+

For more information, see options low_msgq_watermark, + high_watermark, and low_watermark.

+

Notice that distribution sockets disable the use of + high_msgq_watermark and low_msgq_watermark. + Instead use the + distribution buffer busy limit, + which is a similar feature.

- {high_watermark, Size} (TCP/IP sockets) -

The socket will be set into a busy state when the amount - of data queued internally by the ERTS socket implementation - reaches this limit. Default value used is 8 kB.

-

Senders of data to the socket will be suspended if - either the socket message queue is busy, or the socket - itself is busy.

-

For more information see the low_watermark, - high_msgq_watermark, and low_msqg_watermark - options.

+

The socket is set to a busy state when the amount + of data queued internally by the ERTS socket implementation + reaches this limit. Defaults to 8 kB.

+

Senders of data to the socket are suspended if + either the socket message queue is busy or the socket + itself is busy.

+

For more information, see options low_watermark, + high_msgq_watermark, and low_msqg_watermark.

- {ipv6_v6only, Boolean} -

- Restricts the socket to only use IPv6, prohibiting any +

Restricts the socket to use only IPv6, prohibiting any IPv4 connections. This is only applicable for - IPv6 sockets (option inet6). -

-

- On most platforms this option has to be set on the socket - before associating it to an address. Therefore it is only - reasonable to give it when creating the socket and not - to use it when calling the function - (setopts/2) - containing this description. -

-

- The behaviour of a socket with this socket option set to - true is becoming the only portable one. The original + IPv6 sockets (option inet6).

+

On most platforms this option must be set on the socket + before associating it to an address. It is therefore only + reasonable to specify it when creating the socket and not + to use it when calling function + (setopts/2) + containing this description.

+

The behavior of a socket with this option set to + true is the only portable one. The original idea when IPv6 was new of using IPv6 for all traffic is now not recommended by FreeBSD (you can use {ipv6_v6only,false} to override the recommended system default value), - forbidden by OpenBSD (the supported GENERIC kernel) - and impossible on Windows (that has separate + forbidden by OpenBSD (the supported GENERIC kernel), + and impossible on Windows (which has separate IPv4 and IPv6 protocol stacks). Most Linux distros still have a system default value of false. - This policy shift among operating systems towards - separating IPv6 from IPv4 traffic has evolved since + This policy shift among operating systems to + separate IPv6 from IPv4 traffic has evolved, as it gradually proved hard and complicated to get - a dual stack implementation correct and secure. -

-

- On some platforms the only allowed value for this option - is true, e.g. OpenBSD and Windows. Trying to set - this option to false when creating the socket - will in this case fail. -

-

- Setting this option on platforms where it does not exist - is ignored and getting this option with - getopts/2 - returns no value i.e the returned list will not contain an - {ipv6_v6only,_} tuple. On Windows the option acually - does not exist, but it is emulated as being a - read-only option with the value true. -

-

- So it boils down to that setting this option to true - when creating a socket will never fail except possibly - (at the time of this writing) on a platform where you + a dual stack implementation correct and secure.

+

On some platforms, the only allowed value for this option + is true, for example, OpenBSD and Windows. Trying to set + this option to false, when creating the socket, fails + in this case.

+

Setting this option on platforms where it does not exist + is ignored. Getting this option with + getopts/2 + returns no value, that is, the returned list does not contain an + {ipv6_v6only,_} tuple. On Windows, the option + does not exist, but it is emulated as a + read-only option with value true.

+

Therefore, setting this option to true + when creating a socket never fails, except possibly on a + platform where you have customized the kernel to only allow false, - which might be doable (but weird) on e.g. OpenBSD. -

-

- If you read back the option value using - getopts/2 - and get no value the option does not exist in the host OS - and all bets are off regarding the behaviour of both - an IPv6 and an IPv4 socket listening on the same port - as well as for an IPv6 socket getting IPv4 traffic. -

+ which can be doable (but awkward) on, for example, OpenBSD.

+

If you read back the option value using + getopts/2 + and get no value, the option does not exist in the host + operating system. The behavior of both an IPv6 and an IPv4 + socket listening on the same port, and for an IPv6 socket + getting IPv4 traffic is then no longer predictable.

- {keepalive, Boolean}(TCP/IP sockets)

Enables/disables periodic transmission on a connected - socket, when no other data is being exchanged. If + socket when no other data is exchanged. If the other end does not respond, the connection is - considered broken and an error message will be sent to - the controlling process. Default disabled.

- + considered broken and an error message is sent to + the controlling process. Defaults to disabled.

+ +
+ {linger, {true|false, Seconds}} + +

Determines the time-out, in seconds, for flushing unsent data + in the close/1 socket call. If the first component of + the value tuple is false, the second is ignored. This + means that close/1 returns immediately, not waiting + for data to be flushed. Otherwise, the second component is + the flushing time-out, in seconds.

- - {linger, {true|false, Seconds}} - -

Determines the timeout in seconds for flushing unsent data in the - close/1 socket call. If the 1st component of the value - tuple is false, the 2nd one is ignored, which means that - close/1 returns immediately not waiting - for data to be flushed. Otherwise, the 2nd component is - the flushing time-out in seconds.

-
- {low_msgq_watermark, Size}

If the socket message queue is in a busy state, the - socket message queue will be set in a not busy state when - the amount of data queued in the message queue falls - below this limit. Note that this limit only concerns data - that have not yet reached the ERTS internal socket - implementation. Default value used is 4 kB.

-

Senders that have been suspended due to either a - busy message queue or a busy socket, will be resumed - when neither the socket message queue, nor the socket - are busy.

-

For more information see the high_msgq_watermark, - high_watermark, and low_watermark options.

-

Note that distribution sockets will disable the use of - high_msgq_watermark and low_msgq_watermark, - and will instead use the - distribution - buffer busy limit which is a similar feature.

+ socket message queue is set in a not busy state when + the amount of data queued in the message queue falls + below this limit. Notice that this limit only concerns data + that has not yet reached the ERTS internal socket + implementation. Defaults to 4 kB.

+

Senders that are suspended because of either a + busy message queue or a busy socket are resumed + when the socket message queue and the socket + are not busy.

+

For more information, see options high_msgq_watermark, + high_watermark, and low_watermark.

+

Notice that distribution sockets disable the use of + high_msgq_watermark and low_msgq_watermark. + Instead they use the + distribution + buffer busy limit, which is a similar feature.

- {low_watermark, Size} (TCP/IP sockets) -

If the socket is in a busy state, the socket will - be set in a not busy state when the amount of data - queued internally by the ERTS socket implementation - falls below this limit. Default value used is 4 kB.

-

Senders that have been suspended due to either a - busy message queue or a busy socket, will be resumed - when neither the socket message queue, nor the socket - are busy.

-

For more information see the high_watermark, - high_msgq_watermark, and low_msgq_watermark - options.

+

If the socket is in a busy state, the socket is + set in a not busy state when the amount of data + queued internally by the ERTS socket implementation + falls below this limit. Defaults to 4 kB.

+

Senders that are suspended because of a + busy message queue or a busy socket are resumed + when the socket message queue and the socket are not busy.

+

For more information, see options high_watermark, + high_msgq_watermark, and low_msgq_watermark.

- - {mode, Mode :: binary | list} + {mode, Mode :: binary | list} -

Received Packet is delivered as defined by Mode.

-
- +

Received Packet is delivered as defined by Mode. +

+ {netns, Namespace :: file:filename_all()} -

Set a network namespace for the socket. The Namespace - parameter is a filename defining the namespace for example - "/var/run/netns/example" typically created by the command - ip netns add example. This option must be used in a - function call that creates a socket i.e - - gen_tcp:connect/3,4, - - gen_tcp:listen/2, - - gen_udp:open/1,2 or - - gen_sctp:open/0-2. -

-

This option uses the Linux specific syscall - setns() such as in Linux kernel 3.0 or later - and therefore only exists when the runtime system - has been compiled for such an operating system. -

-

- The virtual machine also needs elevated privileges either - running as superuser or (for Linux) having the capability - CAP_SYS_ADMIN according to the documentation for setns(2). - However, during testing also CAP_SYS_PTRACE - and CAP_DAC_READ_SEARCH has proven to be necessary. - Example:

-setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp - -

Note also that the filesystem containing the virtual machine - executable (beam.smp in the example above) has to be local, - mounted without the nosetuid flag, - support extended attributes and that - the kernel has to support file capabilities. - All this runs out of the box on at least Ubuntu 12.04 LTS, - except that SCTP sockets appears to not support - network namespaces. -

-

The Namespace is a file name and is encoded - and decoded as discussed in - file - except that the emulator flag +fnu is ignored and - getopts/2 - for this option will return a binary for the filename - if the stored filename can not be decoded, - which should only happen if you set the option using a binary - that can not be decoded with the emulator's filename encoding: - - file:native_name_encoding/0. -

-
- - list +

Sets a network namespace for the socket. Parameter + Namespace is a filename defining the namespace, for + example, "/var/run/netns/example", typically created by + command ip netns add example. This option must be used in + a function call that creates a socket, that is, + gen_tcp:connect/3,4, + gen_tcp:listen/2, + gen_udp:open/1,2, or + gen_sctp:open/0,1,2.

+

This option uses the Linux-specific syscall + setns(), such as in Linux kernel 3.0 or later, + and therefore only exists when the runtime system + is compiled for such an operating system.

+

The virtual machine also needs elevated privileges, either + running as superuser or (for Linux) having capability + CAP_SYS_ADMIN according to the documentation for + setns(2). + However, during testing also CAP_SYS_PTRACE + and CAP_DAC_READ_SEARCH have proven to be necessary.

+

Example:

+ +setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp +

Notice that the filesystem containing the virtual machine + executable (beam.smp in the example) must be local, + mounted without flag nosetuid, + support extended attributes, and + the kernel must support file capabilities. + All this runs out of the box on at least Ubuntu 12.04 LTS, + except that SCTP sockets appear to not support + network namespaces.

+

Namespace is a filename and is encoded + and decoded as discussed in module + file, with the + following exceptions:

+ +

Emulator flag +fnu is ignored.

+

getopts/2 + for this option returns a binary for the filename if the stored + filename cannot be decoded. This is only to occur if you set the + option using a binary that cannot be decoded with the emulator's + filename encoding: + file:native_name_encoding/0.

+
+ + list -

Received Packet is delivered as a list.

-
- - binary +

Received Packet is delivered as a list.

+ + binary -

Received Packet is delivered as a binary.

-
- +

Received Packet is delivered as a binary.

+ {nodelay, Boolean}(TCP/IP sockets) -

If Boolean == true, the TCP_NODELAY option - is turned on for the socket, which means that even small - amounts of data will be sent immediately.

+

If Boolean == true, option TCP_NODELAY + is turned on for the socket, which means that also small + amounts of data are sent immediately.

{packet, PacketType}(TCP/IP sockets)

Defines the type of packets to use for a socket. - The following values are valid:

+ Possible values:

raw | 0 @@ -917,104 +860,99 @@ setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp

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 header length can be one, two, or four bytes, and containing an unsigned integer in big-endian byte order. - Each send operation will generate the header, and the header - will be stripped off on each receive operation.

-

In current implementation the 4-byte header is limited to 2Gb.

+ Each send operation generates the header, and the header + is stripped off on each receive operation.

+

The 4-byte header is limited to 2Gb.

asn1 | cdr | sunrm | fcgi | tpkt | line

These packet types only have effect on receiving. When sending a packet, it is the responsibility of the application to supply a correct header. On - receiving, however, there will be one message sent to + receiving, however, one message is sent to the controlling process for each complete packet received, and, similarly, each call to gen_tcp:recv/2,3 returns one complete packet. The header is not stripped off.

-

The meanings of the packet types are as follows: -

-asn1 - ASN.1 BER, -

-sunrm - Sun's RPC encoding, -

-cdr - CORBA (GIOP 1.1), -

-fcgi - Fast CGI, -

-tpkt - TPKT format [RFC1006], -

-line - Line mode, a packet is a line - terminated with newline, lines longer than - the receive buffer are truncated.

-
+

The meanings of the packet types are as follows:

+ + asn1 - ASN.1 BER + sunrm - Sun's RPC encoding + cdr - CORBA (GIOP 1.1) + fcgi - Fast CGI + tpkt - TPKT format [RFC1006] + line - Line mode, a packet is a line-terminated + with newline, lines longer than the receive buffer are + truncated + +
http | http_bin

The Hypertext Transfer Protocol. The packets are returned with the format according to HttpPacket - described in - erlang:decode_packet/3. A socket in passive - mode will return {ok, HttpPacket} from gen_tcp:recv - while an active socket will send messages like {http, - Socket, HttpPacket}.

+ described in + + erlang:decode_packet/3 in ERTS. + A socket in passive + mode returns {ok, HttpPacket} from gen_tcp:recv + while an active socket sends messages like + {http, Socket, HttpPacket}.

httph | httph_bin -

These two types are often not needed as the socket will - automatically switch from http/http_bin to +

These two types are often not needed, as the socket + automatically switches from http/http_bin to httph/httph_bin internally after the first line - has been read. There might be occasions however when they are + is read. However, there can be occasions when they are useful, such as parsing trailers from chunked encoding.

{packet_size, Integer}(TCP/IP sockets) -

Sets the max allowed length of the packet body. If +

Sets the maximum allowed length 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. The same happens if the packet header - is too big for the socket receive buffer.

-

For line oriented protocols (line,http*), - option packet_size also guarantees that lines up to the - indicated length are accepted and not considered invalid due - to internal buffer limitations.

+ is longer than the maximum allowed length, the packet is + considered invalid. The same occurs if the packet header + is too large for the socket receive buffer.

+

For line-oriented protocols (line, http*), + option packet_size also guarantees that lines up to the + indicated length are accepted and not considered invalid + because of internal buffer limitations.

{line_delimiter, Char}(TCP/IP sockets) -

Sets the line delimiting character for line oriented protocols - (line). Default value is $\n.

+

Sets the line delimiting character for line-oriented protocols + (line). Defaults to $\n.

+
+ {priority, Priority} + +

Sets the protocol-defined priority for all packets to be sent + on this socket.

+
+ {raw, Protocol, OptionNum, ValueBin} + +

See below.

- - {priority, Priority} -

Set the protocol-defined priority for all packets to be sent - on this socket.

-
- - {raw, Protocol, OptionNum, ValueBin} -

See below.

-
- {read_packets, Integer}(UDP sockets) -

Sets the max number of UDP packets to read without +

Sets the maximum number of UDP packets to read without intervention from the socket when data is available. When this many packets have been read and delivered to the destination process, new packets are not read until a new notification of available data has arrived. - The default is 5, and if this parameter is set too - high the system can become unresponsive due to + Defaults to 5. If this parameter is set too + high, the system can become unresponsive because of UDP packet flooding.

{recbuf, Size}

The minimum size of the receive buffer to use for the socket. You are encouraged to use - inet:getopts/2, - to retrieve the actual size set by your operating system. - -

+ getopts/2 + to retrieve the size set by your operating system.

{reuseaddr, Boolean} @@ -1023,118 +961,160 @@ setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp {send_timeout, Integer} -

Only allowed for connection oriented sockets.

+

Only allowed for connection-oriented sockets.

Specifies a longest time to wait for a send operation to be accepted by the underlying TCP stack. When the limit is - exceeded, the send operation will return - {error,timeout}. How much of a packet that actually - got sent is unknown, why the socket should be closed - whenever a timeout has occurred (see send_timeout_close). - Default is infinity.

+ exceeded, the send operation returns + {error,timeout}. How much of a packet that + got sent is unknown; the socket is therefore to be closed + whenever a time-out has occurred (see send_timeout_close + below). Defaults to infinity.

{send_timeout_close, Boolean} -

Only allowed for connection oriented sockets.

+

Only allowed for connection-oriented sockets.

Used together with send_timeout to specify whether - the socket will be automatically closed when the send operation + the socket is to be automatically closed when the send operation returns {error,timeout}. The recommended setting is - true which will automatically close the socket. - Default is false due to backward compatibility.

- + true, which automatically closes the socket. + Defaults to false because of backward compatibility.

+
- {show_econnreset, Boolean}(TCP/IP sockets) -

When this option is set to false, as it is by - default, an RST that is received from the TCP peer is treated - as a normal close (as though a FIN was sent). A caller - to gen_tcp:recv/2 - will get {error, closed}. In active - mode the controlling process will receive a +

When this option is set to false, which is + default, an RST received from the TCP peer is treated + as a normal close (as though an FIN was sent). A caller to + gen_tcp:recv/2 + gets {error, closed}. In active + mode, the controlling process receives a {tcp_close, Socket} message, indicating that the peer has closed the connection.

-

Setting this option to true will allow you to +

Setting this option to true allows you to distinguish between a connection that was closed normally, - and one which was aborted (intentionally or unintentionally) + and one that was aborted (intentionally or unintentionally) by the TCP peer. A call to - gen_tcp:recv/2 - will return {error, econnreset}. In - active mode, the controlling process will receive a + gen_tcp:recv/2 + returns {error, econnreset}. In + active mode, the controlling process receives a {tcp_error, Socket, econnreset} message before the usual {tcp_closed, Socket}, as is the case for any other socket error. Calls to - gen_tcp:send/2 - will also return {error, econnreset} when it + gen_tcp:send/2 + also returns {error, econnreset} when it is detected that a TCP peer has sent an RST.

A connected socket returned from - gen_tcp:accept/1 - will inherit the show_econnreset setting from the + gen_tcp:accept/1 + inherits the show_econnreset setting from the listening socket.

- +
- {sndbuf, Size}

The minimum size of the send buffer to use for the socket. - You are encouraged to use - inet:getopts/2, - to retrieve the actual size set by your operating system. -

+ You are encouraged to use + getopts/2, + to retrieve the size set by your operating system.

{priority, Integer} -

Sets the SO_PRIORITY socket level option on platforms where - this is implemented. The behaviour and allowed range varies on - different systems. The option is ignored on platforms where the - option is not implemented. Use with caution.

+

Sets the SO_PRIORITY socket level option on platforms + where this is implemented. The behavior and allowed range varies + between different systems. + The option is ignored on platforms where it + is not implemented. Use with caution.

{tos, Integer} -

Sets IP_TOS IP level options on platforms where this is - implemented. The behaviour and allowed range varies on different - systems. The option is ignored on platforms where the option is - not implemented. Use with caution.

+

Sets IP_TOS IP level options on platforms where this is + implemented. The behavior and allowed range varies between + different systems. + The option is ignored on platforms where it is not + implemented. Use with caution.

- -

In addition to the options mentioned above, raw +

In addition to these options, raw option specifications can be used. The raw options are - specified as a tuple of arity four, beginning with the tag - raw, followed by the protocol level, the option number - and the actual option value specified as a binary. This - corresponds to the second, third and fourth argument to the + specified as a tuple of arity four, beginning with tag + raw, followed by the protocol level, the option number, + and the option value specified as a binary. This + corresponds to the second, third, and fourth arguments to the setsockopt call in the C socket API. The option value - needs to be coded in the native endianess of the platform and, - if a structure is required, needs to follow the struct + must be coded in the native endianess of the platform and, + if a structure is required, must follow the structure alignment conventions on the specific platform.

-

Using raw socket options require detailed knowledge about +

Using raw socket options requires detailed knowledge about the current operating system and TCP stack.

-

As an example of the usage of raw options, consider a Linux - system where you want to set the TCP_LINGER2 option on - the IPPROTO_TCP protocol level in the stack. You know +

Example:

+

This example concerns the use of raw options. Consider a Linux + system where you want to set option TCP_LINGER2 on + protocol level IPPROTO_TCP in the stack. You know that on this particular system it defaults to 60 (seconds), - but you would like to lower it to 30 for a particular - socket. The TCP_LINGER2 option is not explicitly - supported by inet, but you know that the protocol level - translates to the number 6, the option number to the number 8 - and the value is to be given as a 32 bit integer. You can use - this line of code to set the option for the socket named + but you want to lower it to 30 for a particular + socket. Option TCP_LINGER2 is not explicitly + supported by inet, but you know that the protocol level + translates to number 6, the option number to number 8, + and the value is to be specified as a 32-bit integer. You can use + this code line to set the option for the socket named Sock:

>}]),]]> +inet:setopts(Sock,[{raw,6,8,<<30:32/native>>}]),]]>

As many options are silently discarded by the stack if they - are given out of range, it could be a good idea to check that - a raw option really got accepted. This code places the value - in the variable TcpLinger2:

+ are specified out of range; it can be a good idea to check that + a raw option is accepted. The following code places the value + in variable TcpLinger2:

>}]}=inet:getopts(Sock,[{raw,6,8,4}]),]]> -

Code such as the examples above is inherently non portable, - even different versions of the same OS on the same platform - may respond differently to this kind of option +{ok,[{raw,6,8,<>}]}=inet:getopts(Sock,[{raw,6,8,4}]),]]> +

Code such as these examples is inherently non-portable, + even different versions of the same OS on the same platform + can respond differently to this kind of option manipulation. Use with care.

-

Note that the default options for TCP/IP sockets can be - changed with the Kernel configuration parameters mentioned in - the beginning of this document.

+

Notice that the default options for TCP/IP sockets can be + changed with the Kernel configuration parameters mentioned in + the beginning of this manual page.

+
+
+ + + + Return the local address and port number for a socket. + + +

Returns the local address and port number for a socket.

+

Notice that for SCTP sockets this function returns only + one of the socket addresses. Function + socknames/1,2 + returns all.

+
+
+ + + + Return all local address/port numbers for a socket. + +

Equivalent to + socknames(Socket, 0). +

+
+
+ + + + Return all local address/port numbers for a socket. + +

Returns a list of all local address/port number pairs for a socket + for the specified association Assoc.

+

This function can return multiple addresses for multihomed + sockets, such as SCTP sockets. For other sockets it + returns a one-element list.

+

Notice that parameter Assoc is by the + SCTP Sockets API Extensions + defined to be ignored for one-to-one style sockets. + For one-to-many style sockets, the special value 0 + is defined to mean that the returned addresses must be + without any particular association. + How different SCTP implementations interprets this varies somewhat. +

@@ -1143,148 +1123,147 @@ setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp POSIX Error Codes - e2big - argument list too long - eacces - permission denied - eaddrinuse - address already in use - eaddrnotavail - cannot assign requested address - eadv - advertise error - eafnosupport - address family not supported by - protocol family - eagain - resource temporarily unavailable + e2big - Too long argument list + eacces - Permission denied + eaddrinuse - Address already in use + eaddrnotavail - Cannot assign requested address + eadv - Advertise error + eafnosupport - Address family not supported by + protocol family + eagain - Resource temporarily unavailable ealign - EALIGN - ealready - operation already in progress - ebade - bad exchange descriptor - ebadf - bad file number - ebadfd - file descriptor in bad state - ebadmsg - not a data message - ebadr - bad request descriptor - ebadrpc - RPC structure is bad - ebadrqc - bad request code - ebadslt - invalid slot - ebfont - bad font file format - ebusy - file busy - echild - no children - echrng - channel number out of range - ecomm - communication error on send - econnaborted - software caused connection abort - econnrefused - connection refused - econnreset - connection reset by peer - edeadlk - resource deadlock avoided - edeadlock - resource deadlock avoided - edestaddrreq - destination address required - edirty - mounting a dirty fs w/o force - edom - math argument out of range - edotdot - cross mount point - edquot - disk quota exceeded - eduppkg - duplicate package name - eexist - file already exists - efault - bad address in system call argument - efbig - file too large - ehostdown - host is down - ehostunreach - host is unreachable - eidrm - identifier removed - einit - initialization error - einprogress - operation now in progress - eintr - interrupted system call - einval - invalid argument + ealready - Operation already in progress + ebade - Bad exchange descriptor + ebadf - Bad file number + ebadfd - File descriptor in bad state + ebadmsg - Not a data message + ebadr - Bad request descriptor + ebadrpc - Bad RPC structure + ebadrqc - Bad request code + ebadslt - Invalid slot + ebfont - Bad font file format + ebusy - File busy + echild - No children + echrng - Channel number out of range + ecomm - Communication error on send + econnaborted - Software caused connection abort + econnrefused - Connection refused + econnreset - Connection reset by peer + edeadlk - Resource deadlock avoided + edeadlock - Resource deadlock avoided + edestaddrreq - Destination address required + edirty - Mounting a dirty fs without force + edom - Math argument out of range + edotdot - Cross mount point + edquot - Disk quota exceeded + eduppkg - Duplicate package name + eexist - File already exists + efault - Bad address in system call argument + efbig - File too large + ehostdown - Host is down + ehostunreach - Host is unreachable + eidrm - Identifier removed + einit - Initialization error + einprogress - Operation now in progress + eintr - Interrupted system call + einval - Invalid argument eio - I/O error - eisconn - socket is already connected - eisdir - illegal operation on a directory - eisnam - is a named file - el2hlt - level 2 halted - el2nsync - level 2 not synchronized - el3hlt - level 3 halted - el3rst - level 3 reset + eisconn - Socket is already connected + eisdir - Illegal operation on a directory + eisnam - Is a named file + el2hlt - Level 2 halted + el2nsync - Level 2 not synchronized + el3hlt - Level 3 halted + el3rst - Level 3 reset elbin - ELBIN - elibacc - cannot access a needed shared library - elibbad - accessing a corrupted shared library - elibexec - cannot exec a shared library directly - elibmax - attempting to link in more shared - libraries than system limit - elibscn - .lib section in a.out corrupted - elnrng - link number out of range - eloop - too many levels of symbolic links - emfile - too many open files - emlink - too many links - emsgsize - message too long - emultihop - multihop attempted - enametoolong - file name too long - enavail - not available + elibacc - Cannot access a needed shared library + elibbad - Accessing a corrupted shared library + elibexec - Cannot exec a shared library directly + elibmax - Attempting to link in more shared + libraries than system limit + elibscn - .lib section in a.out + corrupted + elnrng - Link number out of range + eloop - Too many levels of symbolic links + emfile - Too many open files + emlink - Too many links + emsgsize - Message too long + emultihop - Multihop attempted + enametoolong - Filename too long + enavail - Unavailable enet - ENET - enetdown - network is down - enetreset - network dropped connection on reset - enetunreach - network is unreachable - enfile - file table overflow - enoano - anode table overflow - enobufs - no buffer space available - enocsi - no CSI structure available - enodata - no data available - enodev - no such device - enoent - no such file or directory - enoexec - exec format error - enolck - no locks available - enolink - link has be severed - enomem - not enough memory - enomsg - no message of desired type - enonet - machine is not on the network - enopkg - package not installed - enoprotoopt - bad protocol option - enospc - no space left on device - enosr - out of stream resources or not a stream - device - enosym - unresolved symbol name - enosys - function not implemented - enotblk - block device required - enotconn - socket is not connected - enotdir - not a directory - enotempty - directory not empty - enotnam - not a named file - enotsock - socket operation on non-socket - enotsup - operation not supported - enotty - inappropriate device for ioctl - enotuniq - name not unique on network - enxio - no such device or address - eopnotsupp - operation not supported on socket - eperm - not owner - epfnosupport - protocol family not supported - epipe - broken pipe - eproclim - too many processes - eprocunavail - bad procedure for program - eprogmismatch - program version wrong - eprogunavail - RPC program not available - eproto - protocol error - eprotonosupport - protocol not supported - eprototype - protocol wrong type for socket - erange - math result unrepresentable + enetdown - Network is down + enetreset - Network dropped connection on reset + enetunreach - Network is unreachable + enfile - File table overflow + enoano - Anode table overflow + enobufs - No buffer space available + enocsi - No CSI structure available + enodata - No data available + enodev - No such device + enoent - No such file or directory + enoexec - Exec format error + enolck - No locks available + enolink - Link has been severed + enomem - Not enough memory + enomsg - No message of desired type + enonet - Machine is not on the network + enopkg - Package not installed + enoprotoopt - Bad protocol option + enospc - No space left on device + enosr - Out of stream resources or not a stream device + enosym - Unresolved symbol name + enosys - Function not implemented + enotblk - Block device required + enotconn - Socket is not connected + enotdir - Not a directory + enotempty - Directory not empty + enotnam - Not a named file + enotsock - Socket operation on non-socket + enotsup - Operation not supported + enotty - Inappropriate device for ioctl + enotuniq - Name not unique on network + enxio - No such device or address + eopnotsupp - Operation not supported on socket + eperm - Not owner + epfnosupport - Protocol family not supported + epipe - Broken pipe + eproclim - Too many processes + eprocunavail - Bad procedure for program + eprogmismatch - Wrong program version + eprogunavail - RPC program unavailable + eproto - Protocol error + eprotonosupport - Protocol not supported + eprototype - Wrong protocol type for socket + erange - Math result unrepresentable erefused - EREFUSED - eremchg - remote address changed - eremdev - remote device - eremote - pathname hit remote file system - eremoteio - remote i/o error + eremchg - Remote address changed + eremdev - Remote device + eremote - Pathname hit remote filesystem + eremoteio - Remote I/O error eremoterelease - EREMOTERELEASE - erofs - read-only file system - erpcmismatch - RPC version is wrong - erremote - object is remote - eshutdown - cannot send after socket shutdown - esocktnosupport - socket type not supported - espipe - invalid seek - esrch - no such process - esrmnt - srmount error - estale - stale remote file handle + erofs - Read-only filesystem + erpcmismatch - Wrong RPC version + erremote - Object is remote + eshutdown - Cannot send after socket shutdown + esocktnosupport - Socket type not supported + espipe - Invalid seek + esrch - No such process + esrmnt - Srmount error + estale - Stale remote file handle esuccess - Error 0 - etime - timer expired - etimedout - connection timed out - etoomanyrefs - too many references - etxtbsy - text file or pseudo-device busy - euclean - structure needs cleaning - eunatch - protocol driver not attached - eusers - too many users - eversion - version mismatch - ewouldblock - operation would block - exdev - cross-domain link - exfull - message tables full - nxdomain - the hostname or domain name could not be - found + etime - Timer expired + etimedout - Connection timed out + etoomanyrefs - Too many references + etxtbsy - Text file or pseudo-device busy + euclean - Structure needs cleaning + eunatch - Protocol driver not attached + eusers - Too many users + eversion - Version mismatch + ewouldblock - Operation would block + exdev - Cross-domain link + exfull - Message tables full + nxdomain - Hostname or domain name cannot be found
diff --git a/lib/kernel/doc/src/inet_res.xml b/lib/kernel/doc/src/inet_res.xml index 851a36aba9..4ada4203c0 100644 --- a/lib/kernel/doc/src/inet_res.xml +++ b/lib/kernel/doc/src/inet_res.xml @@ -11,7 +11,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software @@ -19,7 +19,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - + inet_res @@ -29,52 +29,50 @@ A inet_res - A Rudimentary DNS Client + A rudimentary DNS client. -

Performs DNS name resolving towards recursive name servers

-

See also - - ERTS User's Guide: Inet configuration - for more - information on how to configure an Erlang runtime system for IP - communication and how to enable this DNS client by defining - as a lookup method. It then acts - as a backend for the resolving functions in - inet.

+

This module performs DNS name resolving to recursive name servers.

+

See also + ERTS User's Guide: Inet Configuration + for more information about how to configure an Erlang runtime system + for IP communication, and how to enable this DNS client by defining + as a lookup method. + The DNS client then acts as a backend for the resolving functions in + inet.

This DNS client can resolve DNS records even if it is not used for normal name resolving in the node.

-

This is not a full-fledged resolver. It is just a - DNS client that relies on asking trusted recursive nameservers.

+

This is not a full-fledged resolver, only a + DNS client that relies on asking trusted recursive name servers.

Name Resolving

UDP queries are used unless resolver option usevc is true, which forces TCP queries. - If the query is to large for UDP, TCP is used instead. - For regular DNS queries 512 bytes is the size limit. - When EDNS is enabled (resolver option - edns is set to the EDNS version i.e 0 + If the query is too large for UDP, TCP is used instead. + For regular DNS queries, 512 bytes is the size limit.

+

When EDNS is enabled (resolver option + edns is set to the EDNS version (that is, 0 instead of false), resolver option - udp_payload_size sets the limit. If a nameserver - replies with the TC bit set (truncation), indicating + udp_payload_size sets the limit. If a name server + replies with the TC bit set (truncation), indicating that the answer is incomplete, the query is retried - to that nameserver using TCP. The resolver option + to that name server using TCP. Resolver option udp_payload_size also sets the advertised - size for the max allowed reply size, if EDNS is - enabled, otherwise the nameserver uses the limit - 512 byte. If the reply is larger it gets truncated, - forcing a TCP re-query.

-

For UDP queries, the resolver options timeout + size for the maximum allowed reply size, if EDNS is + enabled, otherwise the name server uses the limit + 512 bytes. If the reply is larger, it gets truncated, + forcing a TCP requery.

+

For UDP queries, resolver options timeout and retry control retransmission. - Each nameserver in the nameservers list is - tried with a timeout of timeout / retry. - Then all nameservers are tried again doubling the - timeout, for a total of retry times.

-

For queries that not use the search list, + Each name server in the nameservers list is + tried with a time-out of timeout/retry. + Then all name servers are tried again, doubling the + time-out, for a total of retry times.

+

For queries not using the search list, if the query to all nameservers results in - {error,nxdomain}or an empty answer, the same - query is tried for the alt_nameservers.

+ {error,nxdomain} or an empty answer, the same + query is tried for alt_nameservers.

@@ -92,11 +90,13 @@ +
DNS Types

The following data types concern the DNS client:

+ @@ -112,10 +112,10 @@

This is the start of a hiearchy of opaque data structures - that can be examined with access functions in inet_dns that - return lists of {Field,Value} tuples. The arity 2 functions - just return the value for a given field.

-
+          that can be examined with access functions in inet_dns, which
+          return lists of {Field,Value} tuples. The arity 2 functions
+          only return the value for a specified field.

+
 dns_msg() = DnsMsg
     inet_dns:msg(DnsMsg) ->
         [ {header, dns_header()}
@@ -163,63 +163,55 @@ dns_rr() = DnsRr
                      | {z, integer()}
                      | {data, dns_data()} ]
     inet_dns:rr(DnsRr, Field) -> Value
- -

There is an info function for the types above:

- -
+        

There is an information function for the types above:

+
 inet_dns:record_type(dns_msg()) -> msg;
 inet_dns:record_type(dns_header()) -> header;
 inet_dns:record_type(dns_query()) -> dns_query;
 inet_dns:record_type(dns_rr()) -> rr;
 inet_dns:record_type(_) -> undefined.
- -

So; inet_dns:(inet_dns:record_type(X))(X) will convert -any of these data structures into a {Field,Value} list.

+

So, inet_dns:(inet_dns:record_type(X))(X) converts + any of these data structures into a {Field,Value} list.

-

Regexp is a string with characters encoded in the - UTF-8 coding standard.

+ +

Regexp is a string with characters encoded + in the UTF-8 coding standard.

- - - Resolve a DNS record of the given type for the given host - + Resolve a DNS record of the specified type for the specified + host. -

Resolve a DNS record of the given type for the given host, - of class in. On success returns a hostent() record with - dns_data() elements in the address list field. -

- This function uses the resolver option search that +

Resolves a DNS record of the specified type for the specified host, + of class in. Returns, on success, a hostent() record + with dns_data() elements in the address list field.

+

This function uses resolver option search that is a list of domain names. If the name to resolve contains no dots, it is prepended to each domain name in the search list, and they are tried in order. If the name contains dots, it is first tried as an absolute name - and if that fails the search list is used. If the name - has a trailing dot it is simply supposed to be - an absolute name and the search list is not used. -

+ and if that fails, the search list is used. If the name + has a trailing dot, it is supposed to be + an absolute name and the search list is not used.

- Return a hostent record for the host with the given address - + Return a hostent record for the host with the specified + address.

Backend functions used by - - inet:gethostbyaddr/1 - . + inet:gethostbyaddr/1.

@@ -228,22 +220,19 @@ any of these data structures into a {Field,Value} list.

- Return a hostent record for the host with the given name + Return a hostent record for the host with the specified name.

Backend functions used by - - inet:gethostbyname/1,2 - . -

- This function uses the resolver option search just like - getbyname/2,3. -

- If the resolver option inet6 is true, - an IPv6 address is looked up, and if that fails - the IPv4 address is looked up and returned on - IPv6 mapped IPv4 format. + inet:gethostbyname/1,2.

+

This function uses resolver option search just like + getbyname/2,3. +

+

If resolver option inet6 is true, + an IPv6 address is looked up. If that fails, + the IPv4 address is looked up and returned on + IPv6-mapped IPv4 format.

@@ -251,22 +240,21 @@ any of these data structures into a {Field,Value} list.

- Resolve the DNS data for the record of the given type and class - for the given name - + Resolve the DNS data for the record of the specified type + and class for the specified name. -

Resolve the DNS data for the record of the given type and class - for the given name. On success filters out the answer records - with the correct Class and Type and returns - a list of their data fields. So a lookup for type any - will give an empty answer since the answer records have +

Resolves the DNS data for the record of the specified type and class + for the specified name. On success, filters out the answer records + with the correct Class and + Type, and returns + a list of their data fields. So, a lookup for type any + gives an empty answer, as the answer records have specific types that are not any. An empty answer - as well as a failed lookup returns an empty list. -

- Calls resolve/2..4 + or a failed lookup returns an empty list.

+

Calls + resolve/* with the same arguments and filters the result, so - Opts is explained there. -

+ Opts is described for those functions.

@@ -274,90 +262,77 @@ any of these data structures into a {Field,Value} list.

- Resolve a DNS record of the given type and class - for the given name - + Resolve a DNS record of the specified type and class + for the specified name. -

Resolve a DNS record of the given type and class for the given name. - The returned dns_msg() can be examined using - access functions in inet_db as described - in DNS Types. -

- If Name is an ip_address(), the domain name - to query for is generated as the standard reverse - ".IN-ADDR.ARPA." name for an IPv4 address, or the - ".IP6.ARPA." name for an IPv6 address. - In this case you most probably want to use - Class = in and Type = ptr but it - is not done automatically. -

- Opts override the corresponding resolver options. - If the option nameservers is given, it is - also assumed that it is the complete list of nameserves, - so the resolver option alt_nameserves is ignored. - Of course, if that option is also given to this function, - it is used. -

- The verbose option (or rather {verbose,true}), +

Resolves a DNS record of the specified type and class for the + specified name. The returned dns_msg() can be examined using + access functions in inet_db, as described in section + in DNS Types.

+

If Name is an ip_address(), the domain + name to query for is generated as the standard reverse + ".IN-ADDR.ARPA." name for an IPv4 address, or the + ".IP6.ARPA." name for an IPv6 address. + In this case, you most probably want to use + Class = in and Type = ptr, + but it is not done automatically.

+

Opts overrides the corresponding resolver + options. If option nameservers is specified, it is + assumed that it is the complete list of name serves, + so resolver option alt_nameserves is ignored. + However, if option alt_nameserves is also specified to this + function, it is used.

+

Option verbose (or rather {verbose,true}) causes diagnostics printout through - io:format/2 - of queries, replies retransmissions, etc, similar - to from utilities like dig, nslookup et.al. -

- If Opt is an arbitrary atom it is interpreted + io:format/2 + of queries, replies retransmissions, and so on, similar + to from utilities, such as dig and nslookup.

+

If Opt is any atom, it is interpreted as {Opt,true} unless the atom string starts with - "no" making the interpretation {Opt,false}. - For example: usevc is an alias for {usevc,true}, - and nousevc an alias for {usevc,false}. -

- The inet6 option currently has no effect on this function. - You probably want to use Type = a | aaaa instead. -

+ "no", making the + interpretation {Opt,false}. + For example, usevc is an alias for {usevc,true} + and nousevc is an alias for {usevc,false}.

+

Option inet6 has no effect on this function. You + probably want to use Type = a | aaaa instead.

-
- -
- Examples -

Access functions example: how - lookup/3 - could have been implemented using - resolve/3 - from outside the module. -

- example_lookup(Name, Class, Type) -> - case inet_res:resolve(Name, Class, Type) of - {ok,Msg} -> - [inet_dns:rr(RR, data) - || RR <- inet_dns:msg(Msg, anlist), - inet_dns:rr(RR, type) =:= Type, - inet_dns:rr(RR, class) =:= Class]; - {error,_} -> - [] - end. + Example +

This access functions example shows how + lookup/3 + can be implemented using + resolve/3 + from outside the module:

+ +example_lookup(Name, Class, Type) -> + case inet_res:resolve(Name, Class, Type) of + {ok,Msg} -> + [inet_dns:rr(RR, data) + || RR <- inet_dns:msg(Msg, anlist), + inet_dns:rr(RR, type) =:= Type, + inet_dns:rr(RR, class) =:= Class]; + {error,_} -> + [] + end.
- -
Legacy Functions -

These have been deprecated due to the annoying double - meaning of the nameservers/timeout argument, and - because they had no decent place for a resolver options list.

+

These are deprecated because the annoying double + meaning of the name servers/time-out argument, and + because they have no decent place for a resolver options list.

- - Resolve a DNS record of the given type and class - for the given name - + Resolve a DNS record of the specified type and class for the + specified name. @@ -365,23 +340,20 @@ any of these data structures into a {Field,Value} list.

-

Resolve a DNS record of the given type and class for the given name. -

+

Resolves a DNS record of the specified type and class for the + specified name.

- Resolve a DNS record of the given type and class - for the given name - + Resolve a DNS record of the specified type and class + for the specified name. -

Resolve a DNS record of the given type and class for the given name. -

+

Resolves a DNS record of the specified type and class for the + specified name.

-
- diff --git a/lib/kernel/doc/src/init_stub.xml b/lib/kernel/doc/src/init_stub.xml index eae2cbea95..de00fb8dd7 100644 --- a/lib/kernel/doc/src/init_stub.xml +++ b/lib/kernel/doc/src/init_stub.xml @@ -31,13 +31,9 @@ A init - Coordination of System Startup -

- - The module init is moved to the runtime system - application. Please see init(3) in the - erts reference manual instead. - -

+ Coordination of system startup. + +

This module is moved to the + ERTS application.

+
diff --git a/lib/kernel/doc/src/kernel_app.xml b/lib/kernel/doc/src/kernel_app.xml index 956c57f7c1..9e6fb60bb7 100644 --- a/lib/kernel/doc/src/kernel_app.xml +++ b/lib/kernel/doc/src/kernel_app.xml @@ -4,7 +4,7 @@
- 19962015 + 19962016 Ericsson AB. All Rights Reserved. @@ -29,66 +29,59 @@
kernel - The Kernel Application + The Kernel application. -

The Kernel application is the first application started. It is +

The Kernel application has all the code necessary to run + the Erlang runtime system: file servers, code servers, + and so on.

+

The Kernel application is the first application started. It is mandatory in the sense that the minimal system based on - Erlang/OTP consists of Kernel and STDLIB. The Kernel application - contains the following services:

+ Erlang/OTP consists of Kernel and STDLIB. Kernel + contains the following functional areas:

- application controller, see application(3) - code - disk_log - dist_ac, distributed application controller - erl_boot_server - erl_ddll - error_logger - error_logger_format_depth - file - global - global_group - heart - inet - net_kernel - os - pg2 - rpc - seq_trace - user + Start, stop, supervision, configuration, and distribution of applications + Code loading + Logging + Error logging + Global name service + Supervision of Erlang/OTP + Communication with sockets + Operating system interface
Error Logger Event Handlers

Two standard error logger event handlers are defined in - the Kernel application. These are described in - error_logger(3).

+ the Kernel application. These are described in + error_logger(3).

Configuration -

The following configuration parameters are defined for the Kernel - application. See app(4) for more - information about configuration parameters.

+

The following configuration parameters are defined for the Kernel + application. For more information about configuration parameters, + see file app(4).

browser_cmd = string() | {M,F,A} -

When pressing the Help button in a tool such as Debugger or - TV, the help text (an HTML file File) is by default - displayed in a Netscape browser which is required to be up and - running. This parameter can be used to change the command for +

When pressing the Help button in a tool such as Debugger, + the help text (an HTML file File) is by default + displayed in a Netscape browser, which is required to be + operational. This parameter can be used to change the command for how to display the help text if another browser than Netscape - is preferred, or another platform than Unix or Windows is + is preferred, or if another platform than Unix or Windows is used.

If set to a string Command, the command - "Command File" will be evaluated using os:cmd/1.

-

If set to a module-function-args tuple {M,F,A}, - the call apply(M,F,[File|A]) will be evaluated.

+ "Command File" is evaluated using + os:cmd/1.

+

If set to a module-function-args tuple, {M,F,A}, + the call apply(M,F,[File|A]) is evaluated.

distributed = [Distrib] -

Specifies which applications are distributed and on which - nodes they may execute. In this parameter:

+

Specifies which applications that are distributed and on which + nodes they are allowed to execute. In this parameter:

Distrib = {App,Nodes} | {App,Time,Nodes} App = atom() @@ -96,25 +89,24 @@ Nodes = [node() | {node(),...,node()}]

The parameter is described in - application(3), function - load/2.

+ application:load/2.

dist_auto_connect = Value -

Specifies when nodes will be automatically connected. If +

Specifies when nodes are automatically connected. If this parameter is not specified, a node is always - automatically connected, e.g when a message is to be sent to + automatically connected, for example, when a message is to be sent to that node. Value is one of:

never - Connections are never automatically established, they +

Connections are never automatically established, they must be explicitly connected. See - net_kernel(3). + net_kernel(3).

once - Connections will be established automatically, but only +

Connections are established automatically, but only once per node. If a node goes down, it must thereafter be explicitly connected. See - net_kernel(3). + net_kernel(3).

permissions = [Perm] @@ -127,25 +119,24 @@ Bool = boolean()

Permissions are described in - application(3), function - permit/2.

+ application:permit/2.

error_logger = Value

Value is one of:

tty - Installs the standard event handler which prints error - reports to stdio. This is the default option. +

Installs the standard event handler, which prints error + reports to stdio. This is the default option.

{file, FileName} - Installs the standard event handler which prints error - reports to the file FileName, where FileName - is a string. +

Installs the standard event handler, which prints error + reports to file FileName, where FileName + is a string.

false

No standard event handler is installed, but the initial, primitive event handler is kept, printing - raw event messages to tty.

+ raw event messages to tty.

silent @@ -156,111 +147,110 @@ error_logger_format_depth = Depth -

This parameter can be used to limit the size of the +

Can be used to limit the size of the formatted output from the error logger event handlers.

-

This configuration parameter was introduced in OTP 18.1. - It is currently experimental. Based on user feedback it - may be changed or improved in future releases, for example +

This configuration parameter was introduced in OTP 18.1 + and is experimental. Based on user feedback, it + can be changed or improved in future releases, for example, to gain better control over how to limit the size of the - formatted output. We have no plans to entirely remove this - new feature, unless it turns out to be completely - useless. In OTP 19, the default may be changed to limit the - formatted output.

+ formatted output. We have no plans to remove this + new feature entirely, unless it turns out to be + useless.

-

Depth is a positive integer that is the maximum +

Depth is a positive integer representing the maximum depth to which terms are printed by the error logger event - handlers included in OTP. Specifically, the two event handlers + handlers included in OTP. This + configuration parameter is used by the two event handlers defined by the Kernel application and the two event - handlers in the SASL application will use this - configuration parameter. (If you have implemented you own - error handlers, this configuration parameter will have no - effect on them.)

+ handlers in the SASL application. + (If you have implemented your own error handlers, this configuration + parameter has no effect on them.)

-

The way Depth is used, is that format strings - string passed to the event handlers will be rewritten. - The "~p" and "~w" format controls will be replaced with - "~P" and "~W", respectively, and Depth will be - used as the depth parameter. See - io:format/2.

+

Depth is used as follows: Format strings + passed to the event handlers are rewritten. + The format controls ~p and ~w are replaced with + ~P and ~W, respectively, and Depth is + used as the depth parameter. For details, see + io:format/2 + in STDLIB.

A reasonable starting value for Depth is - 30. You should test crashing various processes in your - application and examine the logs from the crashes, and then - either increase or decrease the value.

+ 30. We recommend to test crashing various processes in your + application, examine the logs from the crashes, and then + increase or decrease the value.

global_groups = [GroupTuple] +

Defines global groups, see - global_group(3).

+ global_group(3). + In this parameter:

- GroupTuple = {GroupName, [Node]} | {GroupName, PublishType, [Node]} - GroupName = atom() - PublishType = normal | hidden - Node = node() +

GroupTuple = {GroupName, [Node]} | {GroupName, PublishType, [Node]}

+

GroupName = atom()

+

PublishType = normal | hidden

+

Node = node()

inet_default_connect_options = [{Opt, Val}]

Specifies default options for connect sockets, - see inet(3).

+ see inet(3).

inet_default_listen_options = [{Opt, Val}]

Specifies default options for listen (and - accept) sockets, see inet(3).

+ accept) sockets, see inet(3).

{inet_dist_use_interface, ip_address()} -

If the host of an Erlang node has several network interfaces, - this parameter specifies which one to listen on. See - inet(3) for the type definition - of ip_address().

+

If the host of an Erlang node has many network interfaces, + this parameter specifies which one to listen on. For the type definition + of ip_address(), + see inet(3).

- {inet_dist_listen_min, First} + {inet_dist_listen_min, First} and {inet_dist_listen_max, Last} -

See below.

-
- {inet_dist_listen_max, Last} - -

Define the First..Last port range for the listener +

Defines the First..Last port range for the listener socket of a distributed Erlang node.

{inet_dist_listen_options, Opts} -

Define a list of extra socket options to be used when opening the +

Defines a list of extra socket options to be used when opening the listening socket for a distributed Erlang node. - See gen_tcp:listen/2

+ See gen_tcp:listen/2.

{inet_dist_connect_options, Opts} -

Define a list of extra socket options to be used when connecting to +

Defines a list of extra socket options to be used when connecting to other distributed Erlang nodes. - See gen_tcp:connect/4

+ See gen_tcp:connect/4.

inet_parse_error_log = silent -

If this configuration parameter is set, no +

If set, no error_logger messages are generated when erroneous lines are found and skipped in the various Inet configuration files.

inetrc = Filename -

The name (string) of an Inet user configuration file. See - ERTS User's Guide, Inet configuration.

+

The name (string) of an Inet user configuration file. For details, + see section + Inet Configuration + in the ERTS User's Guide.

net_setuptime = SetupTime

SetupTime must be a positive integer or floating point - number, and will be interpreted as the maximally allowed time + number, and is interpreted as the maximum allowed time for each network operation during connection setup to another - Erlang node. The maximum allowed value is 120; if higher values - are given, 120 will be used. The default value if the variable - is not given, or if the value is incorrect (e.g. not a number), - is 7 seconds.

-

Note that this value does not limit the total connection + Erlang node. The maximum allowed value is 120. If higher values + are specified, 120 is used. Default is 7 seconds if the variable + is not specified, or if the value is incorrect (for example, not a number).

+

Notice that this value does not limit the total connection setup time, but rather each individual network operation during the connection setup and handshake.

@@ -268,45 +258,44 @@

Specifies the net_kernel tick time. TickTime - is given in seconds. Once every TickTime/4 second, all - connected nodes are ticked (if anything else has been written - to a node) and if nothing has been received from another node - within the last four (4) tick times that node is considered - to be down. This ensures that nodes which are not responding, + is specified in seconds. Once every TickTime/4 second, all + connected nodes are ticked (if anything else is written + to a node). If nothing is received from another node + within the last four tick times, that node is considered + to be down. This ensures that nodes that are not responding, for reasons such as hardware errors, are considered to be down.

The time T, in which a node that is not responding is - detected, is calculated as: where:

+ detected, is calculated as , where:

MinT = TickTime - TickTime / 4 MaxT = TickTime + TickTime / 4 -

TickTime is by default 60 (seconds). Thus, +

TickTime defaults to 60 (seconds). Thus, seconds.

-

Note: All communicating nodes should have the same +

Notice that all communicating nodes are to have the same TickTime value specified.

-

Note: Normally, a terminating node is detected - immediately.

+

Normally, a terminating node is detected immediately.

shutdown_timeout = integer() | infinity -

Specifies the time application_controller will wait +

Specifies the time application_controller waits for an application to terminate during node shutdown. If the - timer expires, application_controller will brutally - kill application_master of the hanging + timer expires, application_controller brutally + kills application_master of the hanging application. If this parameter is undefined, it defaults to infinity.

sync_nodes_mandatory = [NodeName] -

Specifies which other nodes must be alive in order +

Specifies which other nodes that must be alive for this node to start properly. If some node in the list - does not start within the specified time, this node will not + does not start within the specified time, this node does not start either. If this parameter is undefined, it defaults to - [].

+ [].

sync_nodes_optional = [NodeName] -

Specifies which other nodes can be alive in order +

Specifies which other nodes that can be alive for this node to start properly. If some node in this list does not start within the specified time, this node starts anyway. If this parameter is undefined, it defaults to @@ -314,66 +303,65 @@ MaxT = TickTime + TickTime / 4 sync_nodes_timeout = integer() | infinity -

Specifies the amount of time (in milliseconds) this node - will wait for the mandatory and optional nodes to start. If +

Specifies the time (in milliseconds) that this node + waits for the mandatory and optional nodes to start. If this parameter is undefined, no node synchronization is - performed. This option also makes sure that global is + performed. This option ensures that global is synchronized.

start_dist_ac = true | false

Starts the dist_ac server if the parameter is - true. This parameter should be set to true for - systems that use distributed applications.

-

The default value is false. If this parameter is - undefined, the server is started if the parameter + true. This parameter is to be set to true for + systems using distributed applications.

+

Defaults to false. If this parameter is + undefined, the server is started if parameter distributed is set.

start_boot_server = true | false

Starts the boot_server if the parameter is true - (see erl_boot_server(3)). - This parameter should be - set to true in an embedded system which uses this - service.

-

The default value is false.

+ (see erl_boot_server(3)). + This parameter is to be set to true in an embedded system + using this service.

+

Defaults to false.

boot_server_slaves = [SlaveIP] -

If the start_boot_server configuration parameter is +

If configuration parameter start_boot_server is true, this parameter can be used to initialize - boot_server with a list of slave IP addresses. - SlaveIP = string() | atom | {integer(),integer(),integer(),integer()}

+ boot_server with a list of slave IP addresses:

+

+ SlaveIP = string() | atom | {integer(),integer(),integer(),integer()},

where .

-

Examples of SlaveIP in atom, string and tuple form - are:

-'150.236.16.70', "150,236,16,70", {150,236,16,70}.

-

The default value is [].

+

Examples of SlaveIP in atom, string, and tuple form:

+

'150.236.16.70', "150,236,16,70", {150,236,16,70}.

+

Defaults to [].

start_disk_log = true | false

Starts the disk_log_server if the parameter is - true (see disk_log(3)). - This parameter should be - set to true in an embedded system which uses this service.

-

The default value is false.

+ true (see disk_log(3)). + This parameter is to be set to true in an embedded system + using this service.

+

Defaults to false.

start_pg2 = true | false +

Starts the pg2 server (see - pg2(3)) if - the parameter is true. This parameter should be set to - true in an embedded system which uses this service.

-

The default value is false.

+ pg2(3)) if + the parameter is true. This parameter is to be set to + true in an embedded system that uses this service.

+

Defaults to false.

start_timer = true | false

Starts the timer_server if the parameter is - true (see timer(3)). - This parameter should be - set to true in an embedded system which uses this - service.

-

The default value is false.

+ true (see stdlib:timer(3)). + This parameter is to be set to true in an embedded system + using this service.

+

Defaults to false.

shutdown_func = {Mod, Func} @@ -383,7 +371,7 @@ MaxT = TickTime + TickTime / 4 Func = atom()

Sets a function that application_controller calls - when it starts to terminate. The function is called as: + when it starts to terminate. The function is called as Mod:Func(Reason), where Reason is the terminate reason for application_controller, and it must return as soon as possible for application_controller @@ -394,25 +382,25 @@ MaxT = TickTime + TickTime / 4

See Also -

app(4), - application(3), - code(3), - disk_log(3), - erl_boot_server(3), - erl_ddll(3), - error_logger(3), - file(3), - global(3), - global_group(3), - heart(3), - inet(3), - net_kernel(3), - os(3), - pg2(3), - rpc(3), - seq_trace(3), - timer(3), - user(3)

+

app(4), + application(3), + code(3), + disk_log(3), + erl_boot_server(3), + erl_ddll(3), + error_logger(3), + file(3), + global(3), + global_group(3), + heart(3), + inet(3), + net_kernel(3), + os(3), + pg2(3), + rpc(3), + seq_trace(3), + user(3), + timer(3)

diff --git a/lib/kernel/doc/src/net_adm.xml b/lib/kernel/doc/src/net_adm.xml index 4ef9d361f6..e97c8fad11 100644 --- a/lib/kernel/doc/src/net_adm.xml +++ b/lib/kernel/doc/src/net_adm.xml @@ -25,95 +25,105 @@ net_adm Claes Wikstrom 1 - 96-09-10 + 1996-09-10 A net_adm - Various Erlang Net Administration Routines + Various Erlang net administration routines.

This module contains various network utility functions.

+ - Official name of a host + Official name of a host.

Returns the official name of Host, or {error, Host} if no such name is found. See also - inet(3).

+ inet(3).

+ - Read the .hosts.erlangfile + Read file .hosts.erlang. -

Reads the .hosts.erlang file, see the section - Files below. Returns the hosts in this file as a - list, or returns {error, Reason} if the file could not - be read or the Erlang terms on the file could not be interpreted.

+

Reads file .hosts.erlang, see section + Files. Returns the hosts in this + file as a list. Returns {error, Reason} if the + file cannot be read or the Erlang terms on the file cannot be + interpreted.

+ - Name of the local host + Name of the local host.

Returns the name of the local host. If Erlang was started - with the -name command line flag, Name is + with command-line flag -name, Name is the fully qualified name.

+ - Names of Erlang nodes at a host + Names of Erlang nodes at a host. -

Similar to epmd -names, see epmd(1). - Host defaults to the local host. Returns the names and - associated port numbers of the Erlang nodes that epmd - at the specified host has registered.

-

Returns {error, address} if epmd is not - running.

+

Similar to epmd -names, see + erts:epmd(1). + Host defaults to the local host. Returns the + names and associated port numbers of the Erlang nodes that + epmd registered at the specified host. Returns + {error, address} if epmd is not operational.

+

Example:

 (arne@dunn)1> net_adm:names().
 {ok,[{"arne",40262}]}
+ - Set up a connection to a node + Set up a connection to a node. -

Tries to set up a connection to Node. Returns - pang if it fails, or pong if it is successful.

+

Sets up a connection to Node. Returns + pong if it is successful, otherwise pang.

+ - Lookup and connect to all nodes at all hosts in .hosts.erlang + Lookup and connect to all nodes at all hosts in + .hosts.erlang. -

This function calls names(Host) for all hosts which +

Calls names(Host) for all hosts that are specified in the Erlang host file .hosts.erlang, - collects the replies and then evaluates ping(Node) on - all those nodes. Returns the list of all nodes that were, - successfully pinged.

+ collects the replies, and then evaluates ping(Node) on + all those nodes. Returns the list of all nodes that are + successfully pinged.

Arg defaults to silent. - If Arg == verbose, the function writes information about which - nodes it is pinging to stdout.

+ If Arg == verbose, the function writes + information about which nodes it is pinging to stdout.

This function can be useful when a node is started, and - the names of the other nodes in the network are not initially - known.

-

Failure: {error, Reason} if host_file() + the names of the other network nodes are not initially known.

+

Returns {error, Reason} if host_file() returns {error, Reason}.

+ - Lookup and connect to all nodes at specified hosts + Lookup and connect to all nodes at specified hosts. -

As world/0,1, but the hosts are given as argument +

Same as world/0,1, + but the hosts are specified as argument instead of being read from .hosts.erlang.

@@ -121,13 +131,14 @@
Files -

The .hosts.erlang file consists of a number of host names + +

File .hosts.erlang consists of a number of host names written as Erlang terms. It is looked for in the current work directory, the user's home directory, and $OTP_ROOT (the root directory of Erlang/OTP), in that order.

-

The format of the .hosts.erlang file must be one host - name per line. The host names must be within quotes as shown in - the following example:

+

The format of file .hosts.erlang must be one host + name per line. The host names must be within quotes.

+

Example:

 'super.eua.ericsson.se'.
 'renat.eua.ericsson.se'.
diff --git a/lib/kernel/doc/src/net_kernel.xml b/lib/kernel/doc/src/net_kernel.xml
index 311e0d8ea4..2d52adc2eb 100644
--- a/lib/kernel/doc/src/net_kernel.xml
+++ b/lib/kernel/doc/src/net_kernel.xml
@@ -25,41 +25,47 @@
     net_kernel
     Claes Wikstrom
     1
-    96-09-10
+    1996-09-10
     A
   
   net_kernel
-  Erlang Networking Kernel
+  Erlang networking kernel.
   
     

The net kernel is a system process, registered as - net_kernel, which must be running for distributed Erlang + net_kernel, which must be operational for distributed Erlang to work. The purpose of this process is to implement parts of the BIFs spawn/4 and spawn_link/4, and to provide monitoring of the network.

-

An Erlang node is started using the command line flag +

An Erlang node is started using command-line flag -name or -sname:

-
$ erl -sname foobar
+
+$ erl -sname foobar

It is also possible to call net_kernel:start([foobar]) directly from the normal Erlang shell prompt:

-
1> net_kernel:start([foobar, shortnames]).
+    
+1> net_kernel:start([foobar, shortnames]).
 {ok,<0.64.0>}
 (foobar@gringotts)2>
-

If the node is started with the command line flag -sname, - the node name will be foobar@Host, where Host is +

If the node is started with command-line flag -sname, + the node name is foobar@Host, where Host is the short name of the host (not the fully qualified domain name). - If started with the -name flag, Host is the fully - qualified domain name. See erl(1).

+ If started with flag -name, the node name is foobar@Host, + where Host is the fully qualified domain name. + For more information, see + erl.

Normally, connections are established automatically when another node is referenced. This functionality can be disabled - by setting the Kernel configuration parameter + by setting Kernel configuration parameter dist_auto_connect to false, see - kernel(6). In this case, + kernel(6). In this case, connections must be established explicitly by calling - net_kernel:connect_node/1.

-

Which nodes are allowed to communicate with each other is handled - by the magic cookie system, see - Distributed Erlang in the Erlang Reference Manual.

+ connect_node/1.

+

Which nodes that are allowed to communicate with each other is handled + by the magic cookie system, see section + Distributed Erlang + in the Erlang Reference Manual.

+ @@ -77,237 +83,240 @@ an atom.

+ - Establish a connection to a node + Establish a connection to a node. -

Establishes a connection to Node. Returns true - if successful, false if not, and ignored if - the local node is not alive.

+

Establishes a connection to Node. Returns + true if successful, false if not, and ignored + if the local node is not alive.

+
+
+ + + + Get net_ticktime. + +

Gets net_ticktime (see + kernel(6)).

+

Defined return values (Res):

+ + NetTicktime +

net_ticktime is NetTicktime + seconds.

+ {ongoing_change_to, NetTicktime} +

net_kernel is currently changing + net_ticktime to NetTicktime + seconds.

+ ignored +

The local node is not alive.

+
+ - Subscribe to node status change messages + Subscribe to node status change messages.

The calling process subscribes or unsubscribes to node status change messages. A nodeup message is delivered - to all subscribing process when a new node is connected, and + to all subscribing processes when a new node is connected, and a nodedown message is delivered when a node is disconnected.

-

If Flag is true, a new subscription is started. - If Flag is false, all previous subscriptions -- - started with the same Options -- are stopped. Two +

If Flag is true, a new subscription is + started. If Flag is false, all previous + subscriptions started with the same Options + are stopped. Two option lists are considered the same if they contain the same set of options.

-

As of kernel version 2.11.4, and erts version +

As from Kernel version 2.11.4, and ERTS version 5.5.4, the following is guaranteed:

- nodeup messages will be delivered before delivery - of any message from the remote node passed through the - newly established connection. - nodedown messages will not be delivered until all - messages from the remote node that have been passed - through the connection have been delivered. +

nodeup messages are delivered before delivery + of any message from the remote node passed through the + newly established connection.

+

nodedown messages are not delivered until all + messages from the remote node that have been passed + through the connection have been delivered.

-

Note, that this is not guaranteed for kernel +

Notice that this is not guaranteed for Kernel versions before 2.11.4.

-

As of kernel version 2.11.4 subscriptions can also be - made before the net_kernel server has been started, - i.e., net_kernel:monitor_nodes/[1,2] does not return +

As from Kernel version 2.11.4, subscriptions can also be + made before the net_kernel server is started, that is, + net_kernel:monitor_nodes/[1,2] does not return ignored.

-

As of kernel version 2.13, and erts version +

As from Kernel version 2.13, and ERTS version 5.7, the following is guaranteed:

- nodeup messages will be delivered after the - corresponding node appears in results from - erlang:nodes/X. - nodedown messages will be delivered after the - corresponding node has disappeared in results from - erlang:nodes/X. +

nodeup messages are delivered after the + corresponding node appears in results from + erlang:nodes/X.

+

nodedown messages are delivered after the + corresponding node has disappeared in results from + erlang:nodes/X.

-

Note, that this is not guaranteed for kernel +

Notice that this is not guaranteed for Kernel versions before 2.13.

The format of the node status change messages depends on - Options. If Options is [], which is the default, - the format is:

+ Options. If Options is + [], which is the default, the format is as follows:

{nodeup, Node} | {nodedown, Node} Node = node() -

If Options /= [], the format is:

+

If Options is not [], the format is + as follows:

{nodeup, Node, InfoList} | {nodedown, Node, InfoList} Node = node() InfoList = [{Tag, Val}]

InfoList is a list of tuples. Its contents depends on Options, see below.

-

Also, when OptionList == [] only visible nodes, that +

Also, when OptionList == [], only visible nodes, that is, nodes that appear in the result of - nodes/0, are - monitored.

+ erlang:nodes/0, + are monitored.

Option can be any of the following:

{node_type, NodeType} -

Currently valid values for NodeType are:

+

Valid values for NodeType:

visible - Subscribe to node status change messages for visible +

Subscribe to node status change messages for visible nodes only. The tuple {node_type, visible} is - included in InfoList. + included in InfoList.

hidden - Subscribe to node status change messages for hidden +

Subscribe to node status change messages for hidden nodes only. The tuple {node_type, hidden} is - included in InfoList. + included in InfoList.

all - Subscribe to node status change messages for both +

Subscribe to node status change messages for both visible and hidden nodes. The tuple - {node_type, visible | hidden} is included in - InfoList. + {node_type, visible | hidden} is included in + InfoList.

nodedown_reason

The tuple {nodedown_reason, Reason} is included in - InfoList in nodedown messages. Reason - can be:

+ InfoList in nodedown messages.

+

Reason can be any of the following:

connection_setup_failed - The connection setup failed (after nodeup - messages had been sent). +

The connection setup failed (after nodeup + messages were sent).

no_network - No network available. +

No network is available.

net_kernel_terminated - The net_kernel process terminated. +

The net_kernel process terminated.

shutdown - Unspecified connection shutdown. +

Unspecified connection shutdown.

connection_closed - The connection was closed. +

The connection was closed.

disconnect - The connection was disconnected (forced from the - current node). +

The connection was disconnected (forced from the + current node).

net_tick_timeout - Net tick timeout. +

Net tick time-out.

send_net_tick_failed - Failed to send net tick over the connection. +

Failed to send net tick over the connection.

get_status_failed - Status information retrieval from the Port - holding the connection failed. +

Status information retrieval from the Port + holding the connection failed.

- - - Get net_ticktime - -

Gets net_ticktime (see - kernel(6)).

-

Currently defined return values (Res):

- - NetTicktime - -

net_ticktime is NetTicktime seconds.

-
- {ongoing_change_to, NetTicktime} - -

net_kernel is currently changing - net_ticktime to NetTicktime seconds.

-
- ignored - -

The local node is not alive.

-
-
-
-
+ - Set net_ticktime + Set net_ticktime.

Sets net_ticktime (see - kernel(6)) to - NetTicktime seconds. TransitionPeriod defaults - to 60.

+ kernel(6)) to + NetTicktime seconds. + TransitionPeriod defaults to 60.

Some definitions:

- The minimum transition traffic interval (MTTI) - -

minimum(NetTicktime, PreviousNetTicktime)*1000 div 4 milliseconds.

-
- The transition period - -

The time of the least number of consecutive MTTIs - to cover TransitionPeriod seconds following - the call to set_net_ticktime/2 (i.e. - ((TransitionPeriod*1000 - 1) div MTTI + 1)*MTTI - milliseconds).

-
+ Minimum transition traffic interval (MTTI) +

minimum(NetTicktime, + PreviousNetTicktime)*1000 div 4 milliseconds.

+ Transition period +

The time of the least number of consecutive MTTIs + to cover TransitionPeriod seconds following + the call to set_net_ticktime/2 (that is, + ((TransitionPeriod*1000 - 1) div MTTI + 1)*MTTI + milliseconds).

-

If NetTicktime < PreviousNetTicktime]]>, the actual - net_ticktime change will be done at the end of - the transition period; otherwise, at the beginning. During - the transition period, net_kernel will ensure that - there will be outgoing traffic on all connections at least +

If + , + the net_ticktime change is done at the end of + the transition period; otherwise at the beginning. During + the transition period, net_kernel ensures that + there is outgoing traffic on all connections at least every MTTI millisecond.

-

The net_ticktime changes have to be initiated on all +

The net_ticktime changes must be initiated on all nodes in the network (with the same NetTicktime) before the end of any transition period on any node; - otherwise, connections may erroneously be disconnected.

+ otherwise connections can erroneously be disconnected.

Returns one of the following:

unchanged -

net_ticktime already had the value of - NetTicktime and was left unchanged.

+

net_ticktime already has the value of + NetTicktime and is left unchanged.

change_initiated -

net_kernel has initiated the change of - net_ticktime to NetTicktime seconds.

+

net_kernel initiated the change of + net_ticktime to NetTicktime + seconds.

{ongoing_change_to, NewNetTicktime} -

The request was ignored; because, - net_kernel was busy changing net_ticktime to +

The request is ignored because + net_kernel is busy changing net_ticktime to NewNetTicktime seconds.

+ start([Name]) -> {ok, pid()} | {error, Reason} start([Name, NameType]) -> {ok, pid()} | {error, Reason} start([Name, NameType, Ticktime]) -> {ok, pid()} | {error, Reason} - Turn an Erlang runtime system into a distributed node + Turn an Erlang runtime system into a distributed node. Name = atom() NameType = shortnames | longnames Reason = {already_started, pid()} | term() -

Note that the argument is a list with exactly one, two or - three arguments. NameType defaults to longnames - and Ticktime to 15000.

Turns a non-distributed node into a distributed node by starting net_kernel and other necessary processes.

+

Notice that the argument is a list with exactly one, two, or + three arguments. NameType defaults to longnames + and Ticktime to 15000.

+ - Turn a node into a non-distributed Erlang runtime system + Turn a node into a non-distributed Erlang runtime system.

Turns a distributed node into a non-distributed node. For other nodes in the network, this is the same as the node - going down. Only possible when the net kernel was started - using start/1, otherwise returns - {error, not_allowed}. Returns {error, not_found} - if the local node is not alive.

+ going down. Only possible when the net kernel was started using + start/1, + otherwise {error, not_allowed} is returned. Returns + {error, not_found} if the local node is not alive.

diff --git a/lib/kernel/doc/src/os.xml b/lib/kernel/doc/src/os.xml index 165160a909..2427aabcd5 100644 --- a/lib/kernel/doc/src/os.xml +++ b/lib/kernel/doc/src/os.xml @@ -29,98 +29,107 @@ os - Operating System Specific Functions + Operating system-specific functions. -

The functions in this module are operating system specific. - Careless use of these functions will result in programs that will +

The functions in this module are operating system-specific. + Careless use of these functions results in programs that will only run on a specific platform. On the other hand, with careful - use these functions can be of help in enabling a program to run on + use, these functions can be of help in enabling a program to run on most platforms.

- Execute a command in a shell of the target OS + Execute a command in a shell of the target OS. -

Executes Command in a command shell of the target OS, - captures the standard output of the command and returns this +

Executes Command in a command shell of the + target OS, + captures the standard output of the command, and returns this result as a string. This function is a replacement of - the previous unix:cmd/1; on a Unix platform they are - equivalent.

-

Examples:

+ the previous function unix:cmd/1; they are equivalent on a + Unix platform.

+

Examples:

LsOut = os:cmd("ls"), % on unix platform DirOut = os:cmd("dir"), % on Win32 platform -

Note that in some cases, standard output of a command when +

Notice that in some cases, standard output of a command when called from another program (for example, os:cmd/1) - may differ, compared to the standard output of the command + can differ, compared with the standard output of the command when called directly from an OS command shell.

+ - Absolute filename of a program + Absolute filename of a program. -

These two functions look up an executable program given its - name and a search path, in the same way as the underlying - operating system. find_executable/1 uses the current - execution path (that is, the environment variable PATH on +

These two functions look up an executable program, with the + specified name and a search path, in the same way as the underlying + OS. find_executable/1 uses the current + execution path (that is, the environment variable PATH on Unix and Windows).

-

Path, if given, should conform to the syntax of - execution paths on the operating system. The absolute - filename of the executable program Name is returned, - or false if the program was not found.

+

Path, if specified, is to conform to the syntax + of execution paths on the OS. Returns the absolute filename of the + executable program Name, + or false if the program is not found.

+ - List all environment variables + List all environment variables.

Returns a list of all environment variables. - Each environment variable is given as a single string on + Each environment variable is expressed as a single string on the format "VarName=Value", where VarName is the name of the variable and Value its value.

-

If Unicode file name encoding is in effect (see the erl manual - page), the strings may contain characters with - codepoints > 255.

+

If Unicode filename encoding is in effect (see the + erl manual + page), the strings can contain characters with + codepoints > 255.

+ - Get the value of an environment variable + Get the value of an environment variable.

Returns the Value of the environment variable - VarName, or false if the environment variable - is undefined.

-

If Unicode file name encoding is in effect (see the erl manual - page), the strings (both VarName and - Value) may contain characters with codepoints > 255.

+ VarName, or false if the environment + variable is undefined.

+

If Unicode filename encoding is in effect (see the + erl manual + page), the strings VarName and + Value can contain characters with + codepoints > 255.

+ - Get the value of an environment variable + Get the value of an environment variable.

Returns the Value of the environment variable - VarName, or DefaultValue if the environment variable - is undefined.

-

If Unicode file name encoding is in effect (see the erl manual - page), the strings (both VarName and - Value) may contain characters with codepoints > 255.

+ VarName, or DefaultValue if the + environment variable is undefined.

+

If Unicode filename encoding is in effect (see the + erl manual + page), the strings VarName and + Value can contain characters with + codepoints > 255.

+ - Return the process identifier of the emulator process + Return the process identifier of the emulator + process.

Returns the process identifier of the current Erlang emulator - in the format most commonly used by the operating system - environment. Value is returned as a string containing + in the format most commonly used by the OS environment. + Returns Value as a string containing the (usually) numerical identifier for a process. On Unix, this is typically the return value of the getpid() system call. On Windows, @@ -128,88 +137,93 @@ DirOut = os:cmd("dir"), % on Win32 platform system call is used.

+ - Set a new value for an environment variable + Set a new value for an environment variable. -

Sets a new Value for the environment variable +

Sets a new Value for environment variable VarName.

-

If Unicode filename encoding is in effect (see the erl manual - page), the strings (both VarName and - Value) may contain characters with codepoints > 255.

-

On Unix platforms, the environment will be set using UTF-8 encoding - if Unicode file name translation is in effect. On Windows the - environment is set using wide character interfaces.

+

If Unicode filename encoding is in effect (see the + erl manual + page), the strings VarName and + Value can contain characters with + codepoints > 255.

+

On Unix platforms, the environment is set using UTF-8 encoding + if Unicode filename translation is in effect. On Windows, the + environment is set using wide character interfaces.

+ - Current OS system time + Current OS system time. -

Returns current +

Returns the current OS system time in native time unit.

- -

This time is not a monotonically increasing time.

+

This time is not a monotonically increasing time.

+
+ - Current OS system time + Current OS system time. -

Returns current +

Returns the current OS system time converted into the Unit passed as argument.

- -

Calling os:system_time(Unit) is equivalent to: - erlang:convert_time_unit(os:system_time(), +

Calling os:system_time(Unit) is equivalent to + erlang:convert_time_unit(os:system_time(), native, Unit).

- -

This time is not a monotonically increasing time.

+

This time is not a monotonically increasing time.

+
+ - Current OS system time on the erlang:timestamp/0 format + Current OS system time on the erlang:timestamp/0 format. Timestamp = {MegaSecs, Secs, MicroSecs} -

Returns current +

Returns the current OS system time - in the same format as erlang:timestamp/0. - The tuple can be used together with the function - calendar:now_to_universal_time/1 - or calendar:now_to_local_time/1 to - get calendar time. Using the calendar time together with the MicroSecs part of the return - tuple from this function allows you to log timestamps in high resolution and consistent with the - time in the rest of the operating system.

-

Example of code formatting a string in the format "DD Mon YYYY HH:MM:SS.mmmmmm", where - DD is the day of month, Mon is the textual month name, YYYY is the year, HH:MM:SS is the time and - mmmmmm is the microseconds in six positions:

- + in the same format as + erlang:timestamp/0. + The tuple can be used together with function + calendar:now_to_universal_time/1 + or calendar:now_to_local_time/1 + to get calendar time. Using the calendar time, together with the + MicroSecs part of the return tuple from this function, allows + you to log time stamps in high resolution and consistent with the + time in the rest of the OS.

+

Example of code formatting a string in format + "DD Mon YYYY HH:MM:SS.mmmmmm", where DD is the day of month, + Mon is the textual month name, YYYY is the year, HH:MM:SS is the time, + and mmmmmm is the microseconds in six positions:

+ -module(print_time). -export([format_utc_timestamp/0]). format_utc_timestamp() -> TS = {_,_,Micro} = os:timestamp(), - {{Year,Month,Day},{Hour,Minute,Second}} = - calendar:now_to_universal_time(TS), + {{Year,Month,Day},{Hour,Minute,Second}} = +calendar:now_to_universal_time(TS), Mstr = element(Month,{"Jan","Feb","Mar","Apr","May","Jun","Jul", - "Aug","Sep","Oct","Nov","Dec"}), + "Aug","Sep","Oct","Nov","Dec"}), io_lib:format("~2w ~s ~4w ~2w:~2..0w:~2..0w.~6..0w", - [Day,Mstr,Year,Hour,Minute,Second,Micro]). - - -

The module above could be used in the following way:

-
+    [Day,Mstr,Year,Hour,Minute,Second,Micro]).
+       

This module can be used as follows:

+
 1> io:format("~s~n",[print_time:format_utc_timestamp()]).
-29 Apr 2009  9:55:30.051711
-
+29 Apr 2009 9:55:30.051711

OS system time can also be retreived by - os:system_time/0, - and os:system_time/1.

+ system_time/0 and + system_time/1.

+ Returns a performance counter @@ -227,7 +241,7 @@ format_utc_timestamp() -> high resolution timestamp. This counter is read directly from the hardware or operating system with the same guarantees. This means that two consecutive calls to the function are not guaranteed to be monotonic, though it most likely will be. - The performance counter till be converted to the resolution passed as an argument.

+ The performance counter will be converted to the resolution passed as an argument.

1> T1 = os:perf_counter(1000),receive after 10000 -> ok end,T2 = os:perf_counter(1000).
 176525861
 2> T2 - T1.
@@ -236,41 +250,43 @@ format_utc_timestamp() ->
     
     
       
-      Return the OS family and, in some cases, OS name of the current operating system
+      Return the OS family and, in some cases, the OS name of the
+        current OS.
       
-        

Returns the Osfamily and, in some cases, Osname - of the current operating system.

-

On Unix, Osname will have same value as +

Returns the Osfamily and, in some cases, the + Osname of the current OS.

+

On Unix, Osname has the same value as uname -s returns, but in lower case. For example, on - Solaris 1 and 2, it will be sunos.

-

In Windows, Osname will be either nt (on - Windows NT), or windows (on Windows 95).

+ Solaris 1 and 2, it is sunos.

+

On Windows, Osname is nt.

-

Think twice before using this function. Use the - filename module if you want to inspect or build - file names in a portable way. - Avoid matching on the Osname atom.

+

Think twice before using this function. Use module + filename + if you want to inspect or build filenames in a portable way. + Avoid matching on atom Osname.

+ - Delete an environment variable + Delete an environment variable.

Deletes the environment variable VarName.

-

If Unicode filename encoding is in effect (see the erl manual - page), the string (VarName) may - contain characters with codepoints > 255.

+

If Unicode filename encoding is in effect (see the + erl manual + page), the string VarName can + contain characters with codepoints > 255.

+ - Return the Operating System version + Return the OS versions. -

Returns the operating system version. +

Returns the OS version. On most systems, this function returns a tuple, but a string - will be returned instead if the system has versions which + is returned instead if the system has versions that cannot be expressed as three numbers.

Think twice before using this function. If you still need diff --git a/lib/kernel/doc/src/pg2.xml b/lib/kernel/doc/src/pg2.xml index 8c2fdb4cd3..0631b317b4 100644 --- a/lib/kernel/doc/src/pg2.xml +++ b/lib/kernel/doc/src/pg2.xml @@ -4,7 +4,7 @@

- 19972013 + 19972016 Ericsson AB. All Rights Reserved. @@ -30,135 +30,136 @@ mbj@erlang.ericsson.se 1997-08-18 A2 - pg2.sgml + pg2.xml
pg2 - Distributed Named Process Groups + Distributed named process groups. -

This module implements process groups. Each message may be sent - to one, some, or all members of the group. -

+

This module implements process groups. Each message can be sent + to one, some, or all group members.

A group of processes can be accessed by a common name. For example, if there is a group named foobar, there can be a - set of processes (which can be located on different nodes) which + set of processes (which can be located on different nodes) that are all members of the group foobar. There are no special functions for sending a message to the group. Instead, client - functions should be written with the functions - get_members/1 and get_local_members/1 to find out - which processes are members of the group. Then the message can be - sent to one or more members of the group. -

-

If a member terminates, it is automatically removed from the - group. -

+ functions are to be written with the functions + get_members/1 and + get_local_members/1 + to determine which processes are members of the group. + Then the message can be sent to one or more group members.

+

If a member terminates, it is automatically removed from the group.

-

This module is used by the disk_log module for +

This module is used by module + disk_log for managing distributed disk logs. The disk log names are used as - group names, which means that some action may need to be taken + group names, which means that some action can be needed to avoid name clashes.

+

The name of a process group.

+ - Create a new, empty process group + Create a new, empty process group.

Creates a new, empty process group. The group is globally - visible on all nodes. If the group exists, nothing happens. -

+ visible on all nodes. If the group exists, nothing happens.

+ - Delete a process group + Delete a process group. -

Deletes a process group. -

+

Deletes a process group.

+ - Common dispatch function + Common dispatch function. -

This is a useful dispatch function which can be used from +

A useful dispatch function that can be used from client functions. It returns a process on the local node, if - such a process exist. Otherwise, it chooses one randomly. -

+ such a process exists. Otherwise, it selects one randomly.

+ - - Return all processes in a group + + Return all local processes in a group. -

Returns all processes in the group Name. This - function should be used from within a client function that - accesses the group. It is therefore optimized for speed. -

+

Returns all processes running on the local node in the + group Name. This function is to be used from + within a client function that accesses the group. It is therefore + optimized for speed.

+ - - Return all local processes in a group + + Return all processes in a group. -

Returns all processes running on the local node in the - group Name. This function should to be used from - within a client function that accesses the group. It is therefore - optimized for speed. -

+

Returns all processes in the group Name. This + function is to be used from within a client function that + accesses the group. It is therefore optimized for speed.

+ - Join a process to a group + Join a process to a group.

Joins the process Pid to the group Name. - A process can join a group several times; it must then - leave the group the same number of times. -

+ A process can join a group many times and must then + leave the group the same number of times.

+ - Make a process leave a group + Make a process leave a group.

Makes the process Pid leave the group Name. If the process is not a member of the group, ok is - returned. -

-
-
- - - Return a list of all known groups - -

Returns a list of all known groups. -

+ returned.

+ - Start the pg2 server + Start the pg2 server. -

Starts the pg2 server. Normally, the server does not need +

Starts the pg2 server. Normally, the server does not need to be started explicitly, as it is started dynamically if it is needed. This is useful during development, but in a - target system the server should be started explicitly. Use - configuration parameters for kernel for this. -

+ target system the server is to be started explicitly. Use the + configuration parameters for + kernel(6) + for this.

+
+
+ + + + Return a list of all known groups. + +

Returns a list of all known groups.

See Also -

kernel(6)

+

kernel(6)

diff --git a/lib/kernel/doc/src/ref_man.xml b/lib/kernel/doc/src/ref_man.xml index 7eb48a5f1d..32f4f8900e 100644 --- a/lib/kernel/doc/src/ref_man.xml +++ b/lib/kernel/doc/src/ref_man.xml @@ -29,9 +29,7 @@ -

The Kernel application has all the code necessary to run - the Erlang runtime system itself: file servers and code servers - and so on.

+
@@ -45,9 +43,9 @@ + - diff --git a/lib/kernel/doc/src/rpc.xml b/lib/kernel/doc/src/rpc.xml index c323a84e50..032b4fb0c3 100644 --- a/lib/kernel/doc/src/rpc.xml +++ b/lib/kernel/doc/src/rpc.xml @@ -25,328 +25,407 @@ rpc Claes Wikstrom 1 - 96-09-10 + 1996-09-10 A rpc - Remote Procedure Call Services + Remote Procedure Call services. -

This module contains services which are similar to remote - procedure calls. It also contains broadcast facilities and +

This module contains services similar to Remote + Procedure Calls. It also contains broadcast facilities and parallel evaluators. A remote procedure call is a method to call a function on a remote node and collect the answer. It is used for collecting information on a remote node, or for running a function with some specific side effects on the remote node.

+ -

As returned by - async_call/4.

+

As returned by + async_call/4.

+ - - Evaluate a function call on a node + + Broadcast a message asynchronously to a registered process on + all nodes. -

Evaluates apply(Module, Function, Args) on the node - Node and returns the corresponding value Res, or - {badrpc, Reason} if the call fails.

+

Equivalent to abcast([node()|nodes()], Name, + Msg).

+ - - Evaluate a function call on a node + + Broadcast a message asynchronously to a registered process on + specific nodes. -

Evaluates apply(Module, Function, Args) on the node - Node and returns the corresponding value Res, or - {badrpc, Reason} if the call fails. Timeout is - a timeout value in milliseconds. If the call times out, - Reason is timeout.

-

If the reply arrives after the call times out, no message - will contaminate the caller's message queue, since this - function spawns off a middleman process to act as (a void) - destination for such an orphan reply. This feature also makes - this function more expensive than call/4 at - the caller's end.

+

Broadcasts the message Msg asynchronously to + the registered process Name on the specified + nodes.

+ + + + Evaluate a function call on a node, asynchronous + version. + +

Implements call streams with promises, a type of + RPC that does not suspend the caller until the result is + finished. Instead, a key is returned, which can be used + later to collect the value. The key can be viewed as a + promise to deliver the answer.

+

In this case, the key Key is returned, which + can be used in a subsequent call to + yield/1 or + nb_yield/1,2 + to retrieve the value of evaluating apply(Module, + Function, Args) on node + Node.

+
+
+ - Evaluate a function call on a node in the RPC server's context + Evaluate a function call on a node in the RPC server's + context. -

Like call/4, but the RPC server at Node does +

Same as call/4, + but the RPC server at Node does not create a separate process to handle the call. Thus, this function can be used if the intention of the call is to block the RPC server from any other incoming requests until - the request has been handled. The function can also be used + the request has been handled. The function can also be used for efficiency reasons when very small fast functions are - evaluated, for example BIFs that are guaranteed not to + evaluated, for example, BIFs that are guaranteed not to suspend.

+ - Evaluate a function call on a node in the RPC server's context + Evaluate a function call on a node in the RPC server's + context. -

Like block_call/4, but with a timeout value in - the same manner as call/5.

+

Same as + block_call/4, + but with a time-out value in the same manner as + call/5.

+ - - Evaluate a function call on a node, asynchronous version + + Evaluate a function call on a node. -

Implements call streams with promises, a type of - RPC which does not suspend the caller until the result is - finished. Instead, a key is returned which can be used at a - later stage to collect the value. The key can be viewed as a - promise to deliver the answer.

-

In this case, the key Key is returned, which can be - used in a subsequent call to yield/1 or - nb_yield/1,2 to retrieve the value of evaluating - apply(Module, Function, Args) on the node Node.

+

Evaluates apply(Module, Function, + Args) on node Node and returns + the corresponding value Res, or + {badrpc, Reason} if the call fails.

+ - - Deliver the result of evaluating a function call on a node (blocking) + + Evaluate a function call on a node. -

Returns the promised answer from a previous - async_call/4. If the answer is available, it is - returned immediately. Otherwise, the calling process is - suspended until the answer arrives from Node.

+

Evaluates apply(Module, Function, + Args) on node Node and returns + the corresponding value Res, or + {badrpc, Reason} if the call fails. + Timeout is + a time-out value in milliseconds. If the call times out, + Reason is timeout.

+

If the reply arrives after the call times out, no message + contaminates the caller's message queue, as this + function spawns off a middleman process to act as (a void) + destination for such an orphan reply. This feature also makes + this function more expensive than call/4 at + the caller's end.

+ - - Deliver the result of evaluating a function call on a node (non-blocking) + + Run a function on a node ignoring the result. -

Equivalent to nb_yield(Key, 0).

+

Evaluates apply(Module, Function, + Args) on node + Node. No response is delivered and the calling + process is not suspended until the evaluation is complete, as + is the case with + call/4,5.

+ - - Deliver the result of evaluating a function call on a node (non-blocking) + + Run a function on all nodes, ignoring the result. + +

Equivalent to eval_everywhere([node()|nodes()], + Module, Function, + Args).

+
+
+ + + + Run a function on specific nodes, ignoring the + result. + +

Evaluates apply(Module, Function, + Args) on + the specified nodes. No answers are collected.

+
+
+ + + + Interact with the servers on a number of nodes. + +

Equivalent to multi_server_call([node()|nodes()], + Name, Msg).

+
+
+ + + + Interact with the servers on a number of nodes. -

This is a non-blocking version of yield/1. It returns - the tuple {value, Val} when the computation has - finished, or timeout when Timeout milliseconds - has elapsed.

+

Can be used when interacting with servers called + Name on the specified nodes. It is assumed that + the servers receive messages in the format + {From, Msg} and reply using + From ! {Name, Node, Reply}, where + Node is the name of the node where the server is located. + The function returns {Replies, + BadNodes}, where Replies is a + list of all Reply values, and + BadNodes is one of the following:

+ + A list of the nodes that do not exist + A list of the nodes where the server does not exist + A list of the nodes where the server terminatd before sending + any reply. +
+ - Evaluate a function call on a number of nodes + Evaluate a function call on a number of nodes. -

Equivalent to multicall([node()|nodes()], Module, Function, Args, infinity).

+

Equivalent to multicall([node()|nodes()], Module, + Function, Args, infinity).

+ - Evaluate a function call on a number of nodes + Evaluate a function call on a number of nodes. -

Equivalent to multicall(Nodes, Module, Function, Args, infinity).

+

Equivalent to multicall(Nodes, Module, + Function, Args, infinity).

+ - Evaluate a function call on a number of nodes + Evaluate a function call on a number of nodes. -

Equivalent to multicall([node()|nodes()], Module, Function, Args, Timeout).

+

Equivalent to multicall([node()|nodes()], Module, + Function, Args, + Timeout).

+ - Evaluate a function call on a number of nodes + Evaluate a function call on a number of nodes. -

In contrast to an RPC, a multicall is an RPC which is sent +

In contrast to an RPC, a multicall is an RPC that is sent concurrently from one client to multiple servers. This is - useful for collecting some information from a set of nodes, + useful for collecting information from a set of nodes, or for calling a function on a set of nodes to achieve some side effects. It is semantically the same as iteratively making a series of RPCs on all the nodes, but the multicall - is faster as all the requests are sent at the same time + is faster, as all the requests are sent at the same time and are collected one by one as they come back.

-

The function evaluates apply(Module, Function, Args) - on the specified nodes and collects the answers. It returns - {ResL, BadNodes}, where BadNodes is a list +

The function evaluates apply(Module, + Function, Args) + on the specified nodes and collects the answers. It returns + {ResL, BadNodes}, where + BadNodes is a list of the nodes that terminated or timed out during computation, and ResL is a list of the return values. Timeout is a time (integer) in milliseconds, or infinity.

The following example is useful when new object code is to - be loaded on all nodes in the network, and also indicates - some side effects RPCs may produce:

+ be loaded on all nodes in the network, and indicates + some side effects that RPCs can produce:

-%% Find object code for module Mod -{Mod, Bin, File} = code:get_object_code(Mod), +%% Find object code for module Mod +{Mod, Bin, File} = code:get_object_code(Mod), -%% and load it on all nodes including this one +%% and load it on all nodes including this one {ResL, _} = rpc:multicall(code, load_binary, [Mod, File, Bin]), %% and then maybe check the ResL list.
+ - - Run a function on a node ignoring the result - -

Evaluates apply(Module, Function, Args) on the node - Node. No response is delivered and the calling - process is not suspended until the evaluation is complete, as - is the case with call/4,5.

-
-
- - - Run a function on all nodes, ignoring the result - -

Equivalent to eval_everywhere([node()|nodes()], Module, Function, Args).

-
-
- - - Run a function on specific nodes, ignoring the result - -

Evaluates apply(Module, Function, Args) on - the specified nodes. No answers are collected.

-
-
- - - Broadcast a message asynchronously to a registered process on all nodes - -

Equivalent to abcast([node()|nodes()], Name, Msg).

-
-
- - - Broadcast a message asynchronously to a registered process on specific nodes + + Deliver the result of evaluating a function call on a node + (non-blocking). -

Broadcasts the message Msg asynchronously to - the registered process Name on the specified nodes.

+

Equivalent to nb_yield(Key, 0).

+ - - Broadcast a message synchronously to a registered process on all nodes + + Deliver the result of evaluating a function call on a node + (non-blocking). -

Equivalent to sbcast([node()|nodes()], Name, Msg).

+

Non-blocking version of + yield/1. It returns + the tuple {value, Val} when the computation is + finished, or timeout when Timeout + milliseconds has elapsed.

+ - - Broadcast a message synchronously to a registered process on specific nodes + + Evaluate many function calls on all nodes in + parallel. -

Broadcasts the message Msg synchronously to - the registered process Name on the specified nodes.

-

Returns {GoodNodes, BadNodes}, where GoodNodes - is the list of nodes which have Name as a registered - process.

-

The function is synchronous in the sense that it is known - that all servers have received the message when the call - returns. It is not possible to know that the servers have - actually processed the message.

-

Any further messages sent to the servers, after this - function has returned, will be received by all servers after - this message.

+

Evaluates, for every tuple in FuncCalls, + apply(Module, Function, + Args) on some node in + the network. Returns the list of return values, in the same + order as in FuncCalls.

+ - - Interact with a server on a node + + Information about a process. -

This function can be used when interacting with a server - called Name at node Node. It is assumed that - the server receives messages in the format - {From, Msg} and replies using From ! {ReplyWrapper, Node, Reply}. This function makes such - a server call and ensures that the entire call is packed into - an atomic transaction which either succeeds or fails. It - never hangs, unless the server itself hangs.

-

The function returns the answer Reply as produced by - the server Name, or {error, Reason}.

+

Location transparent version of the BIF + erlang:process_info/1 in ERTS.

+ - - Interact with the servers on a number of nodes + + Information about a process. -

Equivalent to multi_server_call([node()|nodes()], Name, Msg).

+

Location transparent version of the BIF + erlang:process_info/2 in ERTS.

+ - - Interact with the servers on a number of nodes + + Parallell evaluation of mapping a function over a + list. -

This function can be used when interacting with servers - called Name on the specified nodes. It is assumed that - the servers receive messages in the format {From, Msg} - and reply using From ! {Name, Node, Reply}, where - Node is the name of the node where the server is - located. The function returns {Replies, BadNodes}, - where Replies is a list of all Reply values and - BadNodes is a list of the nodes which did not exist, or - where the server did not exist, or where the server terminated - before sending any reply.

+

Evaluates apply(Module, Function, + [Elem|ExtraArgs]) for every element + Elem in List1, in parallel. + Returns the list of return values, in the same order as in + List1.

+ - Interact with the servers on a number of nodes (deprecated) + Interact with the servers on a number of nodes + (deprecated). -

This function is deprecated. Use - multi_server_call/2,3 instead.

+

Deprecated. Use + multi_server_call/2,3 + instead.

In Erlang/OTP R6B and earlier releases, multi_server_call/2,3 could not handle the case where the remote node exists, but there is no server called - Name. Instead this function had to be used. In + Name. Instead, this function had to be used. In Erlang/OTP R7B and later releases, however, the functions are - equivalent, except for this function being slightly slower.

+ equivalent, except that this function is slightly slower.

+ - - Evaluate several function calls on all nodes in parallel + + Broadcast a message synchronously to a registered process on + all nodes. -

For every tuple in FuncCalls, evaluates - apply(Module, Function, Args) on some node in - the network. Returns the list of return values, in the same - order as in FuncCalls.

+

Equivalent to sbcast([node()|nodes()], Name, + Msg).

+ - - Parallell evaluation of mapping a function over a list + + Broadcast a message synchronously to a registered process on + specific nodes. -

Evaluates apply(Module, Function, [Elem|ExtraArgs]), - for every element Elem in List1, in parallel. - Returns the list of return values, in the same order as in - List1.

+

Broadcasts the message Msg synchronously to + the registered process Name on the specified + nodes.

+

Returns {GoodNodes, BadNodes}, + where GoodNodes is the list of nodes that have + Name as a registered process.

+

The function is synchronous in the sense that it is known + that all servers have received the message when the call + returns. It is not possible to know that the servers have + processed the message.

+

Any further messages sent to the servers, after this + function has returned, are received by all servers after + this message.

+ - - Information about a process + + Interact with a server on a node. -

Location transparent version of the BIF - - process_info/1.

+

Can be used when interacting with a server called + Name on node Node. It is + assumed that the server receives messages in the format + {From, Msg} and replies using + From ! {ReplyWrapper, Node, + Reply}. This function makes such + a server call and ensures that the entire call is packed into + an atomic transaction, which either succeeds or fails. It + never hangs, unless the server itself hangs.

+

The function returns the answer Reply as + produced by the server Name, or + {error, Reason}.

+ - - Information about a process + + Deliver the result of evaluating a function call on a node + (blocking). -

Location transparent version of the BIF - - process_info/2.

+

Returns the promised answer from a previous + async_call/4. + If the answer is available, it is + returned immediately. Otherwise, the calling process is + suspended until the answer arrives from Node.

diff --git a/lib/kernel/doc/src/seq_trace.xml b/lib/kernel/doc/src/seq_trace.xml index 857444e338..d29aceb564 100644 --- a/lib/kernel/doc/src/seq_trace.xml +++ b/lib/kernel/doc/src/seq_trace.xml @@ -29,24 +29,17 @@ A seq_trace - Sequential Tracing of Messages + Sequential tracing of messages.

Sequential tracing makes it possible to trace all messages resulting from one initial message. Sequential tracing is - completely independent of the ordinary tracing in Erlang, which - is controlled by the erlang:trace/3 BIF. See the chapter - What is Sequential Tracing - below for more information about what sequential tracing is and - how it can be used.

-

seq_trace provides functions which control all aspects of + independent of the ordinary tracing in Erlang, which + is controlled by the erlang:trace/3 BIF. For more information + about what sequential tracing is and how it can be used, see section + Sequential Tracing.

+

seq_trace provides functions that control all aspects of sequential tracing. There are functions for activation, - deactivation, inspection and for collection of the trace output.

- -

The implementation of sequential tracing is in beta status. - This means that the programming interface still might undergo - minor adjustments (possibly incompatible) based on feedback - from users.

-
+ deactivation, inspection, and for collection of the trace output.

@@ -239,20 +232,21 @@ seq_trace:set_token(OldToken), % activate the trace token again
- Trace Messages Sent To the System Tracer -

The format of the messages are:

+ Trace Messages Sent to the System Tracer +

The format of the messages is one of the following, depending on if + flag timestamp of the trace token is set to true or + false:

{seq_trace, Label, SeqTraceInfo, TimeStamp}

or

{seq_trace, Label, SeqTraceInfo} -

depending on whether the timestamp flag of the trace - token is set to true or false. Where:

+

Where:

Label = int() TimeStamp = {Seconds, Milliseconds, Microseconds} Seconds = Milliseconds = Microseconds = int() -

The SeqTraceInfo can have the following formats:

+

SeqTraceInfo can have the following formats:

{send, Serial, From, To, Message} @@ -262,141 +256,151 @@ TimeStamp = {Seconds, Milliseconds, Microseconds} {'receive', Serial, From, To, Message}

Used when a process To receives a message with a - trace token that has the 'receive' flag set to - true.

+ trace token that has flag 'receive' set to true.

{print, Serial, From, _, Info} -

Used when a process From has called +

Used when a process From has called seq_trace:print(Label, TraceInfo) and has a trace - token with the print flag set to true and + token with flag print set to true, and label set to Label.

Serial is a tuple {PreviousSerial, ThisSerial}, - where the first integer PreviousSerial denotes the serial - counter passed in the last received message which carried a trace - token. If the process is the first one in a new sequential trace, - PreviousSerial is set to the value of the process internal - "trace clock". The second integer ThisSerial is the serial - counter that a process sets on outgoing messages and it is based - on the process internal "trace clock" which is incremented by one - before it is attached to the trace token in the message.

+ where:

+ +

Integer PreviousSerial denotes the serial + counter passed in the last received message that carried a trace + token. If the process is the first in a new sequential trace, + PreviousSerial is set to the value of the process internal + "trace clock".

+

Integer ThisSerial is the serial + counter that a process sets on outgoing messages. It is based + on the process internal "trace clock", which is incremented by one + before it is attached to the trace token in the message.

+
- What is Sequential Tracing + Sequential Tracing

Sequential tracing is a way to trace a sequence of messages sent between different local or remote processes, where the sequence - is initiated by one single message. In short it works like this:

+ is initiated by a single message. In short, it works as follows:

Each process has a trace token, which can be empty or - not empty. When not empty the trace token can be seen as + not empty. When not empty, the trace token can be seen as the tuple {Label, Flags, Serial, From}. The trace token is passed invisibly with each message.

-

In order to start a sequential trace the user must explicitly set +

To start a sequential trace, the user must explicitly set the trace token in the process that will send the first message in a sequence.

The trace token of a process is set each time the process matches a message in a receive statement, according to the trace token carried by the received message, empty or not.

-

On each Erlang node a process can be set as the system tracer. This process will receive trace messages each time +

On each Erlang node, a process can be set as the system tracer. + This process receives trace messages each time a message with a trace token is sent or received (if the trace token flag send or 'receive' is set). The system - tracer can then print each trace event, write it to a file or + tracer can then print each trace event, write it to a file, or whatever suitable.

-

The system tracer will only receive those trace events that +

The system tracer only receives those trace events that occur locally within the Erlang node. To get the whole picture - of a sequential trace that involves processes on several Erlang + of a sequential trace, involving processes on many Erlang nodes, the output from the system tracer on each involved node - must be merged (off line).

+ must be merged (offline).

-

In the following sections Sequential Tracing and its most - fundamental concepts are described.

+

The following sections describe sequential tracing and its most + fundamental concepts.

Trace Token -

Each process has a current trace token. Initially the token is +

Each process has a current trace token. Initially, the token is empty. When the process sends a message to another process, a - copy of the current token will be sent "invisibly" along with + copy of the current token is sent "invisibly" along with the message.

-

The current token of a process is set in two ways, either

- +

The current token of a process is set in one of the following two + ways:

+ -

explicitly by the process itself, through a call to - seq_trace:set_token, or

+

Explicitly by the process itself, through a call to + seq_trace:set_token/1,2

-

when a message is received.

+

When a message is received

-

In both cases the current token will be set. In particular, if - the token of a message received is empty, the current token of +

In both cases, the current token is set. In particular, if + the token of a received message is empty, the current token of the process is set to empty.

-

A trace token contains a label, and a set of flags. Both - the label and the flags are set in 1 and 2 above.

+

A trace token contains a label and a set of flags. Both + the label and the flags are set in both alternatives above.

Serial -

The trace token contains a component which is called - serial. It consists of two integers Previous and +

The trace token contains a component called + serial. It consists of two integers, Previous and Current. The purpose is to uniquely identify each traced - event within a trace sequence and to order the messages - chronologically and in the different branches if any.

+ event within a trace sequence, as well as to order the messages + chronologically and in the different branches, if any.

The algorithm for updating Serial can be described as follows:

-

Let each process have two counters prev_cnt and - curr_cnt which both are set to 0 when a process is created. +

Let each process have two counters, prev_cnt and + curr_cnt, both are set to 0 when a process is created. The counters are updated at the following occasions:

-

When the process is about to send a message and the trace token is not empty.

+

When the process is about to send a message and the trace token + is not empty.

Let the serial of the trace token be tprev and - tcurr.

-curr_cnt := curr_cnt + 1

-tprev := prev_cnt

-tcurr := curr_cnt

+ tcurr.

+
+curr_cnt := curr_cnt + 1
+tprev := prev_cnt
+tcurr := curr_cnt

The trace token with tprev and tcurr is then passed along with the message.

-

When the process callsseq_trace:print(Label, Info), Label matches the label part of the trace token and the trace token print flag is true.

-

The same algorithm as for send above.

+

When the process calls seq_trace:print(Label, Info), + Label matches the label part of the trace token and the + trace token print flag is true.

+

The algorithm is the same as for send above.

-

When a message is received and contains a nonempty trace token.

+

When a message is received and contains a non-empty trace + token.

The process trace token is set to the trace token from the message.

Let the serial of the trace token be tprev and - tcurr.

-

- -        curr_cnt := tcurr

-prev_cnt := tcurr

+ tcurr.

+ + + curr_cnt := tcurr +prev_cnt := tcurr
-

The curr_cnt of a process is incremented each time +

curr_cnt of a process is incremented each time the process is involved in a sequential trace. The counter can reach its limit (27 bits) if a process is very long-lived and is - involved in much sequential tracing. If the counter overflows it - will not be possible to use the serial for ordering of the trace - events. To prevent the counter from overflowing in the middle of - a sequential trace the function seq_trace:reset_trace/0 - can be called to reset the prev_cnt and curr_cnt of - all processes in the Erlang node. This function will also set all - trace tokens in processes and their message queues to empty and - will thus stop all ongoing sequential tracing.

+ involved in much sequential tracing. If the counter overflows, the + serial for ordering of the trace events cannot be used. To prevent + the counter from overflowing in the middle of + a sequential trace, function seq_trace:reset_trace/0 + can be called to reset prev_cnt and curr_cnt of + all processes in the Erlang node. This function also sets all + trace tokens in processes and their message queues to empty, and + thus stops all ongoing sequential tracing.

- Performance considerations -

The performance degradation for a system which is enabled for - Sequential Tracing is negligible as long as no tracing is - activated. When tracing is activated there will of course be an - extra cost for each traced message but all other messages will be + Performance Considerations +

The performance degradation for a system that is enabled for + sequential tracing is negligible as long as no tracing is + activated. When tracing is activated, there is an + extra cost for each traced message, but all other messages are unaffected.

@@ -404,13 +408,13 @@ TimeStamp = {Seconds, Milliseconds, Microseconds} Ports

Sequential tracing is not performed across ports.

If the user for some reason wants to pass the trace token to a - port this has to be done manually in the code of the port + port, this must be done manually in the code of the port controlling process. The port controlling processes have to check the appropriate sequential trace settings (as obtained from - seq_trace:get_token/1 and include trace information in + seq_trace:get_token/1) and include trace information in the message data sent to their respective ports.

Similarly, for messages received from a port, a port controller - has to retrieve trace specific information, and set appropriate + has to retrieve trace-specific information, and set appropriate sequential trace flags through calls to seq_trace:set_token/2.

@@ -418,23 +422,23 @@ TimeStamp = {Seconds, Milliseconds, Microseconds}
Distribution

Sequential tracing between nodes is performed transparently. - This applies to C-nodes built with Erl_Interface too. A C-node - built with Erl_Interface only maintains one trace token, which - means that the C-node will appear as one process from + This applies to C-nodes built with Erl_Interface too. A C-node + built with Erl_Interface only maintains one trace token, which + means that the C-node appears as one process from the sequential tracing point of view.

-

In order to be able to perform sequential tracing between +

To be able to perform sequential tracing between distributed Erlang nodes, the distribution protocol has been - extended (in a backward compatible way). An Erlang node which - supports sequential tracing can communicate with an older - (OTP R3B) node but messages passed within that node can of course + extended (in a backward compatible way). An Erlang node + supporting sequential tracing can communicate with an older + (Erlang/OTP R3B) node but messages passed within that node can not be traced.

- Example of Usage -

The example shown here will give rough idea of how the new - primitives can be used and what kind of output it will produce.

-

Assume that we have an initiating process with + Example of Use +

This example gives a rough idea of how the new + primitives can be used and what kind of output it produces.

+

Assume that you have an initiating process with ]]> like this:

-module(seqex). @@ -463,8 +467,8 @@ loop() -> PortController ! {ack,Ack} end, loop(). -

A possible output from the system's sequential_tracer (inspired - by AXE-10 and MD-110) could look like:

+

A possible output from the system's sequential_tracer can be + like this:

 17:<0.30.0> Info {0,1} WITH
 "**** Trace Started ****"
@@ -475,7 +479,7 @@ loop() ->
 17:<0.30.0> Received {2,4} FROM <0.31.0> WITH
 {ack,{received,the_message}}

The implementation of a system tracer process that produces - the printout above could look like this:

+ this printout can look like this:

tracer() -> receive @@ -502,16 +506,15 @@ print_trace({'receive',Serial,From,To,Message}) -> print_trace({send,Serial,From,To,Message}) -> io:format("~p Sent ~p TO ~p WITH~n~p~n", [From,Serial,To,Message]). -

The code that creates a process that runs the tracer function - above and sets that process as the system tracer could look like - this:

+

The code that creates a process that runs this tracer function + and sets that process as the system tracer can look like this:

start() -> Pid = spawn(?MODULE,tracer,[]), seq_trace:set_system_tracer(Pid), % set Pid as the system tracer ok. -

With a function like test/0 below the whole example can be - started.

+

With a function like test/0, the whole example can be + started:

test() -> P = spawn(?MODULE, loop, [port]), diff --git a/lib/kernel/doc/src/user.xml b/lib/kernel/doc/src/user.xml index 24119bea82..440b7878e8 100644 --- a/lib/kernel/doc/src/user.xml +++ b/lib/kernel/doc/src/user.xml @@ -27,13 +27,13 @@ user Robert Virding 1 - 96-10-10 + 1996-10-10 A user - Standard I/O Server + Standard I/O server. -

user is a server which responds to all the messages +

user is a server that responds to all messages defined in the I/O interface. The code in user.erl can be used as a model for building alternative I/O servers.

diff --git a/lib/kernel/doc/src/wrap_log_reader.xml b/lib/kernel/doc/src/wrap_log_reader.xml index c021f42cac..7fb9c1c023 100644 --- a/lib/kernel/doc/src/wrap_log_reader.xml +++ b/lib/kernel/doc/src/wrap_log_reader.xml @@ -4,7 +4,7 @@
- 19982013 + 19982016 Ericsson AB. All Rights Reserved. @@ -26,39 +26,43 @@ Esko Vierumäki Esko Vierumäki - nobody - no - 98-09-21 + + + 1998-09-21 A wrap_log_reader.sgml
wrap_log_reader - A function to read internally formatted wrap disk logs + A service to read internally formatted wrap disk logs. + -

wrap_log_reader is a function to read internally formatted - wrap disk logs, refer to disk_log(3). wrap_log_reader does not - interfere with disk_log activities; there is however a known bug in this - version of the wrap_log_reader, see chapter bugs below. -

-

A wrap disk log file consists of several files, called index files. - A log file can be opened and closed. It is also possible to open just one index file - separately. If an non-existent or a non-internally formatted file is opened, - an error message is returned. If the file is corrupt, no attempt to repair it - will be done but an error message is returned. -

-

If a log is configured to be distributed, there is a possibility that all items - are not loggen on all nodes. wrap_log_reader does only read the log on - the called node, it is entirely up to the user to be sure that all items are read. -

+

This module makes it possible to read internally formatted + wrap disk logs, see + disk_log(3). + wrap_log_reader does not + interfere with disk_log activities; there is however a bug in this + version of the wrap_log_reader, see section + Known Limitations.

+

A wrap disk log file consists of many files, called index files. A log + file can be opened and closed. Also, a single index file can be opened + separately. If a non-existent or non-internally formatted file is opened, + an error message is returned. If the file is corrupt, no attempt is made + to repair it, but an error message is returned.

+

If a log is configured to be distributed, it is possible that all items + are not logged on all nodes. wrap_log_reader only reads the log on + the called node; it is up to the user to be sure that all items + are read.

+ -

Continuation returned by - open/1,2 or chunk/1,2.

+ +

Continuation returned by open/1,2 or chunk/1,2.

+ @@ -66,87 +70,83 @@ Read a chunk of objects written to a wrap log. -

This function makes it possible to efficiently read the - terms which have been appended to a log. It minimises disk - I/O by reading large 8K chunks from the file. -

-

The first time chunk is called an initial - continuation returned from the open/1, open/2 must be provided. -

+

Enables to efficiently read the + terms that are appended to a log. Minimises disk + I/O by reading 64 kilobyte chunks from the file.

+

The first time chunk() is called, an initial + continuation returned from open/1 or open/2 must be + provided.

When chunk/3 is called, N controls the maximum number of terms that are read from the log in each - chunk. Default is infinity, which means that all the + chunk. Defaults to infinity, which means that all the terms contained in the 8K chunk are read. If less than - N terms are returned, this does not necessarily mean - that end of file is reached. -

-

The chunk function returns a tuple - {Continuation2, Terms}, where Terms is a list + N terms are returned, this does not necessarily + mean that end of file is reached.

+

Returns a tuple {Continuation2, + Terms}, where Terms is a list of terms found in the log. Continuation2 is yet - another continuation which must be passed on into any - subsequent calls to chunk. With a series of calls to - chunk it is then possible to extract all terms from a - log. -

-

The chunk function returns a tuple - {Continuation2, Terms, Badbytes} if the log is opened - in read only mode and the read chunk is corrupt. Badbytes + another continuation that must be passed on to any + subsequent calls to chunk(). With a series of calls to + chunk(), it is then possible to extract all terms from a log.

+

Returns a tuple {Continuation2, + Terms, Badbytes} if the log is opened + in read only mode and the read chunk is corrupt. + Badbytes indicates the number of non-Erlang terms found in the chunk. - Note also that the log is not repaired. -

-

chunk returns {Continuation2, eof} when the end of the log is - reached, and {error, Reason} if an error occurs. -

-

The returned continuation may or may not be valid in the next call to - chunk. This is because the log may wrap and delete - the file into which the continuation points. To make sure - this does not happen, the log can be blocked during the - search. -

+ Notice that the log is not repaired.

+

Returns {Continuation2, eof} when + the end of the log is reached, and {error, Reason} + if an error occurs.

+

The returned continuation either is or is not valid in the next call + to this function. This is because the log can wrap and delete + the file into which the continuation points. To ensure + this does not occur, the log can be blocked during the search.

+ - Close a log + Close a log. -

This function closes a log file properly. -

+

Closes a log file properly.

+ - Open a log file + Open a log file. -

Filename specifies the name of the file which is to be read.

-

N specifies the index of the file which is to be read. - If N is omitted the whole wrap log file will be read; if it - is specified only the specified index file will be read. -

-

The open function returns {ok, Continuation} if the - log/index file was successfully opened. The Continuation - is to be used when chunking or closing the file. -

-

The function returns {error, Reason} for all errors. -

+

Filename specifies the name of the file to be + read.

+

N specifies the index of the file to be read. + If N is omitted, the whole wrap log file is read; + if it is specified, only the specified index file is read.

+

Returns {ok, Continuation} if the + log/index file is opened successfully. + Continuation + is to be used when chunking or closing the file.

+

Returns {error, Reason} for all errors.

- Bugs -

This version of the wrap_log_reader does not detect if the disk_log - wraps to a new index file between a wrap_log_reader:open and the first - wrap_log_reader:chunk. - In this case the chuck will actually read the last logged items in the log file, - because the opened index file was truncated by the disk_log. -

+ Known Limitations + +

This version of wrap_log_reader does not detect if + disk_log wraps to a new index file between a call to + wrap_log_reader:open() and the first call to + wrap_log_reader:chunk(). + If this occurs, the call to chunk() reads the last logged + items in the log file, as the opened index file was truncated by + disk_log.

See Also -

disk_log(3)

+

disk_log(3)

diff --git a/lib/kernel/doc/src/zlib_stub.xml b/lib/kernel/doc/src/zlib_stub.xml index d1823b01aa..ea2a6af2bd 100644 --- a/lib/kernel/doc/src/zlib_stub.xml +++ b/lib/kernel/doc/src/zlib_stub.xml @@ -31,13 +31,9 @@ A zlib - Zlib Compression interface. -

- - The module zlib is moved to the runtime system - application. Please see zlib(3) in the - erts reference manual instead. - -

+ Zlib compression interface. + +

This module is moved to the + ERTS application.

+
-- cgit v1.2.3