os(3)
πΈ os(3) β Erlang Module Definition πΈ
okay bestie, gather round, because this module is literally the Erlang-to-operating-system group chat π
It's os, and it's the Erlang module definition for all the functions that go talk to your actual OS.
β¨ NAME β¨
os β operating system-specific functions. yes that's it, that's the whole vibe π«Ά
β¨ DESCRIPTION β¨
so the functions in this module are operating system-specific. and that's the tea, because if you use them carelessly you end up with a program that only runs on one specific platform π but flip it around β use them carefully and they're genuinely iconic for helping a program run on, like, most platforms π
NOTE: the functions in this module will raise a badarg exception if their arguments contain invalid characters according to the description in the "Data Types" section. not me being strict about it, the module is just like that π
β¨ DATA TYPES β¨
πΈ env_var_name() :: nonempty_string().
a string containing valid characters on the specific OS for environment variable names, using file:native_name_encoding() encoding.
null characters (integer value zero) are not allowed. on Unix, = characters are not allowed. on Windows, a = character is only allowed as the very first character in the string. periodt π
πΈ env_var_name_value() :: nonempty_string().
assuming that environment variables have been correctly set, this is a string containing valid characters on the specific OS for environment variable names and values, using file:native_name_encoding() encoding.
the first = characters appearing in the string separate the environment variable name (on the left) from the environment variable value (on the right). so like, NAME=VALUE, and that first = is the divider, iykyk β¨
πΈ env_var_value() :: string().
a string containing valid characters on the specific OS for environment variable values, using file:native_name_encoding() encoding.
null characters (integer value zero) are not allowed. sorry bestie, zero is banned π«
πΈ os_command() :: atom() | io_lib:chars().
all characters need to be valid characters on the specific OS, using file:native_name_encoding() encoding. null characters (integer value zero) are not allowed. again, no zeros, no cap π§
πΈ os_command_opts() ::
#{max_size => non_neg_integer() | infinity,
exception_on_failure => boolean()}.
options for os:cmd/2. let's break it down:
max_sizeβ the maximum size of the data returned by theos:cmd/2call. see theos:cmd/2documentation for more details. honestly a safety feature, lowkey underrated.
Since OTP 20.2.3
exception_on_failureβ if set totrue,cmd/2will throw an error exception if the command exits with a non-zero exit code. very "we don't tolerate failure in this house" of it π₯
Since OTP 28.0
β¨ FUNCTIONS β¨
π cmd(Command, Options) -> string()
when Command :: os_command(), Options :: os_command_opts().
executes Command in a command shell of the target OS, captures the standard output and standard error of the command, and returns this result as a string. one string, both streams, iconic behavior π
examples:
LsOut = os:cmd("ls"), % on unix platform
DirOut = os:cmd("dir"), % on Win32 platform
notice that in some cases, the standard output of a command when called from another program can differ, compared with the standard output of the command when called directly from an OS command shell. so don't come for me when ls looks different, bestie π
the possible options are:
π max_size
the maximum size of the data returned by the os:cmd/2 call. this option is a safety feature that should be used when the command executed can return a very large, possibly infinite, result. yes, cat /dev/zero is exactly the kind of chaos we're protecting you from π«Ά
example:
> os:cmd("cat /dev/zero", #{ max_size => 20 }).
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Since OTP 20.2.3
π exception_on_failure
if set to true, os:cmd/2 will throw an error exception if the command exits with a non-zero exit code. the exception reason looks like this: {command_failed, ResultBeforeFailure, ExitCode} where ResultBeforeFailure is the result written to stdout by the command before the error happened and ExitCode is the exit code from the command.
example:
> catch os:cmd("echo hello && exit 123", #{ exception_on_failure => true }).
{'EXIT',{{command_failed,"hello\n",123},
[{os,cmd,2,[{file,"os.erl"},{line,579}]},
Since OTP 28.0
the command shell can be set using the kernel configuration parameter β by default the shell is detected upon system startup. so the vibe is configurable, love that for us β¨
π env() -> [{env_var_name(), env_var_value()}].
returns a list of all environment variables. each environment variable is expressed as a tuple {VarName,Value}, where VarName is the name of the variable and Value its value. nice and tidy, 2-tuple format, chef's kiss π
if Unicode filename encoding is in effect (see the erl manual page), the strings can contain characters with codepoints > 255. slay π¦
π find_executable(Name) -> Filename | false
when Name :: string(), Filename :: string().
equivalent to find_executable(Name, Path) where Path is the current execution path (that is, the environment variable PATH on Unix and Windows). so it's the "just look in PATH, bestie" version πΈ
π find_executable(Name, Path) -> Filename | false
when
Name :: string(),
Path :: string(),
Filename :: string().
look up an executable program, with the specified name and a search path, in the same way as the underlying OS. it's matching the OS's own energy, fr fr π
Path 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. no program, no problem, just false π
π getenv() -> [env_var_name_value()].
returns a list of all environment variables. 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 filename encoding is in effect (see the erl manual page), the strings can contain characters with codepoints > 255.
consider using env/0 for a nicer 2-tuple format. like, just saying bestie, the tuple version is right there and it's cuter π
π getenv(VarName) -> Value | false
when VarName :: env_var_name(), Value :: env_var_value().
returns the Value of the environment variable 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. highkey inclusive of all the characters π
π getenv(VarName, DefaultValue) -> Value
when
VarName :: env_var_name(),
DefaultValue :: env_var_value(),
Value :: env_var_value().
returns the Value of the environment variable VarName, or DefaultValue if the environment variable is undefined. so you always get something back, no false jumpscare, love that for you π«Ά
if Unicode filename encoding is in effect (see the erl manual page), the strings VarName and Value can contain characters with codepoints > 255.
π getpid() -> Value
when Value :: string().
returns the process identifier of the current Erlang emulator 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/0system call. π§ - on Windows, the process id as returned by the
GetCurrentProcessId()system call is used. πͺ
π perf_counter() -> Counter
when Counter :: integer().
returns the current performance counter value in perf_counter time unit. this is a highly optimized call that might not be traceable. it's giving "too fast to be observed" β‘
π perf_counter(Unit) -> integer()
when Unit :: erlang:time_unit().
returns a performance counter that can be used as a very fast and 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 will be converted to the resolution passed as an argument. so like, probably monotonic, but no promises, bestie π
1> T1 = os:perf_counter(1000),receive after 10000 -> ok end,T2 = os:perf_counter(1000).
176525861
2> T2 - T1.
10004
π putenv(VarName, Value) -> true
when VarName :: env_var_name(), Value :: env_var_value().
sets a new Value for environment variable VarName. setting the vibe, literally π
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. platform-specific but make it fashion β¨
π set_signal(Signal, Option) -> ok
when
Signal ::
sighup | sigquit | sigabrt | sigalrm |
sigterm | sigusr1 | sigusr2 | sigchld |
sigstop | sigtstp | sigcont | sigwinch |
siginfo,
Option :: default | handle | ignore.
enables or disables OS signals. so much power in one little function, ngl π
each signal may be set to one of the following options:
ignoreβ this signal will be ignored. not today, signal πdefaultβ this signal will use the default signal handler for the operating system.handleβ this signal will notifyerl_signal_serverwhen it is received by the Erlang runtime system. π£
π system_time() -> integer().
returns the current OS system time in native time unit.
NOTE: this time is not a monotonically increasing time. so don't go building your whole timeline on it, bestie π
π system_time(Unit) -> integer()
when Unit :: erlang:time_unit().
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(), native, Unit).
NOTE: this time is not a monotonically increasing time. same warning, same drama π
π timestamp() -> Timestamp
when Timestamp :: erlang:timestamp().
returns the current OS system time 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. high-res timestamps that match the OS? that's main character energy, periodt π
(part 1 done bestie, stay tuned, there's more π)
...and if you wanna see that vibe in action, here's a cute lil' example that formats a string in the format "DD Mon YYYY HH:MM:SS.mmmmmm", where DD is the day of the 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),
Mstr = element(Month,{"Jan","Feb","Mar","Apr","May","Jun","Jul",
"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]).
This module can be used as follows:
1> io:format("~s~n",[print_time:format_utc_timestamp()]).
29 Apr 2009 9:55:30.051711
Also bestie, OS system time can be retrieved by system_time/0 and system_time/1 too. Options, options π
π type() -> {Osfamily, Osname}
when Osfamily :: unix | win32, Osname :: atom().
Returns the Osfamily and, in some cases, the Osname of the current OS. So you get the family always, and the name only when it's a name kind of situation. π
On Unix, Osname has the same value as uname -s returns, but in lower case. For example, on Solaris 1 and 2, it is sunos.
On Windows, Osname is nt.
NOTE: Think twice before using this function. Use modulefilenameif you want to inspect or build filenames in a portable way. Avoid matching on atomOsname.
No cap, that note is the whole plot twist. Use filename for filenames, and don't pattern-match on Osname, okay? π«Ά
π¦ unsetenv(VarName) -> true
when VarName :: env_var_name().
Deletes the environment variable VarName.
If Unicode filename encoding is in effect (see the erl manual page), the string VarName can contain characters with codepoints > 255. So like, fancy letters are allowed, slay. β¨
π version() -> VersionString | {Major, Minor, Release}
when
VersionString :: string(),
Major :: non_neg_integer(),
Minor :: non_neg_integer(),
Release :: non_neg_integer().
Returns the OS version. On most systems, this function returns a tuple, but a string is returned instead if the system has versions that cannot be expressed as three numbers. It's giving "sometimes a tuple, sometimes a string," and honestly that's just how it is. π
NOTE: Think twice before using this function. If you still need to use it, always call os:type() first.
Like, call os:type() first, bestie. Always. Periodt. π
And that's the whole page, you made it to the end ππ huge main character energy for reading all of os(3). This gorgeous piece of documentation ships with Ericsson AB's kernel 11.0.3 release, and it's the os(3) manual page. Go forth and query your operating system responsibly, iykyk. π
πΈ
π¦ where this page comes from
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms