# Elixir v1.10.3 System View Source

The `System` module provides functions that interact directly with the VM or the host system.

## Time

The `System` module also provides functions that work with time, returning different times kept by the system with support for different time units.

One of the complexities in relying on system times is that they may be adjusted. For example, when you enter and leave daylight saving time, the system clock will be adjusted, often adding or removing one hour. We call such changes "time warps". In order to understand how such changes may be harmful, imagine the following code:

    ## DO NOT DO THIS
    prev = System.os_time()
    # ... execute some code ...
    next = System.os_time()
    diff = next - prev

If, while the code is executing, the system clock changes, some code that executed in 1 second may be reported as taking over 1 hour! To address such concerns, the VM provides a monotonic time via `System.monotonic_time/0` which never decreases and does not leap:

    ## DO THIS
    prev = System.monotonic_time()
    # ... execute some code ...
    next = System.monotonic_time()
    diff = next - prev

Generally speaking, the VM provides three time measurements:

- `os_time/0` - the time reported by the operating system (OS). This time may be adjusted forwards or backwards in time with no limitation;

- `system_time/0` - the VM view of the `os_time/0`. The system time and operating system time may not match in case of time warps although the VM works towards aligning them. This time is not monotonic (i.e., it may decrease) as its behaviour is configured by the VM time warp mode;

- `monotonic_time/0` - a monotonically increasing time provided by the Erlang VM.

The time functions in this module work in the `:native` unit (unless specified otherwise), which is operating system dependent. Most of the time, all calculations are done in the `:native` unit, to avoid loss of precision, with `convert_time_unit/3` being invoked at the end to convert to a specific time unit like `:millisecond` or `:microsecond`. See the `t:time_unit/0` type for more information.

For a more complete rundown on the VM support for different times, see the chapter on time and time correction in the Erlang docs.

# Link to this section Summary

## Types

time_unit()

The time unit to be passed to functions like `monotonic_time/1` and others.

## Functions

argv()

Lists command line arguments.

argv(args)

Modifies command line arguments.

at_exit(fun)

Registers a program exit handler function.

build_info()

Elixir build information.

cmd(command, args, opts \\ [])

Executes the given `command` with `args`.

compiled_endianness()

Returns the endianness the system was compiled with.

convert_time_unit(time, from_unit, to_unit)

Converts `time` from time unit `from_unit` to time unit `to_unit`.

cwd() deprecated

Current working directory.

cwd!() deprecated

Current working directory, exception on error.

delete_env(varname)

Deletes an environment variable.

endianness()

Returns the endianness.

fetch_env(varname)

Returns the value of the given environment variable or `:error` if not found.

fetch_env!(varname)

Returns the value of the given environment variable or raises if not found.

find_executable(program)

Locates an executable on the system.

get_env()

Returns all system environment variables.

get_env(varname, default \\ nil)

Returns the value of the given environment variable.

get_pid() deprecated

Erlang VM process identifier.

halt(status \\ 0)

Immediately halts the Erlang runtime system.

monotonic_time()

Returns the current monotonic time in the `:native` time unit.

monotonic_time(unit)

Returns the current monotonic time in the given time unit.

no_halt()

Checks if the system will halt or not at the end of ARGV processing.

no_halt(boolean)

Marks if the system should halt or not at the end of ARGV processing.

os_time()

Returns the current operating system (OS) time.

os_time(unit)

Returns the current operating system (OS) time in the given time `unit`.

otp_release()

Returns the Erlang/OTP release number.

pid()

Returns the operating system PID for the current Erlang runtime system instance.

put_env(enum)

Sets multiple environment variables.

put_env(varname, value)

Sets an environment variable value.

restart()

Restarts all applications in the Erlang runtime system.

schedulers()

Returns the number of schedulers in the VM.

schedulers_online()

Returns the number of schedulers online in the VM.

stacktrace()

Deprecated mechanism to retrieve the last exception stacktrace.

stop(status \\ 0)

Carefully stops the Erlang runtime system.

system_time()

Returns the current system time in the `:native` time unit.

system_time(unit)

Returns the current system time in the given time unit.

time_offset()

Returns the current time offset between the Erlang VM monotonic time and the Erlang VM system time.

time_offset(unit)

Returns the current time offset between the Erlang VM monotonic time and the Erlang VM system time.

tmp_dir()

Writable temporary directory.

tmp_dir!()

Writable temporary directory, exception on error.

unique_integer(modifiers \\ [])

Generates and returns an integer that is unique in the current runtime instance.

user_home()

User home directory.

user_home!()

User home directory, exception on error.

version()

Elixir version information.

# Link to this section Types

Link to this type

# time_unit()

View Source

## Specs

    time_unit() ::
      :second | :millisecond | :microsecond | :nanosecond | pos_integer()

The time unit to be passed to functions like `monotonic_time/1` and others.

The `:second`, `:millisecond`, `:microsecond` and `:nanosecond` time units controls the return value of the functions that accept a time unit.

A time unit can also be a strictly positive integer. In this case, it represents the "parts per second": the time will be returned in `1 / parts_per_second` seconds. For example, using the `:millisecond` time unit is equivalent to using `1000` as the time unit (as the time will be returned in 1/1000 seconds - milliseconds).

# Link to this section Functions

Link to this function

# argv()

View Source

## Specs

    argv() :: [String.t()]

Lists command line arguments.

Returns the list of command line arguments passed to the program.

Link to this function

# argv(args)

View Source

## Specs

    argv([String.t()]) :: :ok

Modifies command line arguments.

Changes the list of command line arguments. Use it with caution, as it destroys any previous argv information.

Link to this function

# at_exit(fun)

View Source

## Specs

    at_exit((non_neg_integer() -> any())) :: :ok

Registers a program exit handler function.

Registers a function that will be invoked at the end of program execution. Useful for invoking a hook in "script" mode.

The handler always executes in a different process from the one it was registered in. As a consequence, any resources managed by the calling process (ETS tables, open files, and others) won't be available by the time the handler function is invoked.

The function must receive the exit status code as an argument.

Link to this function

# build_info()

View Source

## Specs

    build_info() :: %{
      build: String.t(),
      date: String.t(),
      revision: String.t(),
      version: String.t(),
      otp_release: String.t()
    }

Elixir build information.

Returns a map with the Elixir version, the Erlang/OTP release it was compiled with, a short Git revision hash and the date and time it was built.

Every value in the map is a string, and these are:

- `:build` - the Elixir version, short Git revision hash and Erlang/OTP release it was compiled with
- `:date` - a string representation of the ISO8601 date and time it was built
- `:otp_release` - OTP release it was compiled with
- `:revision` - short Git revision hash. If Git was not available at building time, it is set to `""`
- `:version` - the Elixir version

One should not rely on the specific formats returned by each of those fields. Instead one should use specialized functions, such as `version/0` to retrieve the Elixir version and `otp_release/0` to retrieve the Erlang/OTP release.

## Examples

    iex> System.build_info()
    %{
      build: "1.9.0-dev (772a00a0c) (compiled with Erlang/OTP 21)",
      date: "2018-12-24T01:09:21Z",
      otp_release: "21",
      revision: "772a00a0c",
      version: "1.9.0-dev"
    }

Link to this function

# cmd(command, args, opts \\ [])

View Source

## Specs

    cmd(binary(), [binary()], keyword()) ::
      {Collectable.t(), exit_status :: non_neg_integer()}

Executes the given `command` with `args`.

`command` is expected to be an executable available in PATH unless an absolute path is given.

`args` must be a list of binaries which the executable will receive as its arguments as is. This means that:

- environment variables will not be interpolated
- wildcard expansion will not happen (unless `Path.wildcard/2` is used explicitly)
- arguments do not need to be escaped or quoted for shell safety

This function returns a tuple containing the collected result and the command exit status.

Internally, this function uses a `Port` for interacting with the outside world. However, if you plan to run a long-running program, ports guarantee stdin/stdout devices will be closed but it does not automatically terminate the program. The documentation for the `Port` module describes this problem and possible solutions under the "Zombie processes" section.

## Examples

    iex> System.cmd("echo", ["hello"])
    {"hello\n", 0}

    iex> System.cmd("echo", ["hello"], env: [{"MIX_ENV", "test"}])
    {"hello\n", 0}

    iex> System.cmd("echo", ["hello"], into: IO.stream(:stdio, :line))
    hello
    {%IO.Stream{}, 0}

## Options

- `:into` - injects the result into the given collectable, defaults to `""`
- `:cd` - the directory to run the command in
- `:env` - an enumerable of tuples containing environment key-value as binary
- `:arg0` - sets the command arg0
- `:stderr_to_stdout` - redirects stderr to stdout when `true`
- `:parallelism` - when `true`, the VM will schedule port tasks to improve parallelism in the system. If set to `false`, the VM will try to perform commands immediately, improving latency at the expense of parallelism. The default can be set on system startup by passing the "+spp" argument to `--erl`.

## Error reasons

If invalid arguments are given, `ArgumentError` is raised by `System.cmd/3`. `System.cmd/3` also expects a strict set of options and will raise if unknown or invalid options are given.

Furthermore, `System.cmd/3` may fail with one of the POSIX reasons detailed below:

- `:system_limit` - all available ports in the Erlang emulator are in use

- `:enomem` - there was not enough memory to create the port

- `:eagain` - there are no more available operating system processes

- `:enametoolong` - the external command given was too long

- `:emfile` - there are no more available file descriptors (for the operating system process that the Erlang emulator runs in)

- `:enfile` - the file table is full (for the entire operating system)

- `:eacces` - the command does not point to an executable file

- `:enoent` - the command does not point to an existing file

## Shell commands

If you desire to execute a trusted command inside a shell, with pipes, redirecting and so on, please check `:os.cmd/1`.

Link to this function

# compiled_endianness()

View Source

## Specs

    compiled_endianness() :: :little | :big

Returns the endianness the system was compiled with.

Link to this function

# convert_time_unit(time, from_unit, to_unit)

View Source

## Specs

    convert_time_unit(integer(), time_unit() | :native, time_unit() | :native) ::
      integer()

Converts `time` from time unit `from_unit` to time unit `to_unit`.

The result is rounded via the floor function.

`convert_time_unit/3` accepts an additional time unit (other than the ones in the `t:time_unit/0` type) called `:native`. `:native` is the time unit used by the Erlang runtime system. It's determined when the runtime starts and stays the same until the runtime is stopped, but could differ the next time the runtime is started on the same machine. For this reason, you should use this function to convert `:native` time units to a predictable unit before you display them to humans.

To determine how many seconds the `:native` unit represents in your current runtime, you can can call this function to convert 1 second to the `:native` time unit: `System.convert_time_unit(1, :second, :native)`.

Link to this function

# cwd()

View Source
This function is deprecated. Use File.cwd/0 instead.

## Specs

    cwd() :: String.t() | nil

Current working directory.

Returns the current working directory or `nil` if one is not available.

Link to this function

# cwd!()

View Source
This function is deprecated. Use File.cwd!/0 instead.

## Specs

    cwd!() :: String.t()

Current working directory, exception on error.

Returns the current working directory or raises `RuntimeError`.

Link to this function

# delete_env(varname)

View Source

## Specs

    delete_env(String.t()) :: :ok

Deletes an environment variable.

Removes the variable `varname` from the environment.

Link to this function

# endianness()

View Source

## Specs

    endianness() :: :little | :big

Returns the endianness.

Link to this function

# fetch_env(varname)

View Source (since 1.9.0)

## Specs

    fetch_env(String.t()) :: {:ok, String.t()} | :error

Returns the value of the given environment variable or `:error` if not found.

If the environment variable `varname` is set, then `{:ok, value}` is returned where `value` is a string. If `varname` is not set, `:error` is returned.

## Examples

    iex> System.fetch_env("PORT")
    {:ok, "4000"}

    iex> System.fetch_env("NOT_SET")
    :error

Link to this function

# fetch_env!(varname)

View Source (since 1.9.0)

## Specs

    fetch_env!(String.t()) :: String.t()

Returns the value of the given environment variable or raises if not found.

Same as `get_env/1` but raises instead of returning `nil` when the variable is not set.

## Examples

    iex> System.fetch_env!("PORT")
    "4000"

    iex> System.fetch_env!("NOT_SET")
    ** (ArgumentError) could not fetch environment variable "NOT_SET" because it is not set

Link to this function

# find_executable(program)

View Source

## Specs

    find_executable(binary()) :: binary() | nil

Locates an executable on the system.

This function looks up an executable program given its name using the environment variable PATH on Windows and Unix-like operating systems. It also considers the proper executable extension for each operating system, so for Windows it will try to lookup files with `.com`, `.cmd` or similar extensions.

Link to this function

# get_env()

View Source

## Specs

    get_env() :: %{optional(String.t()) => String.t()}

Returns all system environment variables.

The returned value is a map containing name-value pairs. Variable names and their values are strings.

Link to this function

# get_env(varname, default \\ nil)

View Source (since 1.9.0)

## Specs

    get_env(String.t(), String.t() | nil) :: String.t() | nil

Returns the value of the given environment variable.

The returned value of the environment variable `varname` is a string. If the environment variable is not set, returns the string specified in `default` or `nil` if none is specified.

## Examples

    iex> System.get_env("PORT")
    "4000"

    iex> System.get_env("NOT_SET")
    nil

    iex> System.get_env("NOT_SET", "4001")
    "4001"

Link to this function

# get_pid()

View Source
This function is deprecated. Use System.pid/0 instead.

## Specs

    get_pid() :: binary()

Erlang VM process identifier.

Returns the process identifier of the current Erlang emulator in the format most commonly used by the operating system environment.

For more information, see `:os.getpid/0`.

Link to this function

# halt(status \\ 0)

View Source

## Specs

    halt(non_neg_integer() | binary() | :abort) :: no_return()

Immediately halts the Erlang runtime system.

Terminates the Erlang runtime system without properly shutting down applications and ports. Please see `stop/1` for a careful shutdown of the system.

`status` must be a non-negative integer, the atom `:abort` or a binary.

- If an integer, the runtime system exits with the integer value which is returned to the operating system.

- If `:abort`, the runtime system aborts producing a core dump, if that is enabled in the operating system.

- If a string, an Erlang crash dump is produced with status as slogan, and then the runtime system exits with status code 1.

Note that on many platforms, only the status codes 0-255 are supported by the operating system.

For more information, see `:erlang.halt/1`.

## Examples

    System.halt(0)
    System.halt(1)
    System.halt(:abort)

Link to this function

# monotonic_time()

View Source

## Specs

    monotonic_time() :: integer()

Returns the current monotonic time in the `:native` time unit.

This time is monotonically increasing and starts in an unspecified point in time.

Inlined by the compiler.

Link to this function

# monotonic_time(unit)

View Source

## Specs

    monotonic_time(time_unit()) :: integer()

Returns the current monotonic time in the given time unit.

This time is monotonically increasing and starts in an unspecified point in time.

Link to this function

# no_halt()

View Source (since 1.9.0)

## Specs

    no_halt() :: boolean()

Checks if the system will halt or not at the end of ARGV processing.

Link to this function

# no_halt(boolean)

View Source (since 1.9.0)

## Specs

    no_halt(boolean()) :: :ok

Marks if the system should halt or not at the end of ARGV processing.

Link to this function

# os_time()

View Source

## Specs

    os_time() :: integer()

Returns the current operating system (OS) time.

The result is returned in the `:native` time unit.

This time may be adjusted forwards or backwards in time with no limitation and is not monotonic.

Inlined by the compiler.

Link to this function

# os_time(unit)

View Source

## Specs

    os_time(time_unit()) :: integer()

Returns the current operating system (OS) time in the given time `unit`.

This time may be adjusted forwards or backwards in time with no limitation and is not monotonic.

Link to this function

# otp_release()

View Source

## Specs

    otp_release() :: String.t()

Returns the Erlang/OTP release number.

Link to this function

# pid()

View Source (since 1.9.0)

## Specs

    pid() :: String.t()

Returns the operating system PID for the current Erlang runtime system instance.

Returns a string containing the (usually) numerical identifier for a process. On Unix-like operating systems, this is typically the return value of the `getpid()` system call. On Windows, the process ID as returned by the `GetCurrentProcessId()` system call is used.

## Examples

    System.pid()

Link to this function

# put_env(enum)

View Source

## Specs

    put_env(Enumerable.t()) :: :ok

Sets multiple environment variables.

Sets a new value for each environment variable corresponding to each `{key, value}` pair in `enum`.

Link to this function

# put_env(varname, value)

View Source

## Specs

    put_env(binary(), binary()) :: :ok

Sets an environment variable value.

Sets a new `value` for the environment variable `varname`.

Link to this function

# restart()

View Source (since 1.9.0)

## Specs

    restart() :: :ok

Restarts all applications in the Erlang runtime system.

All applications are taken down smoothly, all code is unloaded, and all ports are closed before the system starts all applications once again.

## Examples

    System.restart()

Link to this function

# schedulers()

View Source

## Specs

    schedulers() :: pos_integer()

Returns the number of schedulers in the VM.

Link to this function

# schedulers_online()

View Source

## Specs

    schedulers_online() :: pos_integer()

Returns the number of schedulers online in the VM.

Link to this function

# stacktrace()

View Source

Deprecated mechanism to retrieve the last exception stacktrace.

Accessing the stacktrace outside of a rescue/catch is deprecated. If you want to support only Elixir v1.7+, you must access `__STACKTRACE__/0` inside a rescue/catch. If you want to support earlier Elixir versions, move `System.stacktrace/0` inside a rescue/catch.

Note that the Erlang VM (and therefore this function) does not return the current stacktrace but rather the stacktrace of the latest exception. To retrieve the stacktrace of the current process, use `Process.info(self(), :current_stacktrace)` instead.

Link to this function

# stop(status \\ 0)

View Source (since 1.5.0)

## Specs

    stop(non_neg_integer() | binary()) :: no_return()

Carefully stops the Erlang runtime system.

All applications are taken down smoothly, all code is unloaded, and all ports are closed before the system terminates by calling `halt/1`.

`status` must be a non-negative integer value which is returned by the runtime system to the operating system.

Note that on many platforms, only the status codes 0-255 are supported by the operating system.

## Examples

    System.stop(0)
    System.stop(1)

Link to this function

# system_time()

View Source

## Specs

    system_time() :: integer()

Returns the current system time in the `:native` time unit.

It is the VM view of the `os_time/0`. They may not match in case of time warps although the VM works towards aligning them. This time is not monotonic.

Inlined by the compiler.

Link to this function

# system_time(unit)

View Source

## Specs

    system_time(time_unit()) :: integer()

Returns the current system time in the given time unit.

It is the VM view of the `os_time/0`. They may not match in case of time warps although the VM works towards aligning them. This time is not monotonic.

Link to this function

# time_offset()

View Source

## Specs

    time_offset() :: integer()

Returns the current time offset between the Erlang VM monotonic time and the Erlang VM system time.

The result is returned in the `:native` time unit.

See `time_offset/1` for more information.

Inlined by the compiler.

Link to this function

# time_offset(unit)

View Source

## Specs

    time_offset(time_unit()) :: integer()

Returns the current time offset between the Erlang VM monotonic time and the Erlang VM system time.

The result is returned in the given time unit `unit`. The returned offset, added to an Erlang monotonic time (for instance, one obtained with `monotonic_time/1`), gives the Erlang system time that corresponds to that monotonic time.

Link to this function

# tmp_dir()

View Source

## Specs

    tmp_dir() :: String.t() | nil

Writable temporary directory.

Returns a writable temporary directory. Searches for directories in the following order:

1. the directory named by the TMPDIR environment variable
2. the directory named by the TEMP environment variable
3. the directory named by the TMP environment variable
4. `C:\TMP` on Windows or `/tmp` on Unix-like operating systems
5. as a last resort, the current working directory

Returns `nil` if none of the above are writable.

Link to this function

# tmp_dir!()

View Source

## Specs

    tmp_dir!() :: String.t()

Writable temporary directory, exception on error.

Same as `tmp_dir/0` but raises `RuntimeError` instead of returning `nil` if no temp dir is set.

Link to this function

# unique_integer(modifiers \\ [])

View Source

## Specs

    unique_integer([:positive | :monotonic]) :: integer()

Generates and returns an integer that is unique in the current runtime instance.

"Unique" means that this function, called with the same list of `modifiers`, will never return the same integer more than once on the current runtime instance.

If `modifiers` is `[]`, then a unique integer (that can be positive or negative) is returned. Other modifiers can be passed to change the properties of the returned integer:

- `:positive` - the returned integer is guaranteed to be positive.
- `:monotonic` - the returned integer is monotonically increasing. This means that, on the same runtime instance (but even on different processes), integers returned using the `:monotonic` modifier will always be strictly less than integers returned by successive calls with the `:monotonic` modifier.

All modifiers listed above can be combined; repeated modifiers in `modifiers` will be ignored.

Inlined by the compiler.

Link to this function

# user_home()

View Source

## Specs

    user_home() :: String.t() | nil

User home directory.

Returns the user home directory (platform independent).

Link to this function

# user_home!()

View Source

## Specs

    user_home!() :: String.t()

User home directory, exception on error.

Same as `user_home/0` but raises `RuntimeError` instead of returning `nil` if no user home is set.

Link to this function

# version()

View Source

## Specs

    version() :: String.t()

Elixir version information.

Returns Elixir's version as binary.