os(3erl)

✨ os (3erl) ✨

okay bestie so this is the os module from Erlang β€” Operating system-specific functions β€” straight out of the Erlang Module Definition. grab a lil snack, we're getting into it πŸ“


πŸ’… NAME

os β€” operating system-specific functions. that's it, that's the vibe.


🌸 DESCRIPTION

so here's the tea πŸ«– β€” the functions in this module are operating system-specific. like, they're literally built around the OS you're on.

⚠️ bestie listen to me: careless use of these functions results in programs that will only run on a specific platform. like, your code will be that one friend who refuses to leave the house. 😭

on the other hand β€” and this is the slay part β€” with careful use, these functions can be of help in enabling a program to run on most platforms. icon behaviour honestly πŸ‘‘


πŸŽ€ 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. so read the next part, i'm begging you πŸ™


πŸ¦‹ 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. like it's the main character and everyone else has to wait πŸ’…

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. that's the whole rule, no cap.

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 separates environment variable name (on the left) from environment variable value (on the right). so it's like NAME=value, left side is the name, right side is the value. the = is literally the divider πŸͺ„

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. once again, zero is not welcome here 🚫

os_command_opts() = #{max_size => integer() >= 0 | infinity}

options for os:cmd/2. we have exactly one baddie in this map:

  • max_size β€” the maximum size of the data returned by the os:cmd/2 call. see the os:cmd/2 documentation for more details. it's giving "i set boundaries" energy πŸ›‘βœ¨

part 2 is coming, don't go anywhere bestie πŸ§šπŸ’œ

✨ EXPORTS ✨


πŸ’… cmd(Command) -> string() / cmd(Command, Options) -> string()

Types:

Command = os_command()
Options = os_command_opts()

okay so bestie, cmd runs your Command inside a command shell of whatever OS you're on, grabs the standard output, and hands it back to you as a string. that's it, that's the whole vibe πŸŽ€

Examples, because we love a demo:

LsOut = os:cmd("ls"), % on unix platform
DirOut = os:cmd("dir"), % on Win32 platform

⚠️ small but real heads-up: sometimes the standard output of a command when it's called from another program (hi, os:cmd/1) can differ from what you'd see calling that same command straight up from an OS command shell. not a bug, just how it be.

os:cmd/2 showed up in kernel-5.5 (OTP-20.2.1) and it lets you pass an options map as the second argument to control how os:cmd behaves. the possible options are:

  • max_size β€” the maximum size of the data returned by the os:cmd call. this is a safety feature and you should use it when the command you're running can return a very large result, possibly an infinite one. lowkey essential. πŸ”₯
> 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]

🌸 env() -> [{env_var_name(), env_var_value()}]

returns a list of all the environment variables. each one comes as a tuple {VarName,Value} where VarName is the name of the variable and Value is its value. cute, tidy, 2-tuple format, we stan πŸ’–

if Unicode filename encoding is in effect (peep the erl manual page), the strings can contain characters with codepoints > 255.


πŸ¦‹ find_executable(Name) -> Filename | false / find_executable(Name, Path) -> Filename | false

Types:

Name = Path = Filename = string()

these two look up an executable program with the specified name and a search path, in the same way the underlying OS does it. find_executable/1 uses the current execution path (that is, the environment variable PATH on Unix and Windows).

Path, if you specify it, has 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 cap, that's the whole thing ✨


πŸŽ€ getenv() -> [env_var_name_value()]

returns a list of all environment variables, each one 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. just saying πŸ‘€

πŸ’œ getenv(VarName) -> Value | false

Types:

VarName = env_var_name()
Value = env_var_value()

returns the Value of the environment variable VarName, or false if that environment variable is undefined. classic yes/no energy.

if Unicode filename encoding is in effect (see the erl manual page), the strings VarName and Value can contain characters with codepoints > 255.


πŸ“ getenv(VarName, DefaultValue) -> Value

Types:

VarName = env_var_name()
DefaultValue = Value = env_var_value()

returns the Value of the environment variable VarName, or DefaultValue if the environment variable is undefined. it's giving "built-in fallback, main character energy" πŸ’…

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

Types:

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() system call. on Windows, the process id as returned by the GetCurrentProcessId() system call is used. iykyk 😌


🌈 putenv(VarName, Value) -> true

Types:

VarName = env_var_name()
Value = env_var_value()

sets a new Value for environment variable VarName. icon behaviour, honestly.

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. slay across platforms 🫢


⭐ set_signal(Signal, Option) -> ok

Types:

Signal =
    sighup | sigquit | sigabrt | sigalrm | sigterm | sigusr1 |
    sigusr2 | sigchld | sigstop | sigtstp
Option = default | handle | ignore

enables or disables OS signals. each signal can 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 notify erl_signal_server when it is received by the Erlang runtime system. it's giving "someone's watching, bestie" πŸ‘‘

πŸ”₯ system_time() -> integer()

returns the current OS system time in native time unit.

note: this time is not a monotonically increasing time. just so we're clear πŸ’€

🌸 system_time(Unit) -> integer()

Types:

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.

πŸŽ€ timestamp() -> Timestamp

Types:

Timestamp = erlang:timestamp()
  Timestamp = {MegaSecs, Secs, MicroSecs}

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. highkey useful ✨

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),
    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

OS system time can also be retrieved by system_time/0 and system_time/1. options, options everywhere πŸ’–


πŸ¦‹ perf_counter() -> Counter

Types:

Counter = integer()

returns the current performance counter value in perf_counter time unit. this is a highly optimized call that might not be traceable. sneaky fast, love that for us ⚑


🌈 perf_counter(Unit) -> integer()

Types:

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 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.

1> T1 = os:perf_counter(1000),receive after 10000 -> ok end,T2 = os:perf_counter(1000).
176525861
2> T2 - T1.
10004

look at that math go πŸ˜­πŸ’…


🧚 type() -> {Osfamily, Osname}

Types:

Osfamily = unix | win32
Osname = atom()

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 is sunos.

on Windows, Osname is nt.

note: 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. seriously bestie, portability is the vibe 🫢

πŸ’œ unsetenv(VarName) -> true

Types:

VarName = env_var_name()

deletes the environment variable VarName. gone, reduced to atoms, periodt πŸ’€

if Unicode filename encoding is in effect (see the erl manual page), the string VarName can contain characters with codepoints > 255.


🌸 version() -> VersionString | {Major, Minor, Release}

Types:

VersionString = string()
Major = Minor = Release = integer() >= 0

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. some systems just gotta be extra πŸ™ˆ

note: think twice before using this function. if you still need to use it, always call os:type() first. always. no cap.

and that's the whole page, bestie β€” every function, every flag, every note, nothing skipped πŸ’– this gorgeous little man page comes to you courtesy of Ericsson AB, sitting pretty at kernel 8.5.4.2 in the os(3erl) section β€” go forth and os:cmd responsibly, mwah πŸŽ€βœ¨πŸ¦‹

πŸ“¦ where this page comes from