File: spec_proc.html

package info (click to toggle)
erlang-doc-html 1%3A11.b.2-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 23,284 kB
  • ctags: 10,724
  • sloc: erlang: 505; ansic: 323; makefile: 62; perl: 61; sh: 45
file content (565 lines) | stat: -rw-r--r-- 16,231 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
  <TITLE>Sys and Proc_Lib</TITLE>
  <SCRIPT type="text/javascript" src="../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
      ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="6"><!-- Empty --></A>
<H2>6 Sys and Proc_Lib</H2>

<P>The module <CODE>sys</CODE> contains functions for simple debugging of
processes implemented using behaviours.
<P>There are also functions that, together with functions in
the module <CODE>proc_lib</CODE>, can be used to implement a
<STRONG>special process</STRONG>, a process which comply to the OTP design
principles without making use of a standard behaviour. They can
also be used to implement user defined (non-standard) behaviours.

<P>Both <CODE>sys</CODE> and <CODE>proc_lib</CODE> belong to the STDLIB
application.<A NAME="6.1"><!-- Empty --></A>
<H3>6.1 Simple Debugging</H3>

<P>The module <CODE>sys</CODE> contains some functions for simple debugging
of processes implemented using behaviours. We use the
<CODE>code_lock</CODE> example from
the <A HREF="fsm.html#ex">gen_event</A> chapter to
illustrate this:
<PRE>
% <STRONG>erl</STRONG>
Erlang (BEAM) emulator version 5.2.3.6 [hipe] [threads:0]

Eshell V5.2.3.6  (abort with ^G)
1&#62; <STRONG>code_lock:start_link([1,2,3,4]).</STRONG>
{ok,&#60;0.32.0&#62;}
2&#62; <STRONG>sys:statistics(code_lock, true).</STRONG>
ok
3&#62; <STRONG>sys:trace(code_lock, true).</STRONG>
ok
4&#62; <STRONG>code_lock:button(4).</STRONG>
*DBG* code_lock got event {button,4} in state closed
ok
*DBG* code_lock switched to state closed
5&#62; <STRONG> code_lock:button(3).</STRONG>
*DBG* code_lock got event {button,3} in state closed
ok
*DBG* code_lock switched to state closed
6&#62; <STRONG>code_lock:button(2).</STRONG>
*DBG* code_lock got event {button,2} in state closed
ok
*DBG* code_lock switched to state closed
7&#62; <STRONG>code_lock:button(1).</STRONG>
*DBG* code_lock got event {button,1} in state closed
ok
OPEN DOOR
*DBG* code_lock switched to state open
*DBG* code_lock got event timeout in state open
CLOSE DOOR
*DBG* code_lock switched to state closed
8&#62; <STRONG>sys:statistics(code_lock, get).</STRONG> 
{ok,[{start_time,{{2003,6,12},{14,11,40}}},
     {current_time,{{2003,6,12},{14,12,14}}},
     {reductions,333},
     {messages_in,5},
     {messages_out,0}]}
9&#62; <STRONG>sys:statistics(code_lock, false).</STRONG>
ok
10&#62; <STRONG>sys:trace(code_lock, false).</STRONG>     
ok
11&#62; <STRONG>sys:get_status(code_lock).</STRONG>
{status,&#60;0.32.0&#62;,
        {module,gen_fsm},
        [[{'$ancestors',[&#60;0.30.0&#62;]},
          {'$initial_call',{gen,init_it,
                                [gen_fsm,
                                 &#60;0.30.0&#62;,
                                 &#60;0.30.0&#62;,
                                 {local,code_lock},
                                 code_lock,
                                 [1,2,3,4],
                                 []]}}],
         running,
         &#60;0.30.0&#62;,
         [],
         [code_lock,closed,{[],[1,2,3,4]},code_lock,infinity]]}
    
</PRE>
<A NAME="6.2"><!-- Empty --></A>
<H3>6.2 Special Processes</H3>

<P>This section describes how to write a process which comply to
the OTP design principles, without making use of a standard
behaviour. Such a process should:
<P>
<UL>

<LI>
be started in a way that makes the process fit into a
        supervision tree,
</LI>


<LI>
support the <CODE>sys</CODE> <A HREF="#debug">debug
         facilities</A>, and
</LI>


<LI>
take care of <A HREF="#msg">system
         messages</A>.
</LI>


</UL>

<P>System messages are messages with special meaning, used in
the supervision tree. Typical system messages are requests for
trace output, and requests to suspend or resume process execution
(used during release handling). Processes implemented using
standard behaviours automatically understand these messages.<A NAME="6.2.1"><!-- Empty --></A>
<H4>6.2.1 Example</H4>

<P>The simple server from
        the <A HREF="des_princ.html#ch1">Overview</A> chapter,
        implemented using <CODE>sys</CODE> and <CODE>proc_lib</CODE> so it fits into
        a supervision tree:<A NAME="ex"><!-- Empty --></A>
<PRE>
-module(ch4).
-export([start_link/0]).
-export([alloc/0, free/1]).
-export([init/1]).
-export([system_continue/3, system_terminate/4,
         write_debug/3]).

start_link() -&#62;
    proc_lib:start_link(ch4, init, [self()]).

alloc() -&#62;
    ch4 ! {self(), alloc},
    receive
        {ch4, Res} -&#62;
            Res
    end.

free(Ch) -&#62;
    ch4 ! {free, Ch},
    ok.

init(Parent) -&#62;
    register(ch4, self()),
    Chs = channels(),
    Deb = sys:debug_options([]),
    proc_lib:init_ack(Parent, {ok, self()}),
    loop(Chs, Parent, Deb).

loop(Chs, Parent, Deb) -&#62;
    receive
        {From, alloc} -&#62;
            Deb2 = sys:handle_debug(Deb, {ch4, write_debug},
                                    ch4, {in, alloc, From}),
            {Ch, Chs2} = alloc(Chs),
            From ! {ch4, Ch},
            Deb3 = sys:handle_debug(Deb2, {ch4, write_debug},
                                    ch4, {out, {ch4, Ch}, From}),
            loop(Chs2, Parent, Deb3);
        {free, Ch} -&#62;
            Deb2 = sys:handle_debug(Deb, {ch4, write_debug},
                                    ch4, {in, {free, Ch}}),
            Chs2 = free(Ch, Chs),
            loop(Chs2, Parent, Deb2);

        {system, From, Request} -&#62;
            sys:handle_system_msg(Request, From, Parent,
                                  ch4, Deb, Chs)
    end.

system_continue(Parent, Deb, Chs) -&#62;
    loop(Chs, Parent, Deb).

system_terminate(Reason, Parent, Deb, Chs) -&#62;
    exit(Reason).

write_debug(Dev, Event, Name) -&#62;
    io:format(Dev, &#34;~p event = ~p~n&#34;, [Name, Event]).
      
</PRE>

<P>Example on how the simple debugging functions in <CODE>sys</CODE> can
        be used for <CODE>ch4</CODE> as well:
<PRE>
% <STRONG>erl</STRONG>
Erlang (BEAM) emulator version 5.2.3.6 [hipe] [threads:0]

Eshell V5.2.3.6  (abort with ^G)
1&#62; <STRONG>ch4:start_link().</STRONG>
{ok,&#60;0.30.0&#62;}
2&#62; <STRONG>sys:statistics(ch4, true).</STRONG>
ok
3&#62; <STRONG>sys:trace(ch4, true).</STRONG>
ok
4&#62; <STRONG>ch4:alloc().</STRONG>
ch4 event = {in,alloc,&#60;0.25.0&#62;}
ch4 event = {out,{ch4,ch1},&#60;0.25.0&#62;}
ch1
5&#62; <STRONG>ch4:free(ch1).</STRONG>
ch4 event = {in,{free,ch1}}
ok
6&#62; <STRONG>sys:statistics(ch4, get).</STRONG>
{ok,[{start_time,{{2003,6,13},{9,47,5}}},
     {current_time,{{2003,6,13},{9,47,56}}},
     {reductions,109},
     {messages_in,2},
     {messages_out,1}]}
7&#62; <STRONG>sys:statistics(ch4, false).</STRONG>
ok
8&#62; <STRONG>sys:trace(ch4, false).</STRONG>
ok
9&#62; <STRONG>sys:get_status(ch4).</STRONG>
{status,&#60;0.30.0&#62;,
        {module,ch4},
        [[{'$ancestors',[&#60;0.25.0&#62;]},{'$initial_call',{ch4,init,[&#60;0.25.0&#62;]}}],
         running,
         &#60;0.25.0&#62;,
         [],
         [ch1,ch2,ch3]]}
      
</PRE>
<A NAME="6.2.2"><!-- Empty --></A>
<H4>6.2.2 Starting the Process</H4>

<P>A function in the <CODE>proc_lib</CODE> module should be used to
        start the process. There are several possible functions, for
        example <CODE>spawn_link/3,4</CODE> for asynchronous start and
        <CODE>start_link/3,4,5</CODE> for synchronous start.
<P>A process started using one of these functions will store
        information that is needed for a process in a supervision tree,
        for example about the ancestors and initial call.
<P>Also, if the process terminates with another reason than
        <CODE>normal</CODE> or <CODE>shutdown</CODE>, a crash report (see SASL
        User's Guide) is generated.
<P>In the example, synchronous start is used. The process is
        started by calling <CODE>ch4:start_link()</CODE>:
<PRE>
start_link() -&#62;
    proc_lib:start_link(ch4, init, [self()]).
      
</PRE>

<P><CODE>ch4:start_link</CODE> calls the function
        <CODE>proc_lib:start_link</CODE>. This function takes a module name,
        a function name and an argument list as arguments and spawns
        and links to a new process. The new process starts by executing
        the given function, in this case <CODE>ch4:init(Pid)</CODE>, where
        <CODE>Pid</CODE> is the pid (<CODE>self()</CODE>) of the first process, that
        is the parent process.
<P>In <CODE>init</CODE>, all initialization including name registration
        is done. The new process must also acknowledge that it has been
        started to the parent:
<PRE>
init(Parent) -&#62;
    ...
    proc_lib:init_ack(Parent, {ok, self()}),
    loop(...).
      
</PRE>

<P><CODE>proc_lib:start_link</CODE> is synchronous and does not return
        until <CODE>proc_lib:init_ack</CODE> has been called.<A NAME="debug"><!-- Empty --></A><A NAME="6.2.3"><!-- Empty --></A>
<H4>6.2.3 Debugging</H4>

<P>To support the debug facilites in <CODE>sys</CODE>, we need a
        <STRONG>debug structure</STRONG>, a term <CODE>Deb</CODE> which is
        initialized using <CODE>sys:debug_options/1</CODE>:
<PRE>
init(Parent) -&#62;
    ...
    Deb = sys:debug_options([]),
    ...
    loop(Chs, Parent, Deb).
      
</PRE>

<P><CODE>sys:debug_options/1</CODE> takes a list of options as argument.
        Here the list is empty, which means no debugging is enabled
        initially. See <CODE>sys(3)</CODE> for information about possible
        options.
<P>Then for each <STRONG>system event</STRONG> that we want to be logged
        or traced, the following function should be called.
<PRE>
sys:handle_debug(Deb, Func, Info, Event) =&#62; Deb1
      
</PRE>

<P>
<UL>

<LI>
         <CODE>Deb</CODE> is the debug structure.<BR>

        
</LI>


<LI>
         <CODE>Func</CODE> is a tuple <CODE>{Module, Name}</CODE> (or a fun) and
         should specify a (user defined) function used to format
         trace output. For each system event, the format function is
         called as <CODE>Module:Name(Dev, Event, Info)</CODE>, where:<BR>

         
<UL>

<LI>
         <CODE>Dev</CODE> is the IO device to which the output should
                be printed. See <CODE>io(3)</CODE>.<BR>

         
</LI>


<LI>
         <CODE>Event</CODE> and <CODE>Info</CODE> are passed as-is from
                <CODE>handle_debug</CODE>.<BR>

         
</LI>


</UL>

        
</LI>


<LI>
         <CODE>Info</CODE> is used to pass additional information to
         <CODE>Func</CODE>, it can be any term and is passed as-is.<BR>

        
</LI>


<LI>
         <CODE>Event</CODE> is the system event. It is up to the user to
         define what a system event is and how it should be
         represented, but typically at least incoming and outgoing
         messages are considered system events and represented by
         the tuples <CODE>{in,Msg[,From]}</CODE> and <CODE>{out,Msg,To}</CODE>,
         respectively.<BR>

        
</LI>


</UL>

<P><CODE>handle_debug</CODE> returns an updated debug structure
        <CODE>Deb1</CODE>.
<P>In the example, <CODE>handle_debug</CODE> is called for each incoming
        and outgoing message. The format function <CODE>Func</CODE> is
        the function <CODE>ch4:write_debug/3</CODE> which prints the message
        using <CODE>io:format/3</CODE>.
<PRE>
loop(Chs, Parent, Deb) -&#62;
    receive
        {From, alloc} -&#62;
            Deb2 = sys:handle_debug(Deb, {ch4, write_debug},
                                    ch4, {in, alloc, From}),
            {Ch, Chs2} = alloc(Chs),
            From ! {ch4, Ch},
            Deb3 = sys:handle_debug(Deb2, {ch4, write_debug},
                                    ch4, {out, {ch4, Ch}, From}),
            loop(Chs2, Parent, Deb3);
        {free, Ch} -&#62;
            Deb2 = sys:handle_debug(Deb, {ch4, write_debug},
                                    ch4, {in, {free, Ch}}),
            Chs2 = free(Ch, Chs),
            loop(Chs2, Parent, Deb2);
        ...
    end.

write_debug(Dev, Event, Name) -&#62;
    io:format(Dev, &#34;~p event = ~p~n&#34;, [Name, Event]).
     
</PRE>
<A NAME="msg"><!-- Empty --></A><A NAME="6.2.4"><!-- Empty --></A>
<H4>6.2.4 Handling System Messages</H4>

<P><STRONG>System messages</STRONG> are received as:
<PRE>
{system, From, Request}
      
</PRE>

<P>The content and meaning of these messages do not need to be
        interpreted by the process. Instead the following function
        should be called:
<PRE>
sys:handle_system_msg(Request, From, Parent, Module, Deb, State)
      
</PRE>

<P>This function does not return. It will handle the system
        message and then call:
<PRE>
Module:system_continue(Parent, Deb, State)
      
</PRE>

<P>if process execution should continue, or:
<PRE>
Module:system_terminate(Reason, Parent, Deb, State)
      
</PRE>

<P>if the process should terminate. Note that a process in a
        supervision tree is expected to terminate with the same reason as
        its parent.
<P>
<UL>

<LI>
<CODE>Request</CODE> and <CODE>From</CODE> should be passed as-is from
         the system message to the call to <CODE>handle_system_msg</CODE>.
        
</LI>


<LI>
<CODE>Parent</CODE> is the pid of the parent.
</LI>


<LI>
<CODE>Module</CODE> is the name of the module.
</LI>


<LI>
<CODE>Deb</CODE> is the debug structure.
</LI>


<LI>
<CODE>State</CODE> is a term describing the internal state and
         is passed to <CODE>system_continue</CODE>/<CODE>system_terminate</CODE>.
        
</LI>


</UL>

<P>In the example:
<PRE>
loop(Chs, Parent, Deb) -&#62;
    receive
        ...

        {system, From, Request} -&#62;
            sys:handle_system_msg(Request, From, Parent,
                                  ch4, Deb, Chs)
    end.

system_continue(Parent, Deb, Chs) -&#62;
    loop(Chs, Parent, Deb).

system_terminate(Reason, Parent, Deb, Chs) -&#62;
    exit(Reason).
      
</PRE>

<P>If the special process is set to trap exits, note that if
        the parent process terminates, the expected behavior is to
        terminate with the same reason:
<PRE>
init(...) -&#62;
    ...,
    process_flag(trap_exit, true),
    ...,
    loop(...).

loop(...) -&#62;
    receive
        ...

        {'EXIT', Parent, Reason} -&#62;
            ..maybe some cleaning up here..
            exit(Reason);
        ...
    end.
      
</PRE>
<A NAME="6.3"><!-- Empty --></A>
<H3>6.3 User-Defined Behaviours</H3>

<P>To implement a user-defined behaviour, write code similar to
code for a special process but calling functions in a callback
module for handling specific tasks.
<P>If it is desired that the compiler should warn for missing
callback functions, as it does for the OTP behaviours, implement
and export the function:
<PRE>
behaviour_info(callbacks) -&#62;
    [{Name1,Arity1},...,{NameN,ArityN}].
    
</PRE>

<P>where each <CODE>{Name,Arity}</CODE> specifies the name and arity of
a callback function.
<P>When the compiler encounters the module attribute
<CODE>-behaviour(Behaviour).</CODE> in a module <CODE>Mod</CODE>, it will call
<CODE>Behaviour:behaviour_info(callbacks)</CODE> and compare the result
with the set of functions actually exported from <CODE>Mod</CODE>, and
issue a warning if any callback function is missing.
<P>Example:
<PRE>
%% User-defined behaviour module
-module(simple_server).
-export([start_link/2,...]).
-export([behaviour_info/1]).

behaviour_info(callbacks) -&#62;
    [{init,1},
     {handle_req,1},
     {terminate,0}].

start_link(Name, Module) -&#62;
    proc_lib:start_link(?MODULE, init, [self(), Name, Module]).

init(Parent, Name, Module) -&#62;
    register(Name, self()),
    ...,
    Dbg = sys:debug_options([]),
    proc_lib:init_ack(Parent, {ok, self()}),
    loop(Parent, Module, Deb, ...).

...
    
</PRE>

<P>In a callback module:
<PRE>
-module(db).
-behaviour(simple_server).

-export([init/0, handle_req/1, terminate/0]).

...
    
</PRE>
<CENTER>
<HR>
<SMALL>
Copyright &copy; 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>