gen_fsm(3)
π gen_fsm(3) π
Erlang Module Definition
π NAME π
gen_fsm β Deprecated and replaced by gen_statem in OTP 20. Periodt.
π DESCRIPTION π
π¦ Migration to gen_statem π¦
Okay so first thing, bestie: gen_fsm is deprecated and replaced by gen_statem in OTP 20. Here follows a simple example of turning a gen_fsm into a gen_statem. The example comes from the previous User's Guide for gen_fsm.
-module(code_lock).
-define(NAME, code_lock).
%-define(BEFORE_REWRITE, true).
-ifdef(BEFORE_REWRITE).
-behaviour(gen_fsm).
-else.
-behaviour(gen_statem).
-endif.
-export([start_link/1, button/1, stop/0]).
-ifdef(BEFORE_REWRITE).
-export([init/1, locked/2, open/2, handle_sync_event/4, handle_event/3,
handle_info/3, terminate/3, code_change/4]).
-else.
-export([init/1, callback_mode/0, locked/3, open/3,
terminate/3, code_change/4]).
%% Add callback__mode/0
%% Change arity of the state functions
%% Remove handle_info/3
-endif.
-ifdef(BEFORE_REWRITE).
start_link(Code) ->
gen_fsm:start_link({local, ?NAME}, ?MODULE, Code, []).
-else.
start_link(Code) ->
gen_statem:start_link({local,?NAME}, ?MODULE, Code, []).
-endif.
-ifdef(BEFORE_REWRITE).
button(Digit) ->
gen_fsm:send_event(?NAME, {button, Digit}).
-else.
button(Digit) ->
gen_statem:cast(?NAME, {button,Digit}).
%% send_event is asynchronous and becomes a cast
-endif.
-ifdef(BEFORE_REWRITE).
stop() ->
gen_fsm:sync_send_all_state_event(?NAME, stop).
-else.
stop() ->
gen_statem:call(?NAME, stop).
%% sync_send is synchronous and becomes call
%% all_state is handled by callback code in gen_statem
-endif.
init(Code) ->
do_lock(),
Data = #{code => Code, remaining => Code},
{ok, locked, Data}.
-ifdef(BEFORE_REWRITE).
-else.
callback_mode() ->
state_functions.
%% state_functions mode is the mode most similar to
%% gen_fsm. There is also handle_event mode which is
%% a fairly different concept.
-endif.
-ifdef(BEFORE_REWRITE).
locked({button, Digit}, Data0) ->
case analyze_lock(Digit, Data0) of
{open = StateName, Data} ->
{next_state, StateName, Data, 10000};
{StateName, Data} ->
{next_state, StateName, Data}
end.
-else.
locked(cast, {button,Digit}, Data0) ->
case analyze_lock(Digit, Data0) of
{open = StateName, Data} ->
{next_state, StateName, Data, 10000};
{StateName, Data} ->
{next_state, StateName, Data}
end;
locked({call, From}, Msg, Data) ->
handle_call(From, Msg, Data);
locked({info, Msg}, StateName, Data) ->
handle_info(Msg, StateName, Data).
%% Arity differs
%% All state events are dispatched to handle_call and handle_info help
%% functions. If you want to handle a call or cast event specifically
%% for this state you would add a special clause for it above.
-endif.
-ifdef(BEFORE_REWRITE).
open(timeout, State) ->
do_lock(),
{next_state, locked, State};
open({button,_}, Data) ->
{next_state, locked, Data}.
-else.
open(timeout, _, Data) ->
do_lock(),
{next_state, locked, Data};
open(cast, {button,_}, Data) ->
{next_state, locked, Data};
open({call, From}, Msg, Data) ->
handle_call(From, Msg, Data);
open(info, Msg, Data) ->
handle_info(Msg, open, Data).
%% Arity differs
%% All state events are dispatched to handle_call and handle_info help
%% functions. If you want to handle a call or cast event specifically
%% for this state you would add a special clause for it above.
-endif.
-ifdef(BEFORE_REWRITE).
handle_sync_event(stop, _From, _StateName, Data) ->
{stop, normal, ok, Data}.
handle_event(Event, StateName, Data) ->
{stop, {shutdown, {unexpected, Event, StateName}}, Data}.
handle_info(Info, StateName, Data) ->
{stop, {shutdown, {unexpected, Info, StateName}}, StateName, Data}.
-else.
-endif.
terminate(_Reason, State, _Data) ->
State =/= locked andalso do_lock(),
ok.
code_change(_Vsn, State, Data, _Extra) ->
{ok, State, Data}.
%% Internal functions
-ifdef(BEFORE_REWRITE).
-else.
handle_call(From, stop, Data) ->
{stop_and_reply, normal, {reply, From, ok}, Data}.
handle_info(Info, StateName, Data) ->
{stop, {shutdown, {unexpected, Info, StateName}}, StateName, Data}.
%% These are internal functions for handling all state events
%% and not behaviour callbacks as in gen_fsm
-endif.
analyze_lock(Digit, #{code := Code, remaining := Remaining} = Data) ->
case Remaining of
[Digit] ->
do_unlock(),
{open, Data#{remaining := Code}};
[Digit|Rest] -> % Incomplete
{locked, Data#{remaining := Rest}};
_Wrong ->
{locked, Data#{remaining := Code}}
end.
do_lock() ->
io:format("Lock~n", []).
do_unlock() ->
io:format("Unlock~n", []).
That's the glow-up, no cap.
π OTP 19 Documentation π
π¦ Module π¦
gen_fsm
π Module Summary π
Generic finite state machine behavior. Slay.
π¬ Description π¬
This behavior module provides a finite state machine. A generic finite state machine process (gen_fsm) implemented using this module has a standard set of interface functions and includes functionality for tracing and error reporting. It also fits into an OTP supervision tree. For more information, see OTP Design Principles.
A gen_fsm process assumes all specific parts to be located in a callback module exporting a predefined set of functions. The relationship between the behavior functions and the callback functions is as follows:
gen_fsm module Callback module
-------------- ---------------
gen_fsm:start
gen_fsm:start_link -----> Module:init/1
gen_fsm:stop -----> Module:terminate/3
gen_fsm:send_event -----> Module:StateName/2
gen_fsm:send_all_state_event -----> Module:handle_event/3
gen_fsm:sync_send_event -----> Module:StateName/3
gen_fsm:sync_send_all_state_event -----> Module:handle_sync_event/4
- -----> Module:handle_info/3
- -----> Module:terminate/3
- -----> Module:code_change/4
If a callback function fails or returns a bad value, the gen_fsm process terminates. π
A gen_fsm process handles system messages as described in sys(3). The sys module can be used for debugging a gen_fsm process.
Notice that a gen_fsm process does not trap exit signals automatically, this must be explicitly initiated in the callback module. Heads up, bestie.
Unless otherwise stated, all functions in this module fail if the specified gen_fsm process does not exist or if bad arguments are specified.
The gen_fsm process can go into hibernation (see erlang:hibernate/3) if a callback function specifies hibernate instead of a time-out value. This can be useful if the server is expected to be idle for a long time. However, use this feature with care, as hibernation implies at least two garbage collections (when hibernating and shortly after waking up) and is not something you want to do between each call to a busy state machine. π
π Callback Functions π
See the Callback Functions section for the functions to be exported from a gen_fsm callback module.
State name denotes a state of the state machine.
State data denotes the internal state of the Erlang process that implements the state machine.
ποΈ DATA TYPES ποΈ
enter_loop_opt() :: {debug, Dbgs :: [sys:debug_option()]}.β Start options for theenter_loop/4,5,6,start/3,4, andstart_link/3,4functions. Seestart_link/4.from() :: {To :: pid(), Tag :: term()}.β Reply destination. Seereply/2.fsm_name() :: {local, LocalName :: atom()} | {global, GlobalName :: term()} | {via, RegMod :: module(), ViaName :: term()}.β FSM name specification: local, global, or via registered. To be used when starting agen_fsm. Seestart_link/4.fsm_ref() :: pid() | (LocalName :: atom()) | {Name :: atom(), Node :: atom()} | {global, GlobalName :: term()} | {via, RegMod :: module(), ViaName :: term()}.β FSM referencepid/0or registeredfsm_name/0. To be used in for examplesend_event/2to specify the server.start_opt() :: {timeout, Time :: timeout()} | {spawn_opt, [proc_lib:start_spawn_option()]} | enter_loop_opt().β Start options for thestart/3,4, andstart_link/3,4functions. Seestart_link/4.
βοΈ FUNCTIONS βοΈ
π°οΈ cancel_timer(Ref) -> RemainingTime | false π°οΈ
cancel_timer(Ref) -> RemainingTime | false
when
Ref :: reference(),
RemainingTime :: non_neg_integer().
β οΈ Deprecated:gen_fsm:cancel_timer/1is deprecated; use the'gen_statem'module instead
Okay so cancel an internal timer in a generic FSM. Cancels an internal timer referred by Ref in the gen_fsm process that calls this function.
Ref is a reference returned from send_event_after/2 or start_timer/2.
If the timer has already timed out, but the event not yet been delivered, it is cancelled as if it had not timed out, so there is no false timer event after returning from this function.
Returns the remaining time in milliseconds until the timer would have expired if Ref referred to an active timer, otherwise false.
β¨ enter_loop/4 β¨
enter_loop(Module, Options, StateName, StateData) -> no_return()
when
Module :: module(),
Options :: [enter_loop_opt()],
StateName :: atom(),
StateData :: term().
Deprecated:gen_fsm:enter_loop/4is deprecated; use the'gen_statem'module instead
Enter the gen_fsm receive loop. Bestie this is literally the same energy as enter_loop/6 except with Timeout = infinity, and ngl the server you start is not registered, same as start_link/3. π
β¨ enter_loop/5 β¨
enter_loop(Module, Options, StateName, StateData, FsmName) ->
no_return()
when
Module :: module(),
Options :: [enter_loop_opt()],
StateName :: atom(),
StateData :: term(),
FsmName :: fsm_name();
(Module, Options, StateName, StateData, Timeout) ->
no_return()
when
Module :: module(),
Options :: enter_loop_opt(),
StateName :: atom(),
StateData :: term(),
Timeout :: timeout().
Deprecated:gen_fsm:enter_loop/5is deprecated; use the'gen_statem'module instead
Enter the gen_fsm receive loop. Okay so this one is a two-for-one, notice the ; β it's giving versatile.
- With the
FsmNameargument, it's equivalent toenter_loop/6withTimeout = infinity. π - With the
Timeoutargument, it's equivalent toenter_loop/6, but the server you started is not registered, just likestart_link/3. π
β¨ enter_loop/6 β¨
enter_loop(Module, Options, StateName, StateData, FsmName,
Timeout) ->
no_return()
when
Module :: module(),
Options :: [enter_loop_opt()],
StateName :: atom(),
StateData :: term(),
FsmName :: fsm_name() | pid(),
Timeout :: timeout().
Deprecated:gen_fsm:enter_loop/6is deprecated; use the'gen_statem'module instead
Enter the gen_fsm receive loop.
Okay bestie, this one is the main character. π It makes an existing process into a gen_fsm process. It does not return β like, ever β instead the calling process just walks into the gen_fsm receive loop and becomes a gen_fsm process. β¨
The process must have been started using one of the start functions in proc_lib. And you, yes you, are responsible for any initialization of the process, including registering a name for it. No one else is doing that for you, fr fr. π
This function is useful when you need a more complex initialization procedure than the gen_fsm behavior gives you. π¦
Module, Options, and FsmName mean the same things as when you call start[_link]/3,4. But watch out β the process must have been registered according to FsmName before this function is called. π
StateName, StateData, and Timeout mean the same things as in the return value of Module:init/1. And here's the slay: the callback module Module does not need to export an init/1 function. π
Careful bestie: the function fails if the calling process was not started by aproc_libstart function, or if it is not registered according toFsmName. π
β¨ reply/2 β¨
reply(Caller, Reply) -> Result
when Caller :: from(), Reply :: term(), Result :: term().
Deprecated:gen_fsm:reply/2is deprecated; use the'gen_statem'module instead
Send a reply to a caller. π¨
This function can be used by a gen_fsm process to explicitly send a reply to a client process that called sync_send_event/2,3 or sync_send_all_state_event/2,3, for those times when the reply just cannot be defined in the return value of Module:StateName/3 or Module:handle_sync_event/4. iykyk. π
Callermust be theFromargument that was provided to the callback function. πReplyis any term handed back to the client as the return value ofsync_send_event/2,3orsync_send_all_state_event/2,3. π
Return value Result is not further defined, and is always to be ignored. Like, don't even look at it bestie. π
β¨ send_all_state_event/2 β¨
send_all_state_event(FsmRef, Event) -> ok
when FsmRef :: fsm_ref(), Event :: term().
Deprecated:gen_fsm:send_all_state_event/2is deprecated; use the'gen_statem'module instead
Send an event asynchronously to a generic FSM.
Sends an event asynchronously to the FsmRef of the gen_fsm process and returns ok immediately. πββοΈπ¨ The gen_fsm process then calls Module:handle_event/3 to handle the event.
For a description of the arguments, see send_event/2. π
The difference between send_event/2 and send_all_state_event/2 is which callback function gets used to handle the event. This one is lowkey iconic when you're sending events that are handled the same way in every state, because you only need one handle_event clause instead of one clause in each state name function. Efficiency? We love her. πΈ
β¨ send_event/2 β¨
send_event(FsmRef, Event) -> ok
when FsmRef :: fsm_ref(), Event :: term().
Deprecated:gen_fsm:send_event/2is deprecated; use the'gen_statem'module instead
Send an event asynchronously to a generic FSM.
Sends Event to the FsmRef of the gen_fsm process and returns ok immediately. β‘ The gen_fsm process calls Module:StateName/2 to handle the event, where StateName is the name of the current state of the gen_fsm process. That's the vibe check. β¨
FsmRef can be any of the following:
- The
pid/0π«Ά Name, if the gen_fsm process is locally registered π{Name, Node}, if the gen_fsm process is locally registered at another node π{global, GlobalName}, if the gen_fsm process is globally registered π{via, Module, ViaName}, if the gen_fsm process is registered through an alternative process registry π¦
Event is any term that is passed as one of the arguments to Module:StateName/2. π
β¨ send_event_after/2 β¨
send_event_after(Time, Event) -> Ref
when
Time :: non_neg_integer(),
Event :: term(),
Ref :: reference().
Deprecated:gen_fsm:send_event_after/2is deprecated; use the'gen_statem'module instead
Send a delayed event internally in a generic FSM. β°
Sends a delayed event internally in the gen_fsm process that calls this function, after Time milliseconds. Returns immediately with a reference() that can be used to cancel the delayed send using cancel_timer/1. So you get that lil undo button, periodt. π
The gen_fsm process calls Module:StateName/2 to handle the event, where 'StateName' is the name of the current state of the gen_fsm process at the time the delayed event is delivered. Not when you sent it β when it lands. Important distinction bestie. π
Event is any term that is passed as one of the arguments to Module:StateName/2. π
β¨ start/3 β¨
start(Module, Args, Options) -> Result
when
Module :: module(),
Args :: term(),
Options :: [start_opt()],
Result :: {ok, Pid} | ignore | {error, Reason},
Pid :: pid(),
Reason :: term().
Deprecated:gen_fsm:start/3is deprecated; use the'gen_statem'module instead
Create a standalone gen_fsm process, not registered.
Equivalent to start(Name, Mod, Args, Options) without registering a Name. Simple as that. β¨
For a description of arguments and return values, see start_link/3,4. π«Ά
β¨ start/4 β¨
start(FsmName, Module, Args, Options) -> Result
when
FsmName :: fsm_name(),
Module :: module(),
Args :: term(),
Options :: [start_opt()],
Result :: {ok, Pid} | ignore | {error, Reason},
Pid :: pid(),
Reason :: {already_started, Pid} | term().
Deprecated:gen_fsm:start/4is deprecated; use the'gen_statem'module instead
Create a standalone gen_fsm process.
The created process is not part of a supervision tree, and thus has no supervisor. She's out here fending for herself, no cap. π
For a description of arguments and return values, see start_link/3,4. π
β¨ start_link/3 β¨
start_link(Module, Args, Options) -> Result
when
Module :: module(),
Args :: term(),
Options :: [start_opt()],
Result :: {ok, Pid} | ignore | {error, Reason},
Pid :: pid(),
Reason :: term().
Deprecated:gen_fsm:start_link/3is deprecated; use the'gen_statem'module instead
Create a gen_fsm process in a supervision tree, not registered.
Equivalent to start_link(Name, Mod, Args, Options) without registering a Name. π
β¨ start_link/4 β¨
start_link(FsmName, Module, Args, Options) -> Result
when
FsmName :: fsm_name(),
Module :: module(),
Args :: term(),
Options :: [start_opt()],
Result :: {ok, Pid} | ignore | {error, Reason},
Pid :: pid(),
Reason :: {already_started, Pid} | term().
Deprecated:gen_fsm:start_link/4is deprecated; use the'gen_statem'module instead
Create a gen_fsm process in a supervision tree. π³
The process is created as part of a supervision tree. The function is meant to be called, directly or indirectly, by the supervisor. For example β and this is the slay β it ensures that the gen_fsm process is linked to the supervisor. π«Ά
The gen_fsm process calls Module:init/1 to initialize. And to make sure the startup procedure stays synchronized, start_link/3,4 does not return until Module:init/1 has returned. No racing, no chaos, just vibes. β¨
- If
FsmName = {local, Name}, the gen_fsm process is registered locally asNameusingregister/2. π - If
FsmName = {global, GlobalName}, the gen_fsm process is registered globally asGlobalNameusingglobal:register_name/2. π - If <code>FsmName = {via, Module, ViaName}</code>, the gen_fsm process registers itself with the registry that
Modulerepresents. ThatModulecallback is supposed to exportregister_name/2,unregister_name/1,whereis_name/1, andsend/2, and they gotta act just like the matching functions inglobal. So yes bestie,{via, global, GlobalName}is a totally valid reference. β¨
Module is the name of the callback module, okay?
Args is any term, and it gets handed over as the argument to Module:init/1.
If the option {timeout, Time} is there, the gen_fsm process is allowed to spend Time milliseconds initializing β and if it doesn't finish in time, it dies and the start function returns {error, timeout}. β° clock's ticking
If the option {debug, Dbgs} is present, the corresponding sys function gets called for each item in Dbgs β peep sys(3) for that one.
If the option {spawn_opt, SOpts} is present, SOpts is passed as an option list to the spawn_opt BIF that's used to spawn the gen_fsm process β see spawn_opt/2.
NOTE: using spawn optionmonitoris not allowed, it makes the function fail with reasonbadarg. π ββοΈ
If the gen_fsm process gets created and initialized successfully, the function returns {ok, Pid}, where Pid is the pid of the gen_fsm process. But if a process with the specified FsmName already exists, you get {error, {already_started, Pid}}, where Pid is the pid of that process. somebody got there first π
If Module:init/1 fails with Reason, the function returns {error, Reason}. And if Module:init/1 returns {stop, Reason} or ignore, the process is terminated and the function returns {error, Reason} or ignore, respectively.
start_timer(Time, Msg) -> Ref
start_timer(Time, Msg) -> Ref
when
Time :: non_neg_integer(),
Msg :: term(),
Ref :: reference().
Deprecated:gen_fsm:start_timer/2is deprecated; use the'gen_statem'module instead.
Send a time-out event internally in a generic FSM.
It sends a time-out event internally in the gen_fsm process that calls this function, after Time milliseconds. Returns immediately a reference that you can use to cancel the timer with cancel_timer/1. tick tock, but make it cancelable π
The gen_fsm process calls Module:StateName/2 to handle the event, where 'StateName' is the name of the current state of the gen_fsm process at the time the time-out message is delivered.
Msg is any term that gets passed in the time-out message, {timeout, Ref, Msg}, as one of the arguments to Module:StateName/2.
stop(FsmRef, Reason, Timeout) -> ok
stop(FsmRef, Reason, Timeout) -> ok
when
FsmRef :: fsm_ref(),
Reason :: term(),
Timeout :: timeout().
Deprecated:gen_fsm:stop/3is deprecated; use the'gen_statem'module instead.
Synchronously stop a generic FSM. yep, we're ending this era
Orders a generic finite state machine to exit with the specified Reason and waits for it to terminate. The gen_fsm process calls Module:terminate/3 before exiting. π«Ά
The function returns ok if the generic finite state machine terminates with the expected reason. Any other reason than normal, shutdown, or {shutdown, Term} causes an error report to be issued using error_logger:format/2.
Timeout is an integer greater than zero that says how many milliseconds to wait for the generic FSM to terminate, or the atom infinity to wait indefinitely. If the generic finite state machine has not terminated within the specified time, a timeout exception is raised. β³
If the process does not exist, a noproc exception is raised. π ghosted
sync_send_all_state_event(FsmRef, Event, Timeout) -> Reply
sync_send_all_state_event(FsmRef, Event, Timeout) -> Reply
when
FsmRef :: fsm_ref(),
Event :: term(),
Timeout :: timeout(),
Reply :: term().
Deprecated:gen_fsm:sync_send_all_state_event/3is deprecated; use the'gen_statem'module instead.
Send an event synchronously to a generic FSM.
Sends an event to the FsmRef of the gen_fsm process and waits until a reply arrives or a time-out occurs. The gen_fsm process calls Module:handle_sync_event/4 to handle the event.
For a description of FsmRef and Event, see send_event/2. For a description of Timeout and Reply, see sync_send_event/3.
For a discussion about the difference between sync_send_event and sync_send_all_state_event, see send_all_state_event/2. iykyk π
sync_send_event(FsmRef, Event, Timeout) -> Reply
sync_send_event(FsmRef, Event, Timeout) -> Reply
when
FsmRef :: fsm_ref(),
Event :: term(),
Timeout :: timeout(),
Reply :: term().
Deprecated:gen_fsm:sync_send_event/3is deprecated; use the'gen_statem'module instead.
Send an event synchronously to a generic FSM.
Sends an event to the FsmRef of the gen_fsm process and waits until a reply arrives or a time-out occurs. The gen_fsm process calls Module:StateName/3 to handle the event, where 'StateName' is the name of the current state of the gen_fsm process.
For a description of FsmRef and Event, see send_event/2.
Timeout is an integer greater than zero that specifies how many milliseconds to wait for a reply, or the atom infinity to wait indefinitely. If no reply is received within the specified time, the function call fails. girl answer the phone π
Return value Reply is defined in the return value of Module:StateName/3.
NOTE: the ancient behavior of sometimes consuming the server exit message if the server died during the call while linked to the client was removed in Erlang 5.6/OTP R12B.
β¨ CALLBACKS β¨
'StateName'(Event, StateData)
Deprecated: the callbackgen_fsm:'StateName'(_,_)is deprecated; use the'gen_statem'module instead.
Handle an asynchronous event. no waiting around, we just vibe β¨
There's supposed to be one instance of this function for each possible state name. Whenever a gen_fsm process receives an event sent using send_event/2, the instance of this function with the same name as the current state name StateName is called to handle the event. It's also called if a time-out occurs.
Event is either the atom timeout, if a time-out has occurred, or the Event argument provided to send_event/2.
StateData is the state data of the gen_fsm process.
If the function returns {next_state, NextStateName, NewStateData}, {next_state, NextStateName, NewStateData, Timeout}, or {next_state, NextStateName, NewStateData, hibernate}, the gen_fsm process continues executing with the current state name set to NextStateName and with the possibly updated state data NewStateData. For a description of Timeout and hibernate, see Module:init/1.
If the function returns {stop ,Reason, NewStateData}, the gen_fsm process calls Module:terminate(Reason, StateName, NewStateData) and terminates. and that's a wrap π
'StateName'(Event, From, StateData)
Deprecated: the callbackgen_fsm:'StateName'(_,_,_)is deprecated; use the'gen_statem'module instead.
Handle a synchronous event.
There's supposed to be one instance of this function for each possible state name. Whenever a gen_fsm process receives an event sent using sync_send_event/2,3, the instance of this function with the same name as the current state name StateName is called to handle the event.
Event is the Event argument provided to sync_send_event/2,3.
From is a tuple {Pid, Tag} where Pid is the pid/0 of the process that called sync_send_event/2,3, and Tag is a unique tag.
StateData is the state data of the gen_fsm process.
- If
{reply, Reply, NextStateName, NewStateData},{reply, Reply, NextStateName, NewStateData, Timeout}, or{reply, Reply, NextStateName, NewStateData, hibernate}is returned,Replyis given back toFromas the return value ofsync_send_event/2,3. The gen_fsm process then continues executing with the current state name set toNextStateNameand with the possibly updated state dataNewStateData. For a description ofTimeoutandhibernate, seeModule:init/1. - If
{next_state, NextStateName, NewStateData},{next_state, NextStateName, NewStateData, Timeout}, or{next_state, NextStateName, NewStateData, hibernate}is returned, the gen_fsm process continues executing inNextStateNamewithNewStateData. Any reply toFrommust be specified explicitly usingreply/2. speak up or forever hold your peace - If the function returns
{stop, Reason, Reply, NewStateData},Replyis given back toFrom. If the function returns{stop, Reason, NewStateData}, any reply toFrommust be specified explicitly usingreply/2. The gen_fsm process then callsModule:terminate(Reason, StateName, NewStateData)and terminates.
code_change(OldVsn, StateName, StateData, Extra)
Deprecated: the callbackgen_fsm:code_change(_,_,_,_)is deprecated; use the'gen_statem'module instead.
Update the internal state data during upgrade/downgrade. glow-up time β¨
This function is called by a gen_fsm process when it's supposed to update its internal state data during a release upgrade/downgrade, that is, when instruction {update, Module, Change, ...}, where Change = {advanced, Extra}, is given in the appup file; see Release Handling Instructions in OTP Design Principles.
For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is {down, Vsn}. Vsn is defined by the vsn attribute(s) of the old version of the callback module Module. If no such attribute is defined, the version is the checksum of the Beam file.
StateName is the current state name and StateData the internal state data of the gen_fsm process.
Extra is passed "as is" from the {advanced, Extra} part of the update instruction.
The function is supposed to return the new current state name and updated internal data.
format_status/2
π« Deprecated: the callbackgen_fsm:format_status(_,_)is deprecated; use the'gen_statem'module instead
Okay bestie, this one is optional β it's the function that gives you a term describing the current gen_fsm process status.
The second argument is [PDict, StateData], aka a list with the 2 elements, in that order. No cap.
NOTE: This callback is optional, so callback modules need not export it. The gen_fsm module provides a default implementation of this function that returns the callback module state data.
This function gets called by a gen_fsm process in these situations:
- One of
sys:get_status/1,2is invoked to get thegen_fsmstatus.Optis set to the atomnormalfor this case. - The
gen_fsmprocess terminates abnormally and logs an error.Optis set to the atomterminatefor this case.
This function is useful for changing the form and appearance of the gen_fsm status for these cases. A callback module wishing to change the sys:get_status/1,2 return value as well as how its status appears in termination error logs, exports an instance of format_status/2 that returns a term describing the current status of the gen_fsm process.
PDict is the current value of the process dictionary of the gen_fsm process.
StateData is the internal state data of the gen_fsm process.
The function is to return Status, a term that changes the details of the current state and status of the gen_fsm process. There are no restrictions of the form Status can take, but for the sys:get_status/1,2 case (when Opt is normal), the recommended form for the Status value is [{data, [{"StateData", Term}]}], where Term provides relevant details of the gen_fsm state data. Following this recommendation is not required, but it makes the callback module status consistent with the rest of the sys:get_status/1,2 return value.
One use for this function is to return compact alternative state data representations to avoid that large state terms are printed in log files.
π
handle_event(Event, StateName, StateData)
π« Deprecated: the callbackgen_fsm:handle_event(_,_,_)is deprecated; use the'gen_statem'module instead
Handle an asynchronous event.
Whenever a gen_fsm process receives an event sent using send_all_state_event/2, this function is called to handle the event.
StateName is the current state name of the gen_fsm process.
For a description of the other arguments and possible return values, see Module:StateName/2.
π¨ handle_info(Info, StateName, StateData)
π« Deprecated: the callbackgen_fsm:handle_info(_,_,_)is deprecated; use the'gen_statem'module instead
Handle an incoming message.
This function is called by a gen_fsm process when it receives any other message than a synchronous or asynchronous event (or a system message).
Info is the received message.
For a description of the other arguments and possible return values, see Module:StateName/2.
π¦ handle_sync_event(Event, From, StateName, StateData)
π« Deprecated: the callbackgen_fsm:handle_sync_event(_,_,_,_)is deprecated; use the'gen_statem'module instead
Handle a synchronous event.
Whenever a gen_fsm process receives an event sent using sync_send_all_state_event/2,3, this function is called to handle the event.
StateName is the current state name of the gen_fsm process.
For a description of the other arguments and possible return values, see Module:StateName/3.
β¨ init(Args)
π« Deprecated: the callbackgen_fsm:init(_)is deprecated; use the'gen_statem'module instead
Initialize process and internal state name and state data.
Whenever a gen_fsm process is started using start/3,4 or start_link/3,4, this function is called by the new process to initialize.
Args is the Args argument provided to the start function.
If initialization is successful, the function is to return {ok, StateName, StateData}, {ok, StateName, StateData, Timeout}, or {ok, StateName, StateData, hibernate}, where StateName is the initial state name and StateData the initial state data of the gen_fsm process.
If an integer/0 time-out value is provided, a time-out occurs unless an event or a message is received within Timeout milliseconds. A time-out is represented by the atom timeout and is to be handled by the Module:StateName/2 callback functions. The atom infinity can be used to wait indefinitely, this is the default value.
If hibernate is specified instead of a time-out value, the process goes into hibernation when waiting for the next message to arrive (by calling proc_lib:hibernate/3).
If the initialization fails, the function returns {stop, Reason}, where Reason is any term, or ignore.
π§Ή terminate(Reason, StateName, StateData)
π« Deprecated: the callbackgen_fsm:terminate(_,_,_)is deprecated; use the'gen_statem'module instead
Clean up before termination.
This function is called by a gen_fsm process when it is about to terminate. It is to be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_fsm process terminates with Reason. The return value is ignored.
Reason is a term denoting the stop reason, StateName is the current state name, and StateData is the state data of the gen_fsm process.
Reason depends on why the gen_fsm process is terminating. If it is because another callback function has returned a stop tuple {stop, ...}, Reason has the value specified in that tuple. If it is because of a failure, Reason is the error reason.
If the gen_fsm process is part of a supervision tree and is ordered by its supervisor to terminate, this function is called with Reason = shutdown if the following conditions apply:
- The
gen_fsmprocess has been set to trap exit signals. - The shutdown strategy as defined in the child specification of the supervisor is an integer time-out value, not
brutal_kill.
Even if the gen_fsm process is not part of a supervision tree, this function is called if it receives an 'EXIT' message from its parent. Reason is the same as in the 'EXIT' message.
Otherwise, the gen_fsm process terminates immediately.
Notice that for any other reason than normal, shutdown, or {shutdown, Term} the gen_fsm process is assumed to terminate because of an error and an error report is issued using error_logger:format/2.
And that's a wrap, bestie π Source/version: Ericsson AB Β· stdlib 8.0.4 Β· gen_fsm(3) π (date? not in this footer, but the vibe is timeless β¨)
π¦ 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