1gen_server(3) Erlang Module Definition gen_server(3)
2
3
4
6 gen_server - Generic server behavior.
7
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_link -----> Module:init/1
25
26 gen_server:stop -----> Module:terminate/2
27
28 gen_server:call
29 gen_server:multi_call -----> Module:handle_call/3
30
31 gen_server:cast
32 gen_server:abcast -----> Module:handle_cast/2
33
34 - -----> Module:handle_info/2
35
36 - -----> Module:terminate/2
37
38 - -----> Module:code_change/3
39
40 If a callback function fails or returns a bad value, the gen_server
41 process terminates.
42
43 A gen_server process handles system messages as described in sys(3).
44 The sys module can be used for debugging a gen_server process.
45
46 Notice that a gen_server process does not trap exit signals automati‐
47 cally, this must be explicitly initiated in the callback module.
48
49 Unless otherwise stated, all functions in this module fail if the spec‐
50 ified gen_server process does not exist or if bad arguments are speci‐
51 fied.
52
53 The gen_server process can go into hibernation (see erlang:hibernate/3)
54 if a callback function specifies 'hibernate' instead of a time-out
55 value. This can be useful if the server is expected to be idle for a
56 long time. However, use this feature with care, as hibernation implies
57 at least two garbage collections (when hibernating and shortly after
58 waking up) and is not something you want to do between each call to a
59 busy server.
60
62 abcast(Name, Request) -> abcast
63 abcast(Nodes, Name, Request) -> abcast
64
65 Types:
66
67 Nodes = [Node]
68 Node = atom()
69 Name = atom()
70 Request = term()
71
72 Sends an asynchronous request to the gen_server processes
73 locally registered as Name at the specified nodes. The function
74 returns immediately and ignores nodes that do not exist, or
75 where the gen_server Name does not exist. The gen_server pro‐
76 cesses call Module:handle_cast/2 to handle the request.
77
78 For a description of the arguments, see multi_call/2,3,4.
79
80 call(ServerRef, Request) -> Reply
81 call(ServerRef, Request, Timeout) -> Reply
82
83 Types:
84
85 ServerRef = Name | {Name,Node} | {global,GlobalName}
86 | {via,Module,ViaName} | pid()
87 Node = atom()
88 GlobalName = ViaName = term()
89 Request = term()
90 Timeout = int()>0 | infinity
91 Reply = term()
92
93 Makes a synchronous call to the ServerRef of the gen_server
94 process by sending a request and waiting until a reply arrives
95 or a time-out occurs. The gen_server process calls Module:han‐
96 dle_call/3 to handle the request.
97
98 ServerRef can be any of the following:
99
100 * The pid
101
102 * Name, if the gen_server process is locally registered
103
104 * {Name,Node}, if the gen_server process is locally registered
105 at another node
106
107 * {global,GlobalName}, if the gen_server process is globally
108 registered
109
110 * {via,Module,ViaName}, if the gen_server process is regis‐
111 tered through an alternative process registry
112
113 Request is any term that is passed as one of the arguments to
114 Module:handle_call/3.
115
116 Timeout is an integer greater than zero that specifies how many
117 milliseconds to wait for a reply, or the atom infinity to wait
118 indefinitely. Defaults to 5000. If no reply is received within
119 the specified time, the function call fails. If the caller
120 catches the failure and continues running, and the server is
121 just late with the reply, it can arrive at any time later into
122 the message queue of the caller. The caller must in this case be
123 prepared for this and discard any such garbage messages that are
124 two element tuples with a reference as the first element.
125
126 The return value Reply is defined in the return value of Mod‐
127 ule:handle_call/3.
128
129 The call can fail for many reasons, including time-out and the
130 called gen_server process dying before or during the call.
131
132 cast(ServerRef, Request) -> ok
133
134 Types:
135
136 ServerRef = Name | {Name,Node} | {global,GlobalName}
137 | {via,Module,ViaName} | pid()
138 Node = atom()
139 GlobalName = ViaName = term()
140 Request = term()
141
142 Sends an asynchronous request to the ServerRef of the gen_server
143 process and returns ok immediately, ignoring if the destination
144 node or gen_server process does not exist. The gen_server
145 process calls Module:handle_cast/2 to handle the request.
146
147 For a description of ServerRef, see call/2,3.
148
149 Request is any term that is passed as one of the arguments to
150 Module:handle_cast/2.
151
152 enter_loop(Module, Options, State)
153 enter_loop(Module, Options, State, ServerName)
154 enter_loop(Module, Options, State, Timeout)
155 enter_loop(Module, Options, State, ServerName, Timeout)
156
157 Types:
158
159 Module = atom()
160 Options = [Option]
161 Option = {debug,Dbgs} | {hibernate_after,HibernateAfterTime‐
162 out}
163 Dbgs = [Dbg]
164 Dbg = trace | log | statistics
165 | {log_to_file,FileName} | {install,{Func,FuncState}}
166 State = term()
167 ServerName = {local,Name} | {global,GlobalName}
168 | {via,Module,ViaName}
169 Name = atom()
170 GlobalName = ViaName = term()
171 Timeout = int() | infinity
172
173 Makes an existing process into a gen_server process. Does not
174 return, instead the calling process enters the gen_server
175 process receive loop and becomes a gen_server process. The
176 process must have been started using one of the start functions
177 in proc_lib(3). The user is responsible for any initialization
178 of the process, including registering a name for it.
179
180 This function is useful when a more complex initialization pro‐
181 cedure is needed than the gen_server process behavior provides.
182
183 Module, Options, and ServerName have the same meanings as when
184 calling start[_link]/3,4. However, if ServerName is specified,
185 the process must have been registered accordingly before this
186 function is called.
187
188 State and Timeout have the same meanings as in the return value
189 of Module:init/1. The callback module Module does not need to
190 export an init/1 function.
191
192 The function fails if the calling process was not started by a
193 proc_lib start function, or if it is not registered according to
194 ServerName.
195
196 multi_call(Name, Request) -> Result
197 multi_call(Nodes, Name, Request) -> Result
198 multi_call(Nodes, Name, Request, Timeout) -> Result
199
200 Types:
201
202 Nodes = [Node]
203 Node = atom()
204 Name = atom()
205 Request = term()
206 Timeout = int()>=0 | infinity
207 Result = {Replies,BadNodes}
208 Replies = [{Node,Reply}]
209 Reply = term()
210 BadNodes = [Node]
211
212 Makes a synchronous call to all gen_server processes locally
213 registered as Name at the specified nodes by first sending a
214 request to every node and then waits for the replies. The
215 gen_server process calls Module:handle_call/3 to handle the
216 request.
217
218 The function returns a tuple {Replies,BadNodes}, where Replies
219 is a list of {Node,Reply} and BadNodes is a list of node that
220 either did not exist, or where the gen_server Name did not exist
221 or did not reply.
222
223 Nodes is a list of node names to which the request is to be
224 sent. Default value is the list of all known nodes
225 [node()|nodes()].
226
227 Name is the locally registered name of each gen_server process.
228
229 Request is any term that is passed as one of the arguments to
230 Module:handle_call/3.
231
232 Timeout is an integer greater than zero that specifies how many
233 milliseconds to wait for each reply, or the atom infinity to
234 wait indefinitely. Defaults to infinity. If no reply is received
235 from a node within the specified time, the node is added to
236 BadNodes.
237
238 When a reply Reply is received from the gen_server process at a
239 node Node, {Node,Reply} is added to Replies. Reply is defined in
240 the return value of Module:handle_call/3.
241
242 Warning:
243 If one of the nodes cannot process monitors, for example, C or
244 Java nodes, and the gen_server process is not started when the
245 requests are sent, but starts within 2 seconds, this function
246 waits the whole Timeout, which may be infinity.
247
248 This problem does not exist if all nodes are Erlang nodes.
249
250
251 To prevent late answers (after the time-out) from polluting the
252 message queue of the caller, a middleman process is used to do
253 the calls. Late answers are then discarded when they arrive to a
254 terminated process.
255
256 reply(Client, Reply) -> Result
257
258 Types:
259
260 Client - see below
261 Reply = term()
262 Result = term()
263
264 This function can be used by a gen_server process to explicitly
265 send a reply to a client that called call/2,3 or
266 multi_call/2,3,4, when the reply cannot be defined in the return
267 value of Module:handle_call/3.
268
269 Client must be the From argument provided to the callback func‐
270 tion. Reply is any term given back to the client as the return
271 value of call/2,3 or multi_call/2,3,4.
272
273 The return value Result is not further defined, and is always to
274 be ignored.
275
276 start(Module, Args, Options) -> Result
277 start(ServerName, Module, Args, Options) -> Result
278
279 Types:
280
281 ServerName = {local,Name} | {global,GlobalName}
282 | {via,Module,ViaName}
283 Name = atom()
284 GlobalName = ViaName = term()
285 Module = atom()
286 Args = term()
287 Options = [Option]
288 Option = {debug,Dbgs} | {timeout,Time} | {hiber‐
289 nate_after,HibernateAfterTimeout} | {spawn_opt,SOpts}
290 Dbgs = [Dbg]
291 Dbg = trace | log | statistics | {log_to_file,FileName} |
292 {install,{Func,FuncState}}
293 SOpts = [term()]
294 Result = {ok,Pid} | ignore | {error,Error}
295 Pid = pid()
296 Error = {already_started,Pid} | term()
297
298 Creates a standalone gen_server process, that is, a gen_server
299 process that is not part of a supervision tree and thus has no
300 supervisor.
301
302 For a description of arguments and return values, see
303 start_link/3,4.
304
305 start_link(Module, Args, Options) -> Result
306 start_link(ServerName, Module, Args, Options) -> Result
307
308 Types:
309
310 ServerName = {local,Name} | {global,GlobalName}
311 | {via,Module,ViaName}
312 Name = atom()
313 GlobalName = ViaName = term()
314 Module = atom()
315 Args = term()
316 Options = [Option]
317 Option = {debug,Dbgs} | {timeout,Time} | {hiber‐
318 nate_after,HibernateAfterTimeout} | {spawn_opt,SOpts}
319 Dbgs = [Dbg]
320 Dbg = trace | log | statistics | {log_to_file,FileName} |
321 {install,{Func,FuncState}}
322 SOpts = [term()]
323 Result = {ok,Pid} | ignore | {error,Error}
324 Pid = pid()
325 Error = {already_started,Pid} | term()
326
327 Creates a gen_server process as part of a supervision tree. This
328 function is to be called, directly or indirectly, by the super‐
329 visor. For example, it ensures that the gen_server process is
330 linked to the supervisor.
331
332 The gen_server process calls Module:init/1 to initialize. To
333 ensure a synchronized startup procedure, start_link/3,4 does not
334 return until Module:init/1 has returned.
335
336 * If ServerName={local,Name}, the gen_server process is regis‐
337 tered locally as Name using register/2.
338
339 * If ServerName={global,GlobalName}, the gen_server process id
340 registered globally as GlobalName using global:regis‐
341 ter_name/2 If no name is provided, the gen_server process is
342 not registered.
343
344 * If ServerName={via,Module,ViaName}, the gen_server process
345 registers with the registry represented by Module. The Mod‐
346 ule callback is to export the functions register_name/2,
347 unregister_name/1, whereis_name/1, and send/2, which are to
348 behave like the corresponding functions in global. Thus,
349 {via,global,GlobalName} is a valid reference.
350
351 Module is the name of the callback module.
352
353 Args is any term that is passed as the argument to Mod‐
354 ule:init/1.
355
356 * If option {timeout,Time} is present, the gen_server process
357 is allowed to spend Time milliseconds initializing or it is
358 terminated and the start function returns {error,timeout}.
359
360 * If option {hibernate_after,HibernateAfterTimeout} is
361 present, the gen_server process awaits any message for
362 HibernateAfterTimeout milliseconds and if no message is
363 received, the process goes into hibernation automatically
364 (by calling proc_lib:hibernate/3).
365
366 * If option {debug,Dbgs} is present, the corresponding sys
367 function is called for each item in Dbgs; see sys(3).
368
369 * If option {spawn_opt,SOpts} is present, SOpts is passed as
370 option list to the spawn_opt BIF, which is used to spawn the
371 gen_server process; see spawn_opt/2.
372
373 Note:
374 Using spawn option monitor is not allowed, it causes the func‐
375 tion to fail with reason badarg.
376
377
378 If the gen_server process is successfully created and initial‐
379 ized, the function returns {ok,Pid}, where Pid is the pid of the
380 gen_server process. If a process with the specified ServerName
381 exists already, the function returns
382 {error,{already_started,Pid}}, where Pid is the pid of that
383 process.
384
385 If Module:init/1 fails with Reason, the function returns
386 {error,Reason}. If Module:init/1 returns {stop,Reason} or
387 ignore, the process is terminated and the function returns
388 {error,Reason} or ignore, respectively.
389
390 stop(ServerRef) -> ok
391 stop(ServerRef, Reason, Timeout) -> ok
392
393 Types:
394
395 ServerRef = Name | {Name,Node} | {global,GlobalName}
396 | {via,Module,ViaName} | pid()
397 Node = atom()
398 GlobalName = ViaName = term()
399 Reason = term()
400 Timeout = int()>0 | infinity
401
402 Orders a generic server to exit with the specified Reason and
403 waits for it to terminate. The gen_server process calls Mod‐
404 ule:terminate/2 before exiting.
405
406 The function returns ok if the server terminates with the
407 expected reason. Any other reason than normal, shutdown, or
408 {shutdown,Term} causes an error report to be issued using
409 error_logger:format/2. The default Reason is normal.
410
411 Timeout is an integer greater than zero that specifies how many
412 milliseconds to wait for the server to terminate, or the atom
413 infinity to wait indefinitely. Defaults to infinity. If the
414 server has not terminated within the specified time, a timeout
415 exception is raised.
416
417 If the process does not exist, a noproc exception is raised.
418
420 The following functions are to be exported from a gen_server callback
421 module.
422
424 Module:code_change(OldVsn, State, Extra) -> {ok, NewState} | {error,
425 Reason}
426
427 Types:
428
429 OldVsn = Vsn | {down, Vsn}
430 Vsn = term()
431 State = NewState = term()
432 Extra = term()
433 Reason = term()
434
435 Note:
436 This callback is optional, so callback modules need not export
437 it. If a release upgrade/downgrade with Change={advanced,Extra}
438 specified in the appup file is made when code_change/3 isn't
439 implemented the process will crash with an undef exit reason.
440
441
442 This function is called by a gen_server process when it is to
443 update its internal state during a release upgrade/downgrade,
444 that is, when the instruction {update,Module,Change,...}, where
445 Change={advanced,Extra}, is specifed in the appup file. For more
446 information, see section Release Handling Instructions in OTP
447 Design Principles.
448
449 For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is
450 {down,Vsn}. Vsn is defined by the vsn attribute(s) of the old
451 version of the callback module Module. If no such attribute is
452 defined, the version is the checksum of the Beam file.
453
454 State is the internal state of the gen_server process.
455
456 Extra is passed "as is" from the {advanced,Extra} part of the
457 update instruction.
458
459 If successful, the function must return the updated internal
460 state.
461
462 If the function returns {error,Reason}, the ongoing upgrade
463 fails and rolls back to the old release.
464
465 Module:format_status(Opt, [PDict, State]) -> Status
466
467 Types:
468
469 Opt = normal | terminate
470 PDict = [{Key, Value}]
471 State = term()
472 Status = term()
473
474 Note:
475 This callback is optional, so callback modules need not export
476 it. The gen_server module provides a default implementation of
477 this function that returns the callback module state.
478
479
480 This function is called by a gen_server process in the following
481 situations:
482
483 * One of sys:get_status/1,2 is invoked to get the gen_server
484 status. Opt is set to the atom normal.
485
486 * The gen_server process terminates abnormally and logs an
487 error. Opt is set to the atom terminate.
488
489 This function is useful for changing the form and appearance of
490 the gen_server status for these cases. A callback module wishing
491 to change the sys:get_status/1,2 return value, as well as how
492 its status appears in termination error logs, exports an
493 instance of format_status/2 that returns a term describing the
494 current status of the gen_server process.
495
496 PDict is the current value of the process dictionary of the
497 gen_server process..
498
499 State is the internal state of the gen_server process.
500
501 The function is to return Status, a term that changes the
502 details of the current state and status of the gen_server
503 process. There are no restrictions on the form Status can take,
504 but for the sys:get_status/1,2 case (when Opt is normal), the
505 recommended form for the Status value is [{data, [{"State",
506 Term}]}], where Term provides relevant details of the gen_server
507 state. Following this recommendation is not required, but it
508 makes the callback module status consistent with the rest of the
509 sys:get_status/1,2 return value.
510
511 One use for this function is to return compact alternative state
512 representations to avoid that large state terms are printed in
513 log files.
514
515 Module:handle_call(Request, From, State) -> Result
516
517 Types:
518
519 Request = term()
520 From = {pid(),Tag}
521 State = term()
522 Result = {reply,Reply,NewState} | {reply,Reply,NewState,Time‐
523 out}
524 | {reply,Reply,NewState,hibernate}
525 | {noreply,NewState} | {noreply,NewState,Timeout}
526 | {noreply,NewState,hibernate}
527 | {stop,Reason,Reply,NewState} | {stop,Reason,NewState}
528 Reply = term()
529 NewState = term()
530 Timeout = int()>=0 | infinity
531 Reason = term()
532
533 Whenever a gen_server process receives a request sent using
534 call/2,3 or multi_call/2,3,4, this function is called to handle
535 the request.
536
537 Request is the Request argument provided to call or multi_call.
538
539 From is a tuple {Pid,Tag}, where Pid is the pid of the client
540 and Tag is a unique tag.
541
542 State is the internal state of the gen_server process.
543
544 * If {reply,Reply,NewState} is returned, {reply,Reply,New‐
545 State,Timeout} or {reply,Reply,NewState,hibernate}, Reply is
546 given back to From as the return value of call/2,3 or
547 included in the return value of multi_call/2,3,4. The
548 gen_server process then continues executing with the possi‐
549 bly updated internal state NewState.
550
551 For a description of Timeout and hibernate, see Mod‐
552 ule:init/1.
553
554 * If {noreply,NewState} is returned, {noreply,NewState,Time‐
555 out}, or {noreply,NewState,hibernate}, the gen_server
556 process continues executing with NewState. Any reply to From
557 must be specified explicitly using reply/2.
558
559 * If {stop,Reason,Reply,NewState} is returned, Reply is given
560 back to From.
561
562 * If {stop,Reason,NewState} is returned, any reply to From
563 must be specified explicitly using reply/2. The gen_server
564 process then calls Module:terminate(Reason,NewState) and
565 terminates.
566
567 Module:handle_cast(Request, State) -> Result
568
569 Types:
570
571 Request = term()
572 State = term()
573 Result = {noreply,NewState} | {noreply,NewState,Timeout}
574 | {noreply,NewState,hibernate}
575 | {stop,Reason,NewState}
576 NewState = term()
577 Timeout = int()>=0 | infinity
578 Reason = term()
579
580 Whenever a gen_server process receives a request sent using
581 cast/2 or abcast/2,3, this function is called to handle the
582 request.
583
584 For a description of the arguments and possible return values,
585 see Module:handle_call/3.
586
587 Module:handle_info(Info, State) -> Result
588
589 Types:
590
591 Info = timeout | term()
592 State = term()
593 Result = {noreply,NewState} | {noreply,NewState,Timeout}
594 | {noreply,NewState,hibernate}
595 | {stop,Reason,NewState}
596 NewState = term()
597 Timeout = int()>=0 | infinity
598 Reason = normal | term()
599
600 Note:
601 This callback is optional, so callback modules need not export
602 it. The gen_server module provides a default implementation of
603 this function that logs about the unexpected Info message, drops
604 it and returns {noreply, State}.
605
606
607 This function is called by a gen_server process when a time-out
608 occurs or when it receives any other message than a synchronous
609 or asynchronous request (or a system message).
610
611 Info is either the atom timeout, if a time-out has occurred, or
612 the received message.
613
614 For a description of the other arguments and possible return
615 values, see Module:handle_call/3.
616
617 Module:init(Args) -> Result
618
619 Types:
620
621 Args = term()
622 Result = {ok,State} | {ok,State,Timeout} | {ok,State,hiber‐
623 nate}
624 | {stop,Reason} | ignore
625 State = term()
626 Timeout = int()>=0 | infinity
627 Reason = term()
628
629 Whenever a gen_server process is started using start/3,4 or
630 start_link/3,4, this function is called by the new process to
631 initialize.
632
633 Args is the Args argument provided to the start function.
634
635 If the initialization is successful, the function is to return
636 {ok,State}, {ok,State,Timeout}, or {ok,State,hibernate}, where
637 State is the internal state of the gen_server process.
638
639 If an integer time-out value is provided, a time-out occurs
640 unless a request or a message is received within Timeout mil‐
641 liseconds. A time-out is represented by the atom timeout, which
642 is to be handled by the Module:handle_info/2 callback function.
643 The atom infinity can be used to wait indefinitely, this is the
644 default value.
645
646 If hibernate is specified instead of a time-out value, the
647 process goes into hibernation when waiting for the next message
648 to arrive (by calling proc_lib:hibernate/3).
649
650 If the initialization fails, the function is to return
651 {stop,Reason}, where Reason is any term, or ignore.
652
653 Module:terminate(Reason, State)
654
655 Types:
656
657 Reason = normal | shutdown | {shutdown,term()} | term()
658 State = term()
659
660 Note:
661 This callback is optional, so callback modules need not export
662 it. The gen_server module provides a default implementation
663 without cleanup.
664
665
666 This function is called by a gen_server process when it is about
667 to terminate. It is to be the opposite of Module:init/1 and do
668 any necessary cleaning up. When it returns, the gen_server
669 process terminates with Reason. The return value is ignored.
670
671 Reason is a term denoting the stop reason and State is the
672 internal state of the gen_server process.
673
674 Reason depends on why the gen_server process is terminating. If
675 it is because another callback function has returned a stop
676 tuple {stop,..}, Reason has the value specified in that tuple.
677 If it is because of a failure, Reason is the error reason.
678
679 If the gen_server process is part of a supervision tree and is
680 ordered by its supervisor to terminate, this function is called
681 with Reason=shutdown if the following conditions apply:
682
683 * The gen_server process has been set to trap exit signals.
684
685 * The shutdown strategy as defined in the child specification
686 of the supervisor is an integer time-out value, not bru‐
687 tal_kill.
688
689 Even if the gen_server process is not part of a supervision
690 tree, this function is called if it receives an 'EXIT' message
691 from its parent. Reason is the same as in the 'EXIT' message.
692
693 Otherwise, the gen_server process terminates immediately.
694
695 Notice that for any other reason than normal, shutdown, or
696 {shutdown,Term}, the gen_server process is assumed to terminate
697 because of an error and an error report is issued using
698 error_logger:format/2.
699
701 gen_event(3), gen_statem(3), proc_lib(3), supervisor(3), sys(3)
702
703
704
705Ericsson AB stdlib 3.4.5.1 gen_server(3)