sys(3)
π sys(3) π
okay so this is sys, straight out of the Erlang Module Definition manual, section 3, and bestie it is so much more than it looks. sit down, grab a strawberry drink π, we're doing this.
πΈ NAME πΈ
sys β a functional interface to system messages. iconic, brief, slays.
β¨ DESCRIPTION β¨
This module is where the functions live for sending system messages (the ones programs use) and the messages used for debugging purposes. two flavours, one module, no notes.
There's also functions used for the implementation of processes, and those processes are also expected to get what system messages are β think debug messages, code change, all that lore. If you're implementing system message support for a process you have to use these functions β either directly, or via the standard behaviours like gen_server. no skipping, fr fr.
The default time-out is 5000 ms, unless something else is specified. timeout is literally just how long we wait for the process to answer a request. And if it never answers? The function evaluates exit({timeout, {M, F, A}}). π ghosted by a process, devastating.
These functions make references to a debug structure. The debug structure is a list of dbg_opt/0 β an internal data type used by the function handle_system_msg/6. If it's an empty list, literally no debugging happens. zero. nada. she's not doing it.
π¨ System Messages
So if a process isn't implemented as one of the standard behaviours, it still has to understand system messages. non-negotiable. There are three of them and you need all three:
- Plain system messages. These arrive as
{system, From, Msg}. The receiving process module does not interpret the content or the meaning of this message β she just takes it. When a system message lands, the functionhandle_system_msg/6is called to handle the request. - Shutdown messages. If the process traps exits, it must be able to handle a shutdown request from its parent, the supervisor. The message
{'EXIT', Parent, Reason}coming from the parent is an order to terminate. When it arrives, the process must terminate β normally with the sameReasonasParent. that's the parent saying "we're done here" and you listen. - Module-change messages. If the modules used to implement the process change dynamically at runtime, the process has to understand one more message.
gen_eventprocesses are the classic example. The message is{_Label, {From, Ref}, get_modules}, and the reply to it isFrom ! {Ref, Modules}, whereModulesis a list of the currently active modules in the process.
This message is used by the release handler to find which processes execute a certain module. Later on, the process can be suspended and ordered to do a code change for one of its modules. it's giving scheduled maintenance vibes.
π System Events
When you debug a process using this module's functions, the process generates system_events, which then get treated inside the debug function. Example: trace formats the system events out to the terminal. pretty.
There are four predefined system events used when a process receives or sends a message. A process can also define its own system events. And it's always up to the process itself to format these events. your events, your formatting, your rules β¨.
π DATA TYPES π
dbg_fun() ::
fun((FuncState :: _, Event :: system_event(), ProcState :: _)
->
done | (NewFuncState :: _)).
-opaque dbg_opt()β see the introduction of this manual page (yes, the one right up there, we already spilled that tea π).
debug_option() ::
trace | log |
{log, N :: pos_integer()} |
statistics |
{log_to_file, FileName :: file:name()} |
{install,
{Func :: dbg_fun(), FuncState :: term()} |
{FuncId :: term(), Func :: dbg_fun(), FuncState :: term()}}.
format_fun() ::
fun((Device :: io:device() | file:io_device(),
Event :: system_event(),
Extra :: term()) ->
any()).
name() ::
pid() | atom() | {global, term()} | {via, module(), term()}.
system_event() ::
{in, Msg :: _} |
{in, Msg :: _, State :: _} |
{out, Msg :: _, To :: _} |
{out, Msg :: _, To :: _, State :: _} |
{noreply, State :: _} |
{continue, Continuation :: _} |
{postpone, Event :: _, State :: _, NextState :: _} |
{consume, Event :: _, State :: _, NextState :: _} |
{start_timer, Action :: _, State :: _} |
{insert_timeout, Event :: _, State :: _} |
{enter, Module :: module(), State :: _} |
{module, Module :: module(), State :: _} |
{terminate, Reason :: _, State :: _} |
term().
π Debug events produced by gen_server, gen_statem and gen_event
okay here's the whole roster, one by one, no skipping:
{in,Msg}β is produced bygen_serverandgen_eventwhen the messageMsgarrives. hi bestie, you got mail.{in,Msg,State}β is produced bygen_statemwhen the messageMsgarrives in stateState. Forgen_statem, theMsgterm is an{EventType,EventContent}tuple.{out,Msg,To}β is produced bygen_statemwhen the replyMsgis sent back toToby returning a{reply,To,Msg}action from the callback module.Tois of the same type as the first argument togen_statem:reply/2.{out,Msg,To,State}β is produced bygen_serverwhen the replyMsgis sent back toToby returning a{reply,...}tuple from the callback module.Tois of the same type as the first argument togen_server:reply/2.Stateis the new server state.{noreply,State}β is produced bygen_serverwhen a{noreply,...}tuple is returned from the callback module.Stateis the new server state. leaving them on read, respectfully.{continue,Continuation}β is produced bygen_serverwhen a{continue,Continuation}tuple is returned from the callback module.{postpone,Event,State,NextState}β is produced bygen_statemwhen the messageEventis postponed in stateState.NextStateis the new state.Eventis an{EventType,EventContent}tuple.{consume,Event,State,NextState}β is produced bygen_statemwhen the messageEventis consumed in stateState.NextStateis the new state.Eventis an{EventType,EventContent}tuple.{start_timer,Action,State}β is produced bygen_statemwhen the actionActionstarts a timer in stateState. β°{insert_timeout,Event,State}β is produced bygen_statemwhen a timeout zero action inserts eventEventin stateState.Eventis an{EventType,EventContent}tuple.{enter,Module,State}β is produced bygen_statemwhen moduleModuleenters the first stateState.{module,Module,State}β is produced bygen_statemwhen setting moduleModulein stateState.{terminate,Reason,State}β is produced bygen_statemwhen it terminates with reasonReasonin stateState. and that's the season finale π
π₯ FUNCTIONS π₯
π¦ change_code(Name, Module, OldVsn, Extra, Timeout) -> ok | {error, Reason}
change_code(Name, Module, OldVsn, Extra, Timeout) ->
ok | {error, Reason}
when
Name :: name(),
Module :: module(),
OldVsn :: undefined | term(),
Extra :: term(),
Timeout :: timeout(),
Reason :: term().
Tells the process to change code. π
The process must be suspended to handle this message β like, it has to be paused, that's the deal. The argument Extra is reserved for each process to use as its own. The function Module:system_code_change/4 gets called. OldVsn is the old version of the Module.
π¦ debug_options([Opt :: debug_option()]) -> [dbg_opt()]
Can be used by a process that initiates a debug structure from a list of options. The values of argument Opt are the same as for the corresponding functions.
π¦ get_debug(Item, Debug, Default) -> term()
get_debug(Item, Debug, Default) -> term()
when
Item :: log | statistics,
Debug :: [dbg_opt()],
Default :: term().
β οΈ Deprecated:sys:get_debug/3is deprecated; incorrectly documented and only for internal use. Can often be replaced withsys:get_log/1.
Gets the data associated with a debug option. Default is returned if Item is not found. Can be used by the process to retrieve debug data for printing before it terminates.
π¦ get_log(Debug) -> [system_event()]
get_log(Debug) -> [system_event()] when Debug :: [dbg_opt()].
Returns the logged system events in the debug structure, that is the last argument to handle_debug/4.
π¦ get_state(Name, Timeout) -> State
get_state(Name, Timeout) -> State
when
Name :: name(),
Timeout :: timeout(),
State :: term().
Gets the state of the process. π«Ά
π NOTE: These functions are intended only to help with debugging. They are provided for convenience, allowing developers to avoid having to create their own state extraction functions and also avoid having to interactively extract the state from the return values ofget_status/1orget_status/2while debugging.
The value of State varies for different types of processes, as follows:
- For a
gen_serverprocess, the returnedStateis the state of the callback module. - For a
gen_statemprocess,Stateis the tuple{CurrentState,CurrentData}. - For a
gen_eventprocess,Stateis a list of tuples, where each tuple corresponds to an event handler registered in the process and contains{Module, Id, HandlerState}, as follows:Moduleβ the module name of the event handler.Idβ the ID of the handler (which isfalseif it was registered without an ID).HandlerStateβ the state of the handler.
If the callback module exports a function system_get_state/1, it is called in the target process to get its state. Its argument is the same as the Misc value returned by get_status/1,2, and function Module:system_get_state/1 is expected to extract the state of the callback module from it. Function system_get_state/1 must return {ok, State}, where State is the state of the callback module.
If the callback module does not export a system_get_state/1 function, get_state/1,2 assumes that the Misc value is the state of the callback module and returns it directly instead. easy, low-effort, still valid.
If the callback module's system_get_state/1 function crashes or throws an exception, the caller exits with error {callback_failed, {Module, system_get_state}, {Class, Reason}}, where Module is the name of the callback module and Class and Reason indicate details of the exception. π that's a whole dramatic exit.
and that's not even all of the FUNCTIONS, bestie β there's more coming, don't go anywhere π
okay so system_get_state/1? It's literally mainly for user-defined behaviors and modules that implement OTP special processes. The gen_server, gen_statem, and gen_event OTP behavior modules export this function, so callback modules for those behaviors need not to supply their own. no cap. π
want more info about a process, including its state? bestie, see get_status/1 and get_status/2. π«Ά
β¨ get_status/2 β¨
get_status(Name, Timeout) -> Status
when
Name :: name(),
Timeout :: timeout(),
Status ::
{status,
Pid :: pid(),
{module, Module :: module()},
[SItem]},
SItem ::
(PDict :: [{Key :: term(), Value ::
term()}]) |
(SysState :: running | suspended) |
(Parent :: pid()) |
(Dbg :: [dbg_opt()]) |
(Misc :: term()).
This one gets the status of the process. slay.
The value of Misc varies for different types of processes, for example:
gen_serverprocess returns the state of the callback module.gen_statemprocess returns information, such as its current state name and state data.gen_eventprocess returns information about each of its registered handlers.- bare
sysprocess returns the value passed asMisctohandle_system_msg/6.
Callback modules for gen_server, gen_statem, and gen_event can also change the value of Misc by exporting a function format_status/1, which contributes module-specific information. For details, see gen_server:format_status/1, gen_statem:format_status/1, and gen_event:format_status/1. iconic π
β¨ handle_debug/4 β¨
handle_debug(Debug, FormFunc, Extra, Event) -> [dbg_opt()]
when
Debug :: [dbg_opt()],
FormFunc :: format_fun(),
Extra :: term(),
Event :: system_event().
This function is called by a process when it generates a system event. FormFunc is a formatting function, called as FormFunc(Device, Event, Extra) to print the events, which is necessary if tracing is activated. Extra is any extra information that the process needs in the format function, for example, the process name. π
β¨ handle_system_msg/6 β¨
handle_system_msg(Msg, From, Parent, Module, Debug, Misc) ->
no_return()
when
Msg :: term(),
From :: {pid(), Tag :: _},
Parent :: pid(),
Module :: module(),
Debug :: [dbg_opt()],
Misc :: term().
This function is used by a process module to take care of system messages. The process receives a {system, From, Msg} message and passes Msg and From to this function.
This function never returns. It calls either of the following functions:
Module:system_continue(Parent, NDebug, Misc), where the process continues the execution.Module:system_terminate(Reason, Parent, Debug, Misc), if the process is to terminate.
Module must export the following:
system_continue/3system_terminate/4system_code_change/4system_get_state/1system_replace_state/2
Argument Misc can be used to save internal data in a process, for example, its state. It is sent to Module:system_continue/3 or Module:system_terminate/4. π¦
β¨ install/3 β¨
install(Name, FuncSpec, Timeout) -> ok
when
Name :: name(),
FuncSpec ::
{Func, FuncState} | {FuncId, Func, FuncState},
FuncId :: term(),
Func :: dbg_fun(),
FuncState :: term(),
Timeout :: timeout().
Enables installation of alternative debug functions. An example of such a function is a trigger, a function that waits for some special event and performs some action when the event is generated. For example, turning on low-level tracing.
Func is called whenever a system event is generated. This function is to return done, or a new Func state. In the first case, the function is removed. It is also removed if the function fails. If one debug function should be installed more times, a unique FuncId must be specified for each installation. π
β¨ log/3 β¨
log(Name, Flag, Timeout) -> ok | {ok, [system_event()]}
when
Name :: name(),
Flag ::
true |
{true, N :: pos_integer()} |
false | get | print,
Timeout :: timeout().
Turns the logging of system events on or off. If on, a maximum of N events are kept in the debug structure (default is 10).
If Flag is get, a list of all logged events is returned.
If Flag is print, the logged events are printed to standard_io.
The events are formatted with a function that is defined by the process that generated the event (with a call to handle_debug/4). periodt π
β¨ log_to_file/3 β¨
log_to_file(Name, Flag, Timeout) -> ok | {error, open_file}
when
Name :: name(),
Flag :: (FileName :: string()) | false,
Timeout :: timeout().
Enables or disables the logging of all system events in text format to the file. The events are formatted with a function that is defined by the process that generated the event (with a call to handle_debug/4). The file is opened with encoding UTF-8. π
β¨ no_debug/3 β¨
no_debug(Name, Timeout) -> ok
when Name :: name(), Timeout :: timeout().
Turns off all debugging for the process. This includes functions that are installed explicitly with function install/2,3, for example, triggers. π
β¨ print_log/1 β¨
print_log(Debug) -> ok when Debug :: [dbg_opt()].
Prints the logged system events in the debug structure, using FormFunc as defined when the event was generated by a call to handle_debug/4. β¨
β¨ remove/3 β¨
remove(Name, Func | FuncId, Timeout) -> ok
when
Name :: name(),
Func :: dbg_fun(),
FuncId :: term(),
Timeout :: timeout().
Removes an installed debug function from the process. Func or FuncId must be the same as previously installed. ποΈ
β¨ replace_state/3 β¨
replace_state(Name, StateFun, Timeout) -> NewState
when
Name :: name(),
StateFun ::
fun((State :: term()) ->
NewState :: term()),
Timeout :: timeout(),
NewState :: term().
Replaces the state of the process, and returns the new state.
NOTE: These functions are intended only to help with debugging, and are not to be called from normal code. They are provided for convenience, allowing developers to avoid having to create their own custom state replacement functions. β οΈ
Function StateFun provides a new state for the process. Argument State and the NewState return value of StateFun vary for different types of processes as follows:
- For a
gen_serverprocess,Stateis the state of the callback module andNewStateis a new instance of that state. - For a
gen_statemprocess,Stateis the tuple{CurrentState,CurrentData}, andNewStateis a similar tuple, which can contain a new current state, new state data, or both. - For a
gen_eventprocess,Stateis the tuple{Module, Id, HandlerState}as follows:Moduleβ The module name of the event handler.Idβ The ID of the handler (which isfalseif it was registered without an ID).HandlerStateβ The state of the handler.
NewState is a similar tuple where Module and Id are to have the same values as in State, but the value of HandlerState can be different. Returning a NewState, whose Module or Id values differ from those of State, leaves the state of the event handler unchanged. For a gen_event process, StateFun is called once for each event handler registered in the gen_event process.
If a StateFun function decides not to effect any change in process state, then regardless of process type, it can return its State argument.
If a StateFun function crashes or throws an exception, the original state of the process is unchanged for gen_server, and gen_statem processes. For gen_event processes, a crashing or failing StateFun function means that only the state of the particular event handler it was working on when it failed or crashed is unchanged; it can still succeed in changing the states of other event handlers registered in the same gen_event process.
If the callback module exports a system_replace_state/2 function, it is called in the target process to replace its state using StateFun. Its two arguments are StateFun and Misc, where Misc is the same as the Misc value returned by get_status/1,2. A system_replace_state/2 function is expected to return {ok, NewState, NewMisc}, where NewState is the new state of the callback module, obtained by calling StateFun, and NewMisc is a possibly new value used to replace the original Misc (required as Misc often contains the state of the callback module within it).
If the callback module does not export a system_replace_state/2 function, replace_state/2,3 assumes that Misc is the state of the callback module, passes it to StateFun and uses the return value as both the new state and as the new value of Misc. π
Okay so bestie, if the callback module's function system_replace_state/2 crashes or throws an exception, the caller exits with error {callback_failed, {Module, system_replace_state}, {Class, Reason}}, where Module is the name of the callback module and Class and Reason indicate details of the exception. π
And if the callback module does not provide asystem_replace_state/2function andStateFuncrashes or throws an exception, the caller exits with error{callback_failed, StateFun, {Class, Reason}}. Not me crying in OTP π
Function system_replace_state/2 is primarily useful for user-defined behaviors and modules that implement OTP special processes. The OTP behavior modules gen_server, gen_statem, and gen_event export this function, so callback modules for those behaviors need not to supply their own. iconic β¨
resume(Name, Timeout) -> ok
resume(Name, Timeout) -> ok
when Name :: name(), Timeout :: timeout().
Resumes a suspended process. Like waking your bestie up for brunch π₯
statistics(Name, Flag, Timeout) -> ok | {ok, Statistics}
statistics(Name, Flag, Timeout) -> ok | {ok, Statistics}
when
Name :: name(),
Flag :: true | false | get,
Statistics :: [StatisticsTuple] | no_statistics,
StatisticsTuple ::
{start_time, DateTime1} |
{current_time, DateTime2} |
{reductions, non_neg_integer()} |
{messages_in, non_neg_integer()} |
{messages_out, non_neg_integer()},
DateTime1 :: file:date_time(),
DateTime2 :: file:date_time(),
Timeout :: timeout().
Enables or disables the collection of statistics. If Flag is get, the statistical collection is returned. π
suspend(Name, Timeout) -> ok
suspend(Name, Timeout) -> ok
when Name :: name(), Timeout :: timeout().
Suspends the process. When the process is suspended, it only responds to other system messages, but not other messages. π€
terminate(Name, Reason, Timeout) -> ok
terminate(Name, Reason, Timeout) -> ok
when
Name :: name(),
Reason :: term(),
Timeout :: timeout().
Orders the process to terminate with the specified Reason. The termination is done asynchronously, so it is not guaranteed that the process is terminated when the function returns. π async queen
trace(Name, Flag, Timeout) -> ok
trace(Name, Flag, Timeout) -> ok
when
Name :: name(),
Flag :: boolean(),
Timeout :: timeout().
Prints all system events on standard_io. The events are formatted with a function that is defined by the process that generated the event (with a call to handle_debug/4). π
π CALLBACKS π
system_code_change(Misc, Module, OldVsn, Extra)
Called from handle_system_msg/6 when the process is to perform a code change. The code change is used when the internal data structure has changed. This function converts argument Misc to the new data structure. OldVsn is attribute vsn of the old version of the Module. If no such attribute is defined, the atom undefined is sent. π¦
system_continue(Parent, Debug, Misc)
Called from handle_system_msg/6 when the process is to continue its execution (for example, after it has been suspended). This function never returns. β¨
system_get_state(Misc)
Called from handle_system_msg/6 when the process is to return a term that reflects its current state. State is the value returned by get_state/2. π
system_replace_state(StateFun, Misc)
Called from handle_system_msg/6 when the process is to replace its current state. NState is the value returned by replace_state/3. π
system_terminate(Reason, Parent, Debug, Misc)
Called from handle_system_msg/6 when the process is to terminate. For example, this function is called when the process is suspended and its parent orders shutdown. It gives the process a chance to do a cleanup. This function never returns. π
This page is brought to you by Ericsson AB, stdlib 8.0.4, and sys(3). ππ¦
π¦ 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