summaryrefslogtreecommitdiff
path: root/lib/erl_interface/doc/src/ei_users_guide.xml
blob: 951fe32ad5c49ab9de04fc648a38f5aaef16be02 (plain)
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
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>
  <header>
    <copyright>
      <year>2002</year><year>2022</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Erl_Interface User's Guide</title>
    <prepared>Kent Boortz</prepared>
    <responsible>Kent Boortz</responsible>
    <docno></docno>
    <approved></approved>
    <checked></checked>
    <date></date>
    <rev></rev>
    <file>ei_users_guide.xml</file>
  </header>

  <section>
    <title>Introduction</title>
    <p>The <c>Erl_Interface</c> library contains functions that help you
      integrate programs written in C and Erlang. The functions in
      <c>Erl_Interface</c> support the following:</p>
    <list type="bulleted">
      <item>Manipulation of data represented as Erlang data types</item>
      <item>Conversion of data between C and Erlang formats</item>
      <item>Encoding and decoding of Erlang data types for transmission or
        storage</item>
      <item>Communication between C nodes and Erlang processes</item>
      <item>Backup and restore of C node state to and from
        <seeerl marker="mnesia:mnesia">Mnesia</seeerl></item>
    </list>
    <note>
      <p>By default, the <c>Erl_Interface</c> library is only guaranteed
        to be compatible with other Erlang/OTP components from the same
        release as the libraries themselves. For information about how to
        communicate with Erlang/OTP components from earlier releases, see
        function <seecref marker="ei#ei_set_compat_rel">
        <c>ei_set_compat_rel</c></seecref>.</p>
    </note>

    <section>
      <title>Scope</title>
      <p>In the following sections, these topics are described:</p>
      <list type="bulleted">
        <item>Compiling your code for use with <c>Erl_Interface</c></item>
        <item>Initializing <c>Erl_Interface</c></item>
        <item>Encoding, decoding, and sending Erlang terms</item>
        <item>Building terms and patterns</item>
        <item>Pattern matching</item>
        <item>Connecting to a distributed Erlang node</item>
        <item>Using the Erlang Port Mapper Daemon (EPMD)</item>
        <item>Sending and receiving Erlang messages</item>
        <item>Remote procedure calls</item>
        <item>Using global names</item>
      </list>
    </section>

    <section>
      <title>Prerequisites</title>
      <p>It is assumed that the reader is familiar with the Erlang programming
        language.</p>
    </section>
  </section>

  <section>
    <title>Compiling and Linking Your Code</title>
    <p>To use any of the <c>Erl_Interface</c> functions, include the
      following line in your code:</p>

    <code type="none"><![CDATA[
#include "ei.h"    ]]></code>

    <p>Determine where the top directory of your OTP installation is.
      To find this, start Erlang and enter the following
      command at the Eshell prompt:</p>

    <code type="none"><![CDATA[
Eshell V4.7.4  (abort with ^G)
1> code:root_dir().
/usr/local/otp    ]]></code>

    <p>To compile your code, ensure that your C compiler knows where
      to find <c>ei.h</c> by specifying an appropriate
      <c>-I</c> argument on the command line, or add it to
      the <c>CFLAGS</c> definition in your
      <c>Makefile</c>. The correct value for this path is
      <c>$OTPROOT/lib/erl_interface-$EIVSN/include</c>,
      where:</p>

    <list type="bulleted">
      <item>
        <p><c>$OTPROOT</c> is the path reported by
          <c>code:root_dir/0</c> in the example above.</p>
      </item>
      <item>
        <p><c>$EIVSN</c> is the version of the <c>Erl_Interface</c> application,
          for example, <c>erl_interface-3.2.3</c>.</p>
      </item>
    </list>

    <p>Compiling the code:</p>

    <code type="none"><![CDATA[
$ cc -c -I/usr/local/otp/lib/erl_interface-3.2.3/include myprog.c    ]]></code>

    <p>When linking:</p>

    <list type="bulleted">
      <item>Specify the path to <c>libei.a</c> with
        <c>-L$OTPROOT/lib/erl_interface-3.2.3/lib</c>.</item>
      <item>Specify the name of the library with <c>-lei</c>.</item>
    </list>

    <p>Do this on the command line or add the flags to the
      <c>LDFLAGS</c> definition in your
      <c>Makefile</c>.</p>

    <p>Linking the code:</p>

    <code type="none"><![CDATA[
$ ld -L/usr/local/otp/lib/erl_interface-3.2.3/
                            lib myprog.o -lei -o myprog    ]]></code>

    <p>On some systems it can be necessary to link with some more
      libraries (for example, <c>libnsl.a</c> and
      <c>libsocket.a</c> on Solaris, or
      <c>wsock32.lib</c> on Windows) to use the
      communication facilities of <c>Erl_Interface</c>.</p>

    <p>If you use the <c>Erl_Interface</c> functions in a threaded
      application based on POSIX threads or Solaris threads, then
      <c>Erl_Interface</c> needs access to some of the synchronization
      facilities in your threads package. You must specify extra
      compiler flags to indicate which of the packages you use. Define
      <c>_REENTRANT</c> and either <c>STHREADS</c> or
      <c>PTHREADS</c>. The default is to use POSIX threads if
      <c>_REENTRANT</c> is specified.</p>
  </section>

  <section>
    <title>Initializing the Library</title>
    <p>
      Before calling any of the other functions in the library,
      initialize it by calling
      <c>ei_init()</c> exactly once.
    </p>
  </section>

  <section>
    <title>Encoding, Decoding, and Sending Erlang Terms</title>
    <p>Data sent between distributed Erlang nodes is encoded in the
      Erlang external format. You must therefore encode and decode
      Erlang terms into byte streams if you want to use the distribution
      protocol to communicate between a C program and Erlang.</p>

    <p>The <c>Erl_Interface</c> library supports this activity. It has
      several C functions that create and manipulate Erlang data
      structures. The following example shows how to create and encode
      an Erlang tuple <c>{tobbe,3928}</c>:</p>

    <code type="none"><![CDATA[
ei_x_buff buf;
ei_x_new(&buf);
int i = 0;
ei_x_encode_tuple_header(&buf, 2);
ei_x_encode_atom(&buf, "tobbe");
ei_x_encode_long(&buf, 3928);    ]]></code>

    <p>For a complete description, see the
    <seecref marker="ei"><c>ei</c></seecref> module.</p>
  </section>

  <section>
    <marker id="building_terms_and_patterns"/>
    <title>Building Terms</title>
    <p>The previous example can be simplified by using the
      <seecref marker="ei#ei_x_format_wo_ver"><c>ei_x_format_wo_ver</c></seecref> function
      to create an Erlang term:</p>

    <code type="none"><![CDATA[
ei_x_buff buf;
ei_x_new(&buf);
ei_x_format_wo_ver(&buf, "{~a,~i}", "tobbe", 3928);    ]]></code>

    <p>For a complete description of the different format directives, see the
      the <seecref marker="ei#ei_x_format_wo_ver"><c>ei_x_format_wo_ver</c></seecref> function.</p>

    <p>The following example is more complex:</p>

    <code type="none"><![CDATA[
ei_x_buff buf;
int i = 0;
ei_x_new(&buf);
ei_x_format_wo_ver(&buf,
                   "[{name,~a},{age,~i},{data,[{adr,~s,~i}]}]",
                   "madonna",
                   21,
                  "E-street", 42);
ei_print_term(stdout, buf.buff, &i);
ei_x_free(&buf);      ]]></code>

    <p>As in the previous examples, it is your responsibility to free the
      memory allocated for Erlang terms. In this example,
      <c>ei_x_free()</c> ensures that the data
      pointed to by <c>buf</c> is released.</p>

  </section>

  <section>
    <title>Connecting to a Distributed Erlang Node</title>
    <p>To connect to a distributed Erlang node, you must first
      initialize the connection routine with one of the
      <seecref marker="ei_connect#ei_connect_init">
      <c>ei_connect_init_*</c></seecref> functions,
      which stores information, such as the hostname, and node name
      for later use:</p>

    <code type="none"><![CDATA[
int identification_number = 99;
int creation=1;
char *cookie="a secret cookie string"; /* An example */
const char* node_name = "einode@durin";
const char *cookie = NULL;
short creation = time(NULL) + 1;
ei_cnode ec;
ei_connect_init(&ec,
                node_name,
                cookie,
                creation);    ]]></code>

    <p>For more information, see the
      <seecref marker="ei_connect"><c>ei_connect</c></seecref> module.</p>

    <p>After initialization, you set up the connection to the Erlang node.
      To specify the Erlang node you want to connect to, use the
      <c>ei_connect_*()</c> family of functions. The following example sets up the
      connection and is to result in a valid socket file descriptor:</p>

    <code type="none"><![CDATA[
int sockfd;
const char* node_name = "einode@durin"; /* An example */
if ((sockfd = ei_connect(&ec, nodename)) < 0)
  fprintf(stderr, "ERROR: ei_connect failed");    ]]></code>

  </section>

  <section>
    <title>Using EPMD</title>
    <p><seecom marker="erts:epmd"><c>erts:epmd</c></seecom>
      is the Erlang Port Mapper Daemon. Distributed
      Erlang nodes register with <c>epmd</c> on the local host to
      indicate to other nodes that they exist and can accept connections.
      <c>epmd</c> maintains a register of
      node and port number information, and when a node wishes to connect to
      another node, it first contacts <c>epmd</c> to find the
      correct port number to connect to.</p>

    <p>When you use
      <seecref marker="ei_connect"><c>ei_connect</c></seecref>
      to connect to an Erlang node, a connection is first made to
      <c>epmd</c> and, if the node is known, a
      connection is then made to the Erlang node.</p>

    <p>C nodes can also register themselves with <c>epmd</c>
      if they want other
      nodes in the system to be able to find and connect to them.</p>

    <p>Before registering with <c>epmd</c>, you must first
      create a listen socket and bind it to a port. Then:</p>

    <code type="none"><![CDATA[
int pub;

pub = ei_publish(&ec, port);    ]]></code>

    <p><c>pub</c> is a file descriptor now connected to
      <c>epmd</c>. <c>epmd</c>
      monitors the other end of the connection. If it detects that the
      connection has been closed, the node becomes unregistered. So, if you
      explicitly close the descriptor or if your node fails, it becomes
      unregistered from <c>epmd</c>.</p>

    <p>Notice that on some systems a failed node is
      not detected by this mechanism, as the operating system does not
      automatically close descriptors that were left open when the node
      failed. If a node has failed in this way, <c>epmd</c>
      prevents you from
      registering a new node with the old name, as it thinks that the old
      name is still in use. In this case, you must close the port
      explicitly</p>

  </section>

  <section>
    <title>Sending and Receiving Erlang Messages</title>
    <p>Use one of the following two functions to send messages:</p>

    <list type="bulleted">
      <item><seecref marker="ei_connect#ei_send">
        <c>ei_send</c></seecref></item>
      <item><seecref marker="ei_connect#ei_reg_send">
        <c>ei_reg_send</c></seecref></item>
    </list>

    <p>As in Erlang, messages can be sent to a
      pid or to a registered name. It is easier to send a
      message to a registered name, as it avoids the problem of finding
      a suitable pid.</p>

    <p>Use one of the following two functions to receive messages:</p>

    <list type="bulleted">
      <item><seecref marker="ei_connect#ei_receive">
        <c>ei_receive</c></seecref></item>
      <item><seecref marker="ei_connect#ei_receive_msg">
        <c>ei_receive_msg</c></seecref></item>
    </list>

    <section>
      <title>Example of Sending Messages</title>
      <p>In the following example, <c>{Pid, hello_world}</c> is
        sent to a registered process <c>my_server</c>:</p>

      <code type="none"><![CDATA[
ei_x_buff buf;
ei_x_new_with_version(&buf);

ei_x_encode_tuple_header(&buf, 2);
ei_x_encode_pid(&buf, ei_self(ec));
ei_x_encode_atom(&buf, "Hello world");

ei_reg_send(&ec,fd,"my_server",buf,buf.index);]]></code>

      <p>The first element of the tuple that is sent is your own
        pid. This enables <c>my_server</c> to reply.
        For more information about the primitives, see the
        <seecref marker="ei_connect"><c>ei_connect</c></seecref> module.</p>
    </section>

    <section>
      <title>Example of Receiving Messages</title>
      <p>In this example, <c>{Pid, Something}</c> is received.</p>

        <code type="none"><![CDATA[
erlang_msg msg;
int index = 0;
int version;
int arity = 0;
erlang_pid pid;
ei_x_buff buf;
ei_x_new(&buf);
for (;;) {
  int got = ei_xreceive_msg(fd, &msg, &x);
  if (got == ERL_TICK)
    continue;
  if (got == ERL_ERROR) {
    fprintf(stderr, "ei_xreceive_msg, got==%d", got);
    exit(1);
  }
  break;
}
ei_decode_version(buf.buff, &index, &version);
ei_decode_tuple_header(buf.buff, &index, &arity);
if (arity != 2) {
  fprintf(stderr, "got wrong message");
  exit(1);
}
ei_decode_pid(buf.buff, &index, &pid);     ]]></code>

      <p>To provide robustness, a distributed Erlang node
        occasionally polls all its connected neighbors in an attempt to
        detect failed nodes or communication links. A node that receives such
        a message is expected to respond immediately with an
        <c>ERL_TICK</c> message. This is done automatically by
        <c>ei_xreceive_msg()</c>. However, when this has occurred,
        <c>ei_xreceive_msg</c> returns <c>ERL_TICK</c> to
        the caller without storing a message into the
        <c>erlang_msg</c> structure.</p>

      <p>When a message has been received, it is the caller's responsibility
        to free the received message.</p>

      <p>For more information, see the
        <seecref marker="ei_connect"><c>ei_connect</c></seecref> and
        <seecref marker="ei"><c>ei</c></seecref> modules.</p>
    </section>
  </section>

  <section>
    <title>Remote Procedure Calls</title>
    <p>An Erlang node acting as a client to another Erlang node
      typically sends a request and waits for a reply. Such a request is
      included in a function call at a remote node and is called a remote
      procedure call.</p>

    <p>The following example checks if a specific Erlang process is alive:</p>

    <code type="none"><![CDATA[
int index = 0, is_alive;
ei_x_buff args, result;

ei_x_new(&result);
ei_x_new(&args);
ei_x_encode_list_header(&args, 1);
ei_x_encode_pid(&args, &check_pid);
ei_x_encode_empty_list(&args);

if (ei_rpc(&ec, fd, "erlang", "is_process_alive",
           args.buff, args.index, &result) < 0)
    handle_error();

if (ei_decode_version(result.buff, &index) < 0
    || ei_decode_bool(result.buff, &index, &is_alive) < 0)
    handle_error();    ]]></code>

    <p>For more information about <c>ei_rpc()</c> and its
      companions <c>ei_rpc_to()</c> and
      <c>ei_rpc_from()</c>, see the
      <seecref marker="ei_connect"><c>ei_connect</c></seecref> module.</p>
  </section>

  <section>
    <title>Using Global Names</title>
    <p>A C node has access to names registered through the
      <seeerl marker="kernel:global"><c>global</c></seeerl>
      module in Kernel. Names can be looked up, allowing the C node to send messages
      to named Erlang services. C nodes can also register global names,
      allowing them to provide named services to Erlang processes or other C
      nodes.</p>

    <p><c>Erl_Interface</c> does not provide a native implementation of the
      global service. Instead it uses the global services provided by a "nearby"
      Erlang node. To use the services described in this section,
      it is necessary to first open a connection to an Erlang node.</p>

    <p>To see what names there are:</p>

    <code type="none"><![CDATA[
char **names;
int count;
int i;

names = ei_global_names(&ec,fd,&count);

if (names) 
  for (i=0; i<count; i++) 
    printf("%s\n",names[i]);

free(names);    ]]></code>

    <p><seecref marker="ei_global#ei_global_names">
      <c>ei_global_names</c></seecref>
      allocates and returns a buffer containing
      all the names known to the <c>global</c> module in <c>Kernel</c>.
      <c>count</c> is initialized to
      indicate the number of names in the array. The array of strings in names
      is terminated by a <c>NULL</c> pointer, so it is not necessary to use
      <c>count</c> to determine when the last name is reached.</p>

    <p>It is the caller's responsibility to free the array.
      <c>ei_global_names</c> allocates the array and all the strings
      using a single call to <c>malloc()</c>, so
      <c>free(names)</c> is all that is necessary.</p>

    <p>To look up one of the names:</p>

    <code type="none"><![CDATA[
ETERM *pid;
char node[256];
erlang_pid the_pid;

if (ei_global_whereis(&ec,fd,"schedule",&the_pid,node) < 0)
   fprintf(stderr, "ei_global_whereis error\n");    ]]></code>

    <p>If <c>"schedule"</c> is known to the
      <c>global</c> module in <c>Kernel</c>, an Erlang pid is
      written to the_pid. This pid that can be used to send messages to the schedule service.
      Also, <c>node</c> is initialized to contain the name of
      the node where the service is registered, so that you can make a
      connection to it by simply passing the variable to
      <seecref marker="ei_connect"><c>ei_connect</c></seecref>.</p>

    <p>Before registering a name, you should already have registered your
      port number with <c>epmd</c>. This is not strictly necessary,
      but if you
      neglect to do so, then other nodes wishing to communicate with your
      service cannot find or connect to your process.</p>

    <p>Create a name that Erlang processes can use to communicate with your
      service:</p>

    <code type="none"><![CDATA[
ei_global_register(fd,servicename,ei_self(ec));    ]]></code>

    <p>After registering the name, use
        <seecref marker="ei_connect#ei_accept">
        <c>ei_accept</c></seecref>
        to wait for incoming connections.</p>

    <note>
      <p>Remember to free <c>pid</c> later with
        <seecref marker="ei#ei_x_free">
        <c>ei_x_free</c></seecref>.</p>
    </note>

    <p>To unregister a name:</p>

    <code type="none"><![CDATA[
ei_global_unregister(&ec,fd,servicename);    ]]></code>
  </section>

</chapter>