1gen_server(3)              Erlang Module Definition              gen_server(3)
2
3
4

NAME

6       gen_server - Generic server behavior.
7

DESCRIPTION

9       This behavior module provides the server of a client-server relation. A
10       generic server process (gen_server) implemented using this module has a
11       standard  set  of  interface  functions  and includes functionality for
12       tracing and error reporting. It also fits into an OTP supervision tree.
13       For  more  information, see section  gen_server Behaviour in OTP Design
14       Principles.
15
16       A gen_server process assumes all specific parts  to  be  located  in  a
17       callback  module exporting a predefined set of functions. The relation‐
18       ship between the behavior functions and the callback  functions  is  as
19       follows:
20
21       gen_server module            Callback module
22       -----------------            ---------------
23       gen_server:start
24       gen_server:start_monitor
25       gen_server:start_link -----> Module:init/1
26
27       gen_server:stop       -----> Module:terminate/2
28
29       gen_server:call
30       gen_server:send_request
31       gen_server:multi_call -----> Module:handle_call/3
32
33       gen_server:cast
34       gen_server:abcast     -----> Module:handle_cast/2
35
36       -                     -----> Module:handle_info/2
37
38       -                     -----> Module:handle_continue/2
39
40       -                     -----> Module:terminate/2
41
42       -                     -----> Module:code_change/3
43
44       If  a  callback  function  fails or returns a bad value, the gen_server
45       process terminates.
46
47       A gen_server process handles system messages as  described  in  sys(3).
48       The sys module can be used for debugging a gen_server process.
49
50       Notice  that  a gen_server process does not trap exit signals automati‐
51       cally, this must be explicitly initiated in the callback module.
52
53       Unless otherwise stated, all functions in this module fail if the spec‐
54       ified  gen_server process does not exist or if bad arguments are speci‐
55       fied.
56
57       The gen_server process can go into hibernation (see erlang:hibernate/3)
58       if  a  callback  function  specifies  'hibernate' instead of a time-out
59       value. This can be useful if the server is expected to be  idle  for  a
60       long  time. However, use this feature with care, as hibernation implies
61       at least two garbage collections (when hibernating  and  shortly  after
62       waking  up)  and is not something you want to do between each call to a
63       busy server.
64
65       If the gen_server process needs to perform an action immediately  after
66       initialization  or  to  break the execution of a callback into multiple
67       steps, it can return {continue,Continue} in place of  the  time-out  or
68       hibernation  value, which will immediately invoke the handle_continue/2
69       callback.
70
71       If the gen_server process terminates, e.g. as a result of a function in
72       the  callback  module  returning {stop,Reason,NewState}, an exit signal
73       with this Reason is sent to linked processes and ports. See   Processes
74       in the Reference Manual for details regarding error handling using exit
75       signals.
76

EXPORTS

78       abcast(Name, Request) -> abcast
79       abcast(Nodes, Name, Request) -> abcast
80
81              Types:
82
83                 Nodes = [Node]
84                  Node = atom()
85                 Name = atom()
86                 Request = term()
87
88              Sends an asynchronous request to the  gen_server  processes  lo‐
89              cally  registered  as  Name at the specified nodes. The function
90              returns immediately and ignores nodes  that  do  not  exist,  or
91              where  the  gen_server  Name does not exist. The gen_server pro‐
92              cesses call Module:handle_cast/2 to handle the request.
93
94              For a description of the arguments, see multi_call/2,3,4.
95
96       call(ServerRef, Request) -> Reply
97       call(ServerRef, Request, Timeout) -> Reply
98
99              Types:
100
101                 ServerRef = Name | {Name,Node} | {global,GlobalName}
102                  | {via,Module,ViaName} | pid()
103                  Node = atom()
104                  GlobalName = ViaName = term()
105                 Request = term()
106                 Timeout = int()>0 | infinity
107                 Reply = term()
108
109              Makes a synchronous call to  the  ServerRef  of  the  gen_server
110              process  by  sending a request and waiting until a reply arrives
111              or a time-out occurs. The gen_server process  calls  Module:han‐
112              dle_call/3 to handle the request.
113
114              ServerRef can be any of the following:
115
116                * The pid
117
118                * Name, if the gen_server process is locally registered
119
120                * {Name,Node}, if the gen_server process is locally registered
121                  at another node
122
123                * {global,GlobalName}, if the gen_server process  is  globally
124                  registered
125
126                * {via,Module,ViaName},  if  the  gen_server process is regis‐
127                  tered through an alternative process registry
128
129              Request is any term that is passed as the first argument to Mod‐
130              ule:handle_call/3.
131
132              Timeout  is an integer greater than zero that specifies how many
133              milliseconds to wait for a reply, or the atom infinity  to  wait
134              indefinitely.  Defaults  to 5000. If no reply is received within
135              the specified time, the  function  call  fails.  If  the  caller
136              catches  the  failure  and  continues running, and the server is
137              just late with the reply, it can arrive at any time  later  into
138              the message queue of the caller. The caller must in this case be
139              prepared for this and discard any such garbage messages that are
140              two element tuples with a reference as the first element.
141
142              The  return  value  Reply is defined in the return value of Mod‐
143              ule:handle_call/3.
144
145              The call can fail for many reasons, including time-out  and  the
146              called gen_server process dying before or during the call.
147
148       cast(ServerRef, Request) -> ok
149
150              Types:
151
152                 ServerRef = Name | {Name,Node} | {global,GlobalName}
153                  | {via,Module,ViaName} | pid()
154                  Node = atom()
155                  GlobalName = ViaName = term()
156                 Request = term()
157
158              Sends an asynchronous request to the ServerRef of the gen_server
159              process and returns ok immediately, ignoring if the  destination
160              node  or  gen_server  process  does  not  exist.  The gen_server
161              process calls Module:handle_cast/2 to handle the request.
162
163              For a description of ServerRef, see call/2,3.
164
165              Request is any term that is passed as one of  the  arguments  to
166              Module:handle_cast/2.
167
168       check_response(Msg, RequestId) -> Result
169
170              Types:
171
172                 RequestId = term()
173                 Result = {reply, Reply} | no_reply | {error, {Reason, Server‐
174                 Ref}}
175                 Msg = Reply = term()
176                 Timeout = timeout()
177                 Reason = term()
178                 ServerRef = Name | {Name,Node} | {global,GlobalName}
179                  | {via,Module,ViaName} | pid()
180                  Node = atom()
181                  GlobalName = ViaName = term()
182
183              This function is used to check if a previously received message,
184              for  example  by  receive or handle_info/2, is a result of a re‐
185              quest made with send_request/2. If Msg is a reply to the  handle
186              RequestId the result of the request is returned in Reply. Other‐
187              wise returns no_reply and no cleanup is done, and thus the func‐
188              tion must be invoked repeatedly until a reply is returned.
189
190              The  return  value  Reply is defined in the return value of Mod‐
191              ule:handle_call/3.
192
193              The function returns an error if the gen_server dies  before  or
194              during this request.
195
196       enter_loop(Module, Options, State)
197       enter_loop(Module, Options, State, ServerName)
198       enter_loop(Module, Options, State, Timeout)
199       enter_loop(Module, Options, State, ServerName, Timeout)
200
201              Types:
202
203                 Module = atom()
204                 Options = [Option]
205                  Option = {debug,Dbgs} | {hibernate_after,HibernateAfterTime‐
206                 out}
207                  Dbgs = [Dbg]
208                  Dbg = trace | log | statistics
209                  | {log_to_file,FileName} | {install,{Func,FuncState}}
210                 State = term()
211                 ServerName = {local,Name} | {global,GlobalName}
212                  | {via,Module,ViaName}
213                  Name = atom()
214                  GlobalName = ViaName = term()
215                 Timeout = int() | infinity
216
217              Makes an existing process into a gen_server  process.  Does  not
218              return,  instead  the  calling  process  enters  the  gen_server
219              process receive loop  and  becomes  a  gen_server  process.  The
220              process  must have been started using one of the start functions
221              in proc_lib(3). The user is responsible for  any  initialization
222              of the process, including registering a name for it.
223
224              This  function is useful when a more complex initialization pro‐
225              cedure is needed than the gen_server process behavior provides.
226
227              Module, Options, and ServerName have the same meanings  as  when
228              calling  start[_link|_monitor]/3,4.  However,  if  ServerName is
229              specified, the process must have been registered accordingly be‐
230              fore this function is called.
231
232              State  and Timeout have the same meanings as in the return value
233              of Module:init/1. The callback module Module does  not  need  to
234              export an init/1 function.
235
236              The  function  fails if the calling process was not started by a
237              proc_lib start function, or if it is not registered according to
238              ServerName.
239
240       multi_call(Name, Request) -> Result
241       multi_call(Nodes, Name, Request) -> Result
242       multi_call(Nodes, Name, Request, Timeout) -> Result
243
244              Types:
245
246                 Nodes = [Node]
247                  Node = atom()
248                 Name = atom()
249                 Request = term()
250                 Timeout = int()>=0 | infinity
251                 Result = {Replies,BadNodes}
252                  Replies = [{Node,Reply}]
253                  Reply = term()
254                 BadNodes = [Node]
255
256              Makes  a  synchronous  call  to all gen_server processes locally
257              registered as Name at the specified nodes by first sending a re‐
258              quest  to  every  node  and  then  waits  for  the  replies. The
259              gen_server process calls Module:handle_call/3 to handle the  re‐
260              quest.
261
262              The  function  returns a tuple {Replies,BadNodes}, where Replies
263              is a list of {Node,Reply} and BadNodes is a list  of  node  that
264              either did not exist, or where the gen_server Name did not exist
265              or did not reply.
266
267              Nodes is a list of node names to which  the  request  is  to  be
268              sent.   Default   value   is   the   list  of  all  known  nodes
269              [node()|nodes()].
270
271              Name is the locally registered name of each gen_server process.
272
273              Request is any term that is passed as the first argument to Mod‐
274              ule:handle_call/3.
275
276              Timeout  is an integer greater than zero that specifies how many
277              milliseconds to wait for each reply, or  the  atom  infinity  to
278              wait indefinitely. Defaults to infinity. If no reply is received
279              from a node within the specified time,  the  node  is  added  to
280              BadNodes.
281
282              When  a reply Reply is received from the gen_server process at a
283              node Node, {Node,Reply} is added to Replies. Reply is defined in
284              the return value of Module:handle_call/3.
285
286          Warning:
287              If  one  of the nodes cannot process monitors, for example, C or
288              Java nodes, and the gen_server process is not started  when  the
289              requests  are  sent,  but starts within 2 seconds, this function
290              waits the whole Timeout, which may be infinity.
291
292              This problem does not exist if all nodes are Erlang nodes.
293
294
295              To prevent late answers (after the time-out) from polluting  the
296              message  queue  of the caller, a middleman process is used to do
297              the calls. Late answers are then discarded when they arrive to a
298              terminated process.
299
300       receive_response(RequestId, Timeout) -> Result
301
302              Types:
303
304                 RequestId = term()
305                 Result  = {reply, Reply} | timeout | {error, {Reason, Server‐
306                 Ref}}
307                 Reply = term()
308                 Timeout = timeout()
309                 Reason = term()
310                 ServerRef = Name | {Name,Node} | {global,GlobalName}
311                  | {via,Module,ViaName} | pid()
312                  Node = atom()
313                  GlobalName = ViaName = term()
314
315              This function is used to receive a reply of a request made  with
316              send_request/2  to  a  gen_server process. This function must be
317              called from the same process from which send_request/2 was made.
318
319              Timeout is an integer greater then or equal to zero that  speci‐
320              fies how many milliseconds to wait for an reply, or the atom in‐
321              finity to wait indefinitely. If no reply is received within  the
322              specified  time, the function returns timeout. Assuming that the
323              server executes on a node supporting aliases (introduced in  OTP
324              24)  no  response will be received after a timeout. Otherwise, a
325              garbage response might be received at a later time.
326
327              The return value Reply is defined in the return  value  of  Mod‐
328              ule:handle_call/3.
329
330              The  function  returns an error if the gen_server dies before or
331              during this request.
332
333              The difference between wait_response() and receive_response() is
334              that  receive_response() abandons the request at timeout so that
335              a potential future response is  ignored,  while  wait_response()
336              does not.
337
338       reply(Client, Reply) -> ok
339
340              Types:
341
342                 Client - see below
343                 Reply = term()
344
345              This  function can be used by a gen_server process to explicitly
346              send  a  reply   to   a   client   that   called   call/2,3   or
347              multi_call/2,3,4, when the reply cannot be defined in the return
348              value of Module:handle_call/3.
349
350              Client must be the From argument provided to the callback  func‐
351              tion.  Reply  is any term given back to the client as the return
352              value of call/2,3 or multi_call/2,3,4.
353
354       send_request(ServerRef, Request) -> RequestId
355
356              Types:
357
358                 ServerRef = Name | {Name,Node} | {global,GlobalName}
359                  | {via,Module,ViaName} | pid()
360                  Node = atom()
361                  GlobalName = ViaName = term()
362                 RequestId = term()
363                 Timeout = int()>0 | infinity
364                 Request = term()
365
366              Sends a request to the ServerRef of the gen_server  process  and
367              returns  a  handle  RequestId.  The return value RequestId shall
368              later  be  used  with  receive_response/2,  wait_response/2,  or
369              check_response/2 to fetch the actual result of the request.
370
371              The       call      gen_server:wait_response(gen_server:send_re‐
372              quest(ServerRef,Request), Timeout) can be seen as equivalent  to
373              gen_server:call(Server,Request,Timeout), ignoring the error han‐
374              dling.
375
376              The gen_server process calls Module:handle_call/3 to handle  the
377              request.
378
379              ServerRef can be any of the following:
380
381                * The pid
382
383                * Name, if the gen_server process is locally registered
384
385                * {Name,Node}, if the gen_server process is locally registered
386                  at another node
387
388                * {global,GlobalName}, if the gen_server process  is  globally
389                  registered
390
391                * {via,Module,ViaName},  if  the  gen_server process is regis‐
392                  tered through an alternative process registry
393
394              Request is any term that is passed as the first argument to Mod‐
395              ule:handle_call/3.
396
397       start(Module, Args, Options) -> Result
398       start(ServerName, Module, Args, Options) -> Result
399
400              Types:
401
402                 ServerName = {local,Name} | {global,GlobalName}
403                  | {via,Module,ViaName}
404                  Name = atom()
405                  GlobalName = ViaName = term()
406                 Module = atom()
407                 Args = term()
408                 Options = [Option]
409                  Option  =  {debug,Dbgs}  |  {timeout,Time}  | {hibernate_af‐
410                 ter,HibernateAfterTimeout} | {spawn_opt,SOpts}
411                  Dbgs = [Dbg]
412                  Dbg = trace | log | statistics  |  {log_to_file,FileName}  |
413                 {install,{Func,FuncState}}
414                  SOpts = [term()]
415                 Result = {ok,Pid} | ignore | {error,Error}
416                  Pid = pid()
417                  Error = {already_started,Pid} | term()
418
419              Creates  a  standalone gen_server process, that is, a gen_server
420              process that is not part of a supervision tree and thus  has  no
421              supervisor.
422
423              For   a   description   of  arguments  and  return  values,  see
424              start_link/3,4.
425
426       start_link(Module, Args, Options) -> Result
427       start_link(ServerName, Module, Args, Options) -> Result
428
429              Types:
430
431                 ServerName = {local,Name} | {global,GlobalName}
432                  | {via,Module,ViaName}
433                  Name = atom()
434                  GlobalName = ViaName = term()
435                 Module = atom()
436                 Args = term()
437                 Options = [Option]
438                  Option =  {debug,Dbgs}  |  {timeout,Time}  |  {hibernate_af‐
439                 ter,HibernateAfterTimeout} | {spawn_opt,SOpts}
440                  Dbgs = [Dbg]
441                  Dbg  =  trace  | log | statistics | {log_to_file,FileName} |
442                 {install,{Func,FuncState}}
443                  SOpts = [term()]
444                 Result = {ok,Pid} | ignore | {error,Error}
445                  Pid = pid()
446                  Error = {already_started,Pid} | term()
447
448              Creates a gen_server process as part of a supervision tree. This
449              function  is to be called, directly or indirectly, by the super‐
450              visor. For example, it ensures that the  gen_server  process  is
451              linked to the supervisor.
452
453              The gen_server process calls Module:init/1 to initialize. To en‐
454              sure a synchronized startup procedure, start_link/3,4  does  not
455              return until Module:init/1 has returned.
456
457                * If ServerName={local,Name}, the gen_server process is regis‐
458                  tered locally as Name using register/2.
459
460                * If ServerName={global,GlobalName}, the gen_server process id
461                  registered   globally   as  GlobalName  using  global:regis‐
462                  ter_name/2 If no name is provided, the gen_server process is
463                  not registered.
464
465                * If  ServerName={via,Module,ViaName},  the gen_server process
466                  registers with the registry represented by Module. The  Mod‐
467                  ule callback is to export the functions register_name/2, un‐
468                  register_name/1, whereis_name/1, and send/2,  which  are  to
469                  behave  like  the  corresponding  functions in global. Thus,
470                  {via,global,GlobalName} is a valid reference.
471
472              Module is the name of the callback module.
473
474              Args is any  term  that  is  passed  as  the  argument  to  Mod‐
475              ule:init/1.
476
477                * If  option {timeout,Time} is present, the gen_server process
478                  is allowed to spend Time milliseconds initializing or it  is
479                  terminated and the start function returns {error,timeout}.
480
481                * If    option    {hibernate_after,HibernateAfterTimeout}   is
482                  present, the gen_server process awaits any message  for  Hi‐
483                  bernateAfterTimeout  milliseconds  and  if no message is re‐
484                  ceived, the process goes into hibernation automatically  (by
485                  calling proc_lib:hibernate/3).
486
487                * If  option  {debug,Dbgs}  is  present, the corresponding sys
488                  function is called for each item in Dbgs; see sys(3).
489
490                * If option {spawn_opt,SOpts} is present, SOpts is  passed  as
491                  option list to the spawn_opt BIF, which is used to spawn the
492                  gen_server process; see spawn_opt/2.
493
494          Note:
495              Using spawn option monitor is not allowed, it causes  the  func‐
496              tion to fail with reason badarg.
497
498
499              If  the  gen_server process is successfully created and initial‐
500              ized, the function returns {ok,Pid}, where Pid is the pid of the
501              gen_server  process.  If a process with the specified ServerName
502              exists    already,    the    function    returns     {error,{al‐
503              ready_started,Pid}}, where Pid is the pid of that process.
504
505              If  Module:init/1  fails  with Reason, the function returns {er‐
506              ror,Reason}. If Module:init/1 returns {stop,Reason}  or  ignore,
507              the  process  is terminated and the function returns {error,Rea‐
508              son} or ignore, respectively. An exit signal with the same  Rea‐
509              son  (or  normal  if  Module:init/1  returns  ignore) is sent to
510              linked processes and ports.
511
512       start_monitor(Module, Args, Options) -> Result
513       start_monitor(ServerName, Module, Args, Options) -> Result
514
515              Types:
516
517                 ServerName = {local,Name} | {global,GlobalName}
518                  | {via,Module,ViaName}
519                  Name = atom()
520                  GlobalName = ViaName = term()
521                 Module = atom()
522                 Args = term()
523                 Options = [Option]
524                  Option =  {debug,Dbgs}  |  {timeout,Time}  |  {hibernate_af‐
525                 ter,HibernateAfterTimeout} | {spawn_opt,SOpts}
526                  Dbgs = [Dbg]
527                  Dbg  =  trace  | log | statistics | {log_to_file,FileName} |
528                 {install,{Func,FuncState}}
529                  SOpts = [term()]
530                 Result = {ok,{Pid,Mon}} | ignore | {error,Error}
531                  Pid = pid()
532                  Error = {already_started,Pid} | term()
533
534              Creates a standalone gen_server process, that is,  a  gen_server
535              process  that is not part of a supervision tree (and thus has no
536              supervisor) and atomically sets up a monitor to the  newly  cre‐
537              ated server.
538
539              For   a   description   of  arguments  and  return  values,  see
540              start_link/3,4. Note that the return value on  successful  start
541              differs   from  start_link/3,4.  start_monitor/3,4  will  return
542              {ok,{Pid,Mon}} where  Pid  is  the  process  identifier  of  the
543              server,  and Mon is a reference to the monitor set up to monitor
544              the server. If the start is not successful, the caller  will  be
545              blocked  until  the  DOWN  message has been received and removed
546              from the message queue.
547
548       stop(ServerRef) -> ok
549       stop(ServerRef, Reason, Timeout) -> ok
550
551              Types:
552
553                 ServerRef = Name | {Name,Node} | {global,GlobalName}
554                  | {via,Module,ViaName} | pid()
555                  Node = atom()
556                  GlobalName = ViaName = term()
557                 Reason = term()
558                 Timeout = int()>0 | infinity
559
560              Orders a generic server to exit with the  specified  Reason  and
561              waits  for  it  to  terminate. The gen_server process calls Mod‐
562              ule:terminate/2 before exiting.
563
564              The function returns ok if the server terminates  with  the  ex‐
565              pected reason. Any other reason than normal, shutdown, or {shut‐
566              down,Term} causes an error report to be issued using  logger(3).
567              An  exit signal with the same reason is sent to linked processes
568              and ports. The default Reason is normal.
569
570              Timeout is an integer greater than zero that specifies how  many
571              milliseconds  to  wait  for the server to terminate, or the atom
572              infinity to wait indefinitely.  Defaults  to  infinity.  If  the
573              server  has  not terminated within the specified time, a timeout
574              exception is raised.
575
576              If the process does not exist, a noproc exception is raised.
577
578       wait_response(RequestId, Timeout) -> Result
579
580              Types:
581
582                 RequestId = term()
583                 Result = {reply, Reply} | timeout | {error, {Reason,  Server‐
584                 Ref}}
585                 Reply = term()
586                 Timeout = timeout()
587                 Reason = term()
588                 ServerRef = Name | {Name,Node} | {global,GlobalName}
589                  | {via,Module,ViaName} | pid()
590                  Node = atom()
591                  GlobalName = ViaName = term()
592
593              This function is used to wait for a reply of a request made with
594              send_request/2 from the gen_server process. This  function  must
595              be  called  from  the same process from which send_request/2 was
596              made.
597
598              Timeout is an integer greater then or equal to zero that  speci‐
599              fies how many milliseconds to wait for an reply, or the atom in‐
600              finity to wait indefinitely. If no reply is received within  the
601              specified  time,  the function returns timeout and no cleanup is
602              done, and thus the function can be invoked  repeatedly  until  a
603              reply is returned.
604
605              The  return  value  Reply is defined in the return value of Mod‐
606              ule:handle_call/3.
607
608              The function returns an error if the gen_server dies  before  or
609              during this request.
610
611              The difference between receive_response() and wait_response() is
612              that receive_response() abandons the request at timeout so  that
613              a  potential  future  response is ignored, while wait_response()
614              does not.
615

CALLBACK FUNCTIONS

617       The following functions are to be exported from a  gen_server  callback
618       module.
619

EXPORTS

621       Module:code_change(OldVsn,  State,  Extra)  -> {ok, NewState} | {error,
622       Reason}
623
624              Types:
625
626                 OldVsn = Vsn | {down, Vsn}
627                  Vsn = term()
628                 State = NewState = term()
629                 Extra = term()
630                 Reason = term()
631
632          Note:
633              This callback is optional, so callback modules need  not  export
634              it.  If a release upgrade/downgrade with Change={advanced,Extra}
635              specified in the appup file is made when code_change/3 isn't im‐
636              plemented the process will crash with an undef exit reason.
637
638
639              This  function  is  called by a gen_server process when it is to
640              update its internal state during  a  release  upgrade/downgrade,
641              that  is, when the instruction {update,Module,Change,...}, where
642              Change={advanced,Extra}, is specifed in the appup file. For more
643              information,  see  section  Release Handling Instructions in OTP
644              Design Principles.
645
646              For an upgrade, OldVsn is Vsn, and for a  downgrade,  OldVsn  is
647              {down,Vsn}.  Vsn  is  defined by the vsn attribute(s) of the old
648              version of the callback module Module. If no such  attribute  is
649              defined, the version is the checksum of the Beam file.
650
651              State is the internal state of the gen_server process.
652
653              Extra  is  passed  "as is" from the {advanced,Extra} part of the
654              update instruction.
655
656              If successful, the function must  return  the  updated  internal
657              state.
658
659              If  the  function  returns  {error,Reason},  the ongoing upgrade
660              fails and rolls back to the old release.
661
662       Module:format_status(Opt, [PDict, State]) -> Status
663
664              Types:
665
666                 Opt = normal | terminate
667                 PDict = [{Key, Value}]
668                 State = term()
669                 Status = term()
670
671          Note:
672              This callback is optional, so callback modules need  not  export
673              it.  The  gen_server module provides a default implementation of
674              this function that returns the callback module state.
675
676
677              This function is called by a gen_server process in the following
678              situations:
679
680                * One  of  sys:get_status/1,2 is invoked to get the gen_server
681                  status. Opt is set to the atom normal.
682
683                * The gen_server process terminates abnormally and logs an er‐
684                  ror. Opt is set to the atom terminate.
685
686              This  function is useful for changing the form and appearance of
687              the gen_server status for these cases. A callback module wishing
688              to  change  the  sys:get_status/1,2 return value, as well as how
689              its status appears in termination error  logs,  exports  an  in‐
690              stance  of  format_status/2  that  returns a term describing the
691              current status of the gen_server process.
692
693              PDict is the current value of  the  process  dictionary  of  the
694              gen_server process..
695
696              State is the internal state of the gen_server process.
697
698              The  function  is  to return Status, a term that changes the de‐
699              tails of the current state and status of the gen_server process.
700              There  are  no restrictions on the form Status can take, but for
701              the sys:get_status/1,2 case (when Opt  is  normal),  the  recom‐
702              mended form for the Status value is [{data, [{"State", Term}]}],
703              where Term provides relevant details of  the  gen_server  state.
704              Following  this recommendation is not required, but it makes the
705              callback  module  status  consistent  with  the  rest   of   the
706              sys:get_status/1,2 return value.
707
708              One use for this function is to return compact alternative state
709              representations to avoid that large state terms are  printed  in
710              log files.
711
712       Module:handle_call(Request, From, State) -> Result
713
714              Types:
715
716                 Request = term()
717                 From = {pid(),Tag}
718                 State = term()
719                 Result = {reply,Reply,NewState} | {reply,Reply,NewState,Time‐
720                 out}
721                  | {reply,Reply,NewState,hibernate}
722                  | {reply,Reply,NewState,{continue,Continue}}
723                  | {noreply,NewState} | {noreply,NewState,Timeout}
724                  | {noreply,NewState,hibernate}
725                  | {noreply,NewState,{continue,Continue}}
726                  | {stop,Reason,Reply,NewState} | {stop,Reason,NewState}
727                  Reply = term()
728                  NewState = term()
729                  Timeout = int()>=0 | infinity
730                  Continue = term()
731                  Reason = term()
732
733              Whenever a gen_server process  receives  a  request  sent  using
734              call/2,3  or multi_call/2,3,4, this function is called to handle
735              the request.
736
737              Request is the Request argument provided to call or multi_call.
738
739              From is a tuple {Pid,Tag}, where Pid is the pid  of  the  client
740              and Tag is a unique tag.
741
742              State is the internal state of the gen_server process.
743
744                * If  {reply,Reply,NewState}  is  returned,  {reply,Reply,New‐
745                  State,Timeout} or {reply,Reply,NewState,hibernate}, Reply is
746                  given  back  to  From as the return value of call/2,3 or in‐
747                  cluded  in  the  return  value  of   multi_call/2,3,4.   The
748                  gen_server  process then continues executing with the possi‐
749                  bly updated internal state NewState.
750
751                  For  a  description  of  Timeout  and  hibernate,  see  Mod‐
752                  ule:init/1.
753
754                * If  {noreply,NewState}  is returned, {noreply,NewState,Time‐
755                  out},  or   {noreply,NewState,hibernate},   the   gen_server
756                  process continues executing with NewState. Any reply to From
757                  must be specified explicitly using reply/2.
758
759                * If {stop,Reason,Reply,NewState} is returned, Reply is  given
760                  back to From.
761
762                * If  {stop,Reason,NewState}  is  returned,  any reply to From
763                  must be specified explicitly using reply/2.  The  gen_server
764                  process  then  calls  Module:terminate(Reason,NewState)  and
765                  terminates.
766
767       Module:handle_cast(Request, State) -> Result
768
769              Types:
770
771                 Request = term()
772                 State = term()
773                 Result = {noreply,NewState} | {noreply,NewState,Timeout}
774                  | {noreply,NewState,hibernate}
775                  | {noreply,NewState,{continue,Continue}}
776                  | {stop,Reason,NewState}
777                  NewState = term()
778                  Timeout = int()>=0 | infinity
779                  Continue = term()
780                  Reason = term()
781
782              Whenever a gen_server process  receives  a  request  sent  using
783              cast/2  or abcast/2,3, this function is called to handle the re‐
784              quest.
785
786              For a description of the arguments and possible  return  values,
787              see Module:handle_call/3.
788
789       Module:handle_continue(Continue, State) -> Result
790
791              Types:
792
793                 Continue = term()
794                 State = term()
795                 Result = {noreply,NewState} | {noreply,NewState,Timeout}
796                  | {noreply,NewState,hibernate}
797                  | {noreply,NewState,{continue,Continue}}
798                  | {stop,Reason,NewState}
799                  NewState = term()
800                  Timeout = int()>=0 | infinity
801                  Continue = term()
802                  Reason = normal | term()
803
804          Note:
805              This callback is optional, so callback modules need to export it
806              only if they return {continue,Continue} from  another  callback.
807              If  continue  is  used  and the callback is not implemented, the
808              process will exit with undef error.
809
810
811              This function is called by a gen_server process whenever a  pre‐
812              vious  callback  returns {continue, Continue}. handle_continue/2
813              is invoked immediately after the previous callback, which  makes
814              it useful for performing work after initialization or for split‐
815              ting the work in a callback  in  multiple  steps,  updating  the
816              process state along the way.
817
818              For  a  description  of  the other arguments and possible return
819              values, see Module:handle_call/3.
820
821       Module:handle_info(Info, State) -> Result
822
823              Types:
824
825                 Info = timeout | term()
826                 State = term()
827                 Result = {noreply,NewState} | {noreply,NewState,Timeout}
828                  | {noreply,NewState,hibernate}
829                  | {noreply,NewState,{continue,Continue}}
830                  | {stop,Reason,NewState}
831                  NewState = term()
832                  Timeout = int()>=0 | infinity
833                  Reason = normal | term()
834
835          Note:
836              This callback is optional, so callback modules need  not  export
837              it.  The  gen_server module provides a default implementation of
838              this function that logs about the unexpected Info message, drops
839              it and returns {noreply, State}.
840
841
842              This  function is called by a gen_server process when a time-out
843              occurs or when it receives any other message than a  synchronous
844              or asynchronous request (or a system message).
845
846              Info  is either the atom timeout, if a time-out has occurred, or
847              the received message.
848
849              For a description of the other  arguments  and  possible  return
850              values, see Module:handle_call/3.
851
852       Module:init(Args) -> Result
853
854              Types:
855
856                 Args = term()
857                 Result  =  {ok,State} | {ok,State,Timeout} | {ok,State,hiber‐
858                 nate}
859                  | {ok,State,{continue,Continue}} | {stop,Reason} | ignore
860                  State = term()
861                  Timeout = int()>=0 | infinity
862                  Reason = term()
863
864              Whenever  a  gen_server  process  is  started  using  start/3,4,
865              start_monitor/3,4, or start_link/3,4, this function is called by
866              the new process to initialize.
867
868              Args is the Args argument provided to the start function.
869
870              If the initialization is successful, the function is  to  return
871              {ok,State},    {ok,State,Timeout},    {ok,State,hibernate},   or
872              {ok,State,{continue,Continue}} where State is the internal state
873              of the gen_server process.
874
875              If  an integer time-out value is provided, a time-out occurs un‐
876              less a request or a message is received within Timeout millisec‐
877              onds. A time-out is represented by the atom timeout, which is to
878              be handled by the Module:handle_info/2  callback  function.  The
879              atom  infinity can be used to wait indefinitely, this is the de‐
880              fault value.
881
882              If hibernate is specified  instead  of  a  time-out  value,  the
883              process  goes into hibernation when waiting for the next message
884              to arrive (by calling proc_lib:hibernate/3).
885
886              If {continue,Continue} is specified, the  process  will  execute
887              the Module:handle_continue/2 callback function, with Continue as
888              the first argument.
889
890              If  the  initialization  fails,  the  function  is   to   return
891              {stop,Reason}, where Reason is any term, or ignore. An exit sig‐
892              nal with this Reason (or with reason normal  if  ignore  is  re‐
893              turned)  is  sent  to linked processes and ports, notably to the
894              process starting the gen_server when start_link/3,4 is used.
895
896       Module:terminate(Reason, State)
897
898              Types:
899
900                 Reason = normal | shutdown | {shutdown,term()} | term()
901                 State = term()
902
903          Note:
904              This callback is optional, so callback modules need  not  export
905              it.  The  gen_server  module  provides  a default implementation
906              without cleanup.
907
908
909              This function is called by a gen_server process when it is about
910              to  terminate.  It is to be the opposite of Module:init/1 and do
911              any necessary cleaning  up.  When  it  returns,  the  gen_server
912              process terminates with Reason. The return value is ignored.
913
914              Reason  is  a term denoting the stop reason and State is the in‐
915              ternal state of the gen_server process.
916
917              Reason depends on why the gen_server process is terminating.  If
918              it  is because another callback function has returned a stop tu‐
919              ple {stop,..}, Reason has the value specified in that tuple.  If
920              it is because of a failure, Reason is the error reason.
921
922              If  the  gen_server process is part of a supervision tree and is
923              ordered by its supervisor to terminate, this function is  called
924              with Reason=shutdown if the following conditions apply:
925
926                * The gen_server process has been set to trap exit signals.
927
928                * The  shutdown strategy as defined in the child specification
929                  of the supervisor is an integer  time-out  value,  not  bru‐
930                  tal_kill.
931
932              Even  if  the  gen_server  process  is not part of a supervision
933              tree, this function is called if it receives an  'EXIT'  message
934              from its parent. Reason is the same as in the 'EXIT' message.
935
936              Otherwise, the gen_server process terminates immediately.
937
938              Notice  that  for  any  other  reason  than normal, shutdown, or
939              {shutdown,Term}, the gen_server process is assumed to  terminate
940              because  of  an  error  and an error report is issued using log‐
941              ger(3).
942
943              When the gen_server process exits, an exit signal with the  same
944              reason is sent to linked processes and ports.
945

SEE ALSO

947       gen_event(3), gen_statem(3), proc_lib(3), supervisor(3), sys(3)
948
949
950
951Ericsson AB                      stdlib 3.16.1                   gen_server(3)
Impressum