erl interface 3.3.2

Upload: zhuqiming

Post on 03-Apr-2018

244 views

Category:

Documents


1 download

TRANSCRIPT

  • 7/28/2019 Erl Interface 3.3.2

    1/86

    ErlangInterface

    version3.3

  • 7/28/2019 Erl Interface 3.3.2

    2/86

    Typeset in LATEX from SGML source usingthe DO CBUIL DER 3.2.2 Document System.

  • 7/28/2019 Erl Interface 3.3.2

    3/86

    Contents

    1 Erl InterfaceUsersGuide 1

    1.1 TheErl InterfaceL ibrary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

    1.1.1 Compilingand Linking Your Code . . . . . . . . . . . . . . . . . . . . . . . . . 1

    1.1.2 Initializing the erl interface Library . . . . . . . . . . . . . . . . . . . . . . . . . 2

    1.1.3 Encoding, Decoding and Sending Erlang Terms . . . . . . . . . . . . . . . . . . 21.1.4 Building Termsand Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

    1.1.5 Pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

    1.1.6 Connecting to aDistributed Erlang Node . . . . . . . . . . . . . . . . . . . . . . 5

    1.1.7 Using EPM D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    1.1.8 Sending and Receiving Erlang Messages . . . . . . . . . . . . . . . . . . . . . . . 6

    1.1.9 RemoteProcedureCalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    1.1.10 UsingGlobal Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    1.1.11 TheRegistry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    2 Erl InterfaceCommand Reference 13

    2.1 erl call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    3 Erl InterfaceLibrary Reference 16

    3.1 registry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    3.2 ei . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    3.3 ei connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    3.4 erl connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    3.5 erl error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

    3.6 erl eterm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    3.7 erl format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

    3.8 erl global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

    3.9 erl malloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    3.10 erl marshal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

    iiiErlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    4/86

    iv Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    5/86

    Chapter 1

    Erl Interface Users Guide

    1.1 The Erl Interface Library

    The Erl Interface library contains functions. which help you integrateprograms written in C andErlang. The functions in Erl Interfacesupport thefollowing:

    manipulation of data represented as Erlang data types

    conversion of data between C and Erlang formats

    encoding and decodingof Erlangdata types for transmission or storage

    communication between C nodes and Erlang processes

    backup and restore of C node state to and from Mnesia

    In the following sections, these topics are described:

    compiling your codefor use with Erl Interface

    initializing Erl Interface

    encoding, decoding, and sending Erlangterms

    building terms and patterns

    pattern matching

    connecting to a distributed Erlangnode

    usingEPMD

    sending and receiving Erlangmessages

    remote procedure calls

    global names

    the registry

    1.1.1 Compiling and Linking Your Code

    In order to use any of the Erl Interface functions, include the following lines in your code:

    #include "erl_interface.h"

    #include "ei.h"

    1Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    6/86

    Chapter 1: Erl Interface Users Guide

    Determine where thetop directory of your OT P installation is. You can find thisout by startingErlangand entering the following command at the Eshell prompt:

    Eshell V4.7.4 (abort with ^G)

    1> code:root_dir().

    /usr/local/otp

    To compileyour code, makesure that your C compiler knowswhereto find erl interface.h byspecifying an appropriate-I argument on the command line, or by addingit to the CFLAGS definition inyour Makefile. The correct value for this path is $OTPROOT/lib/erl interfaceVsn/include, where$OTPROOT is the path reported by code:root dir/0 in the aboveexample, and Vsn is the version of theErl interfaceapplication, for example erl interface-3.2.3

    $ cc -c -I/usr/local/otp/lib/erl_interface-3.2.3/include myprog.c

    When linking, you will need to specify the path to liberl interface.a and libei.a with-L$OTPROOT/lib/erl interface-3.2.3/lib, and you will need to specify the name of the librarieswith -lerl interface -lei. You can do this on the command line or by adding the flags to theLDFLAGS definition in your Makefile.

    $ ld -L/usr/local/otp/lib/erl_interface-3.2.3/

    lib myprog.o -lerl_interface -lei -o myprog

    Also, on some systemsit may benecessary to link with some additional libraries(e.g. libnsl.a andlibsocket.a on Solaris, or wsock32.lib on Windows) in order to use thecommunication facilities ofErl Interface.

    If you are usingErl Interfacefunctions in a threaded application based on POSIX threadsor Solaristhreads, then Erl Interfaceneedsaccess to some of the synchronization facilities in your threadspackage, and you will need to specify additional compiler flags in order to indicate which of the

    packages you are using. Define REENTRANT and either STHREADS or PTHREADS. The default is to usePOSIX threadsif REENTRANT is specified.

    1.1.2 Initializing the erl interface Library

    Beforecallingany of theother Erl Interface functions, you must call erl init() exactly oncetoinitialize the library. erl init() takes two arguments, however theargumentsare no longer used byErl Interface, and should thereforebe specified as erl init(NULL,0).

    1.1.3 Encoding, Decoding and Sending Erlang Terms

    Data sent between distributed Erlangnodes is encoded in the Erlang external format. Consequently,you haveto encode and decodeErlangterms into byte streams if you want to use thedistributionprotocol to communicate between a C program and Erlang.

    The Erl Interface library supports this activity. It has a number of C functions which create andmanipulate Erlangdata structures. The library also contains an encode and a decode function. Theexample below showshow to create and encode an Erlangtuple tobbe,3928 :

    2 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    7/86

    1.1: The Erl Interface Library

    ETERM *arr[2], *tuple;

    char buf[BUFSIZ];

    int i;

    arr[0] = erl_mk_atom("tobbe");

    arr[1] = erl_mk_integer(3928);

    tuple = erl_mk_tuple(arr, 2);

    i = erl_encode(tuple, buf);

    Alternatively, you can use erl send() and erl receive msg, which handle theencodingand decodingof messagestransparently.

    Refer to the Reference Manual for a complete description of thefollowing modules:

    the erl eterm module for creating Erlang terms

    the erl marshal modulefor encoding and decodingroutines.

    1.1.4 Building Terms and Patterns

    The previousexamplecan be simplified by using erl format() to create an Erlangterm.

    ETERM *ep;

    ep = erl_format("{~a,~i}", "tobbe", 3928);

    Refer to the Reference Manual, the erl format module, for a full description of thedifferent formatdirectives. The following example is more complex:

    ETERM *ep;

    ep = erl_format("[{name,~a},{age,~i},{data,~w}]",

    "madonna",

    21,erl_format("[{adr,~s,~i}]", "E-street", 42));

    erl_free_compound(ep);

    As in previousexamples, it is your responsibility to free thememory allocated for Erlangterms. In thisexample, erl free compound() ensures that thecomplete term pointed to by ep is released. This isnecessary, because the pointer from the second call to erl format() is lost.

    The following exampleshowsa slightly different solution:

    ETERM *ep,*ep2;

    ep2 = erl_format("[{adr,~s,~i}]","E-street",42);

    ep = erl_format("[{name,~a},{age,~i},{data,~w}]",

    "madonna", 21, ep2);

    erl_free_term(ep);

    erl_free_term(ep2);

    In thiscase, you free thetwo terms independently. The order in which you free theterms ep and ep2 isnot important, because theErl Interfacelibrary uses reference countingto determine when it is safe toactually removeobjects.

    If you are not surewhether you havefreed theterms properly, you can use thefollowingfunction to seethestatusof thefixed term allocator:

    3Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    8/86

  • 7/28/2019 Erl Interface 3.3.2

    9/86

    1.1: The Erl Interface Library

    1.1.6 Connecting to a Distributed Erlang Node

    In order to connect to a distributed Erlangnodeyou need to first initialize the connection routinewitherl connect init(), which stores information such as thehost name, nodename, and IP address forlater use:

    int identification_number = 99;

    int creation=1;

    char *cookie="a secret cookie string"; /* An example */

    erl_connect_init(identification_number, cookie, creation);

    Refer to the Reference Manual, the erl connect module for more information.

    After initialization, you set up theconnection to theErlangnode. Use erl connect() to specify theErlangnodeyou want to connect to. The followingexample sets up theconnection and should result ina valid socket file descriptor:

    int sockfd;

    char *nodename="[email protected]"; /* An example */if ((sockfd = erl_connect(nodename)) < 0)

    erl_err_quit("ERROR: erl_connect failed");

    erl err quit() printsthe specified string and terminates the program. Refer to the Reference Manual,the erl error() function for moreinformation.

    1.1.7 Using EPMD

    Epmd is theErlangPort Mapper Daemon. Distributed Erlangnodes register with epmd on the localhostto indicate to other nodes that they exist and can accept connections. Epmd maintains a register of nodeand port number information, and when a nodewishesto connect to another node, it first contacts

    epmd in order to find out the correct port number to connect to.When you use erl connect() to connect to an Erlangnode, a connection is first madeto epmd and, ifthenodeis known, a connection is then madeto theErlangnode.

    C nodes can also register themselves with epmd if they want other nodes in the system to beableto findand connect to them.

    Before registering with epmd, you need to first create a listen socket and bind it to a port. Then:

    int pub;

    pub = erl_publish(port);

    pub is a file descriptor now connected to epmd. Epmd monitorstheother end of the connection, and if itdetectsthat theconnection has been closed, thenodewill beunregistered. So, if you explicitly close thedescriptor or if your nodefails, it will beunregistered from epmd.

    Beaware that on some systems (such as V xWorks), a failed nodewill not bedetected by thismechanism sincethe operating system does not automatically close descriptors that were left openwhen the nodefailed. I f a node has failed in this way, epmd will prevent you from registeringa newnode with the old name, since it thinks that the old name is still in use. In this case, you must unregisterthe name explicitly:

    erl_unpublish(node);

    5Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    10/86

  • 7/28/2019 Erl Interface 3.3.2

    11/86

    1.1: The Erl Interface Library

    Example of Receiving Messages

    In thisexample Pid, Something is received. The received Pid is then used to return goodbye,Pid

    ETERM *arr[2], *answer;

    int sockfd,rc;

    char buf[BUFSIZE];

    ErlMessage emsg;

    if ((rc = erl_receive_msg(sockfd , buf, BUFSIZE, &emsg)) == ERL_MSG) {

    arr[0] = erl_mk_atom("goodbye");

    arr[1] = erl_element(1, emsg.msg);

    answer = erl_mk_tuple(arr, 2);

    erl_send(sockfd, arr[1], answer);

    erl_free_term(answer);

    erl_free_term(emsg.msg);

    erl_free_term(emsg.to);

    }

    }

    In order to provide robustness, a distributed Erlang nodeoccasionally polls all its connected neighboursin an attempt to detect failed nodes or communication links. A nodewhich receives such a message isexpected to respond immediately with an ERL TICK message. This is done automatically byerl receive(), however when this has occurred erl receive returns ERL TICK to the caller withoutstoringa message into the ErlMessage structure.

    When a message has been received, it is the callers responsibility to free the received messageemsg.msg as well as emsg.to or emsg.from, dependingon the typeof message received.

    Refer to the Reference Manual for additional information about the following modules:

    erl connect

    erl eterm.

    1.1.9 Remote Procedure Calls

    An Erlangnodeactingas a client to another Erlangnodetypically sends a request and waits for a reply.Such a request is included in a function call at a remote nodeand is called a remoteprocedure call. Thefollowing example showshow the Erl Interfacelibrary supportsremote procedurecalls:

    char modname[]=THE_MODNAME;

    ETERM *reply,*ep;

    ep = erl_format("[~a,[]]", modname);

    if (!(reply = erl_rpc(fd, "c", "c", ep)))erl_err_msg(" when compiling file: %s.erl !\n", modname);

    erl_free_term(ep);

    ep = erl_format("{ok,_}");

    if (!erl_match(ep, reply))

    erl_err_msg(" compiler errors !\n");

    erl_free_term(ep);

    erl_free_term(reply);

    7Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    12/86

    Chapter 1: Erl Interface Users Guide

    c:c/1 is called to compile thespecified module on theremotenode. erl match() checks that thecompilation was successful by testing for the expected ok.

    Refer to theReference Manual, theerl connect module for more information about erl rpc(), andits companionserl rpc to() and erl rpc from().

    1.1.10 Using Global Names

    A C nodehas access to names registered through the Erlang Global module. Names can belooked up,allowing the C node to send messages to named Erlangservices. C nodes can also register global names,allowingthem to provide named services to Erlang processesor other C nodes.

    Erl Interfacedoes not provide a native implementation of the global service. Instead it uses the globalservices provided by a nearbyErlangnode. In order to use theservices described in thissection, it isnecessary to first open a connection to an Erlangnode.

    To see what names there are:

    char **names;

    int count;int i;

    names = erl_global_names(fd,&count);

    if (names)

    for (i=0; i

  • 7/28/2019 Erl Interface 3.3.2

    13/86

    1.1: The Erl Interface Library

    ETERM *pid;

    pid = erl_mk_pid(thisnode,14,0,0);

    erl_global_register(fd,servicename,pid);

    After registering the name, you should use erl accept() to wait for incoming connections.

    Do not forget to free pid later with erl free term()!

    To unregister a name:

    erl_global_unregister(fd,servicename);

    1.1.11 The Registry

    This section describes the use of theregistry, a simplemechanism for storing key-valuepairsin aC-node, as well as backingthem up or restoringthem from a Mnesia table on an Erlangnode. Moredetailed information about theindividual API functions can befound in theReference Manual.

    Keys are strings, i.e. 0-terminated arraysof characters, and valuesare arbitrary objects. Althoughintegers and floating point numbers are treated specially by the registry, you can storestrings or binaryobjects of any type as pointers.

    To start, you need to open a registry:

    ei_reg *reg;

    reg = ei_reg_open(45);

    The number 45 in the exampleindicates the approximatenumber of objectsthat you expect to storeinthe registry. Internally the registry uses hash tables with collision chaining, so there is no absolute upperlimit on thenumber of objects that theregistry can contain, but if performance or memory usage are

    important, then you should choose a number accordingly. The registry can be resized later.You can open as many registries as you like(if memory permits).

    Objectsare stored and retrieved through set and get functions. In the following examples you see howto store integers, floats, stringsand arbitrary binary objects:

    struct bonk *b = malloc(sizeof(*b));

    char *name = malloc(7);

    ei_reg_setival(reg,"age",29);

    ei_reg_setfval(reg,"height",1.85);

    strcpy(name,"Martin");

    ei_reg_setsval(reg,"name",name);

    b->l = 42;

    b->m = 12;

    ei_reg_setpval(reg,"jox",b,sizeof(*b));

    9Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    14/86

    Chapter 1: Erl Interface Users Guide

    If you attempt to store an object in the registry and there is an existing object with the same key, thenew value will replacetheold one. This is doneregardless of whether thenew object and theold onehavethesame type, so you can, for example, replacea stringwith an integer. If theexistingvalue is astringor binary, it will befreed beforethenew value is assigned.

    Stored values are retrieved from the registry as follows:

    long i;

    double f;

    char *s;

    struct bonk *b;

    int size;

    i = ei_reg_getival(reg,"age");

    f = ei_reg_getfval(reg,"height");

    s = ei_reg_getsval(reg,"name");

    b = ei_reg_getpval(reg,"jox",&size);

    In all of the above examples, the object must exist and it must beof the right typefor the specifiedoperation. If you do not know the typeof a given object, you can ask:

    struct ei_reg_stat buf;

    ei_reg_stat(reg,"name",&buf);

    Buf will beinitialized to contain object attributes.

    Objectscan beremoved from the registry:

    ei_reg_delete(reg,"name");

    When you are finished with a registry, close it to remove all theobjects and free thememory back tothe system:

    ei_reg_close(reg);

    Backing Up the Registry to Mnesia

    The contentsof a registry can be backed up to Mnesia on a nearby Erlang node. You need to providean open connection to theErlangnode(see erl connect()). A lso, Mnesia 3.0 or later must berunningon theErlangnodebeforethebackup is initiated:

    ei_reg_dump(fd, reg, "mtab", dumpflags);

    The exampleabove will backup the contentsof the registry to the specified Mnesia table "mtab". Oncea registry has been backed up to Mnesia in this manner, additional backupswill only affect objects thathavebeen modified sincethe most recent backup, i.e. objects that havebeen created, changed ordeleted. The backup operation is doneas a single atomic transaction, so that theentire backup will beperformed or noneof it will.

    In thesame manner, a registry can berestored froma Mnesia table:

    ei_reg_restore(fd, reg, "mtab");

    10 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    15/86

    1.1: The Erl Interface Library

    This will read the entire contentsof"mtab" into thespecified registry. After therestore, all of theobjects in the registry will bemarked as unmodified, so a subsequent backup will only affect objectsthat you havemodified sincethe restore.

    Note that if you restore to a non-empty registry, objects in thetable will overwriteobjects in theregistry with the samekeys. Also, theentirecontentsof the registry is marked as unmodified after the

    restore, including any modified obects that were not overwritten by the restoreoperation. This may notbeyour intention.

    Storing Strings and Binaries

    When string or binary objectsare stored in the registry it is important that a number of simpleguidelines are followed.

    Most importantly, theobject must havebeen created with a single call tomalloc() (or similar), so thatit can later beremoved by a single call to free(). Objectswill befreed by the registrywhen it is closed,or when you assign a new value to an object that previously contained a stringor binary.

    You should also be awarethat if you storebinary objectsthat are context-dependent (e.g. containingpointersor open file descriptors), they will lose their meaning if they are backed up to a Mnesia table

    and subsequently restored in a different context.

    When you retrievea stored stringor binary value from theregistry, theregistry maintains a pointer totheobject and you are passed a copy of that pointer. You should never free an object retrieved in thismanner because when theregistry later attemptsto free it, a runtime error will occur that will likelycause the C-node to crash.

    You arefree to modify the contentsof an object retrieved this way. However when you do so, theregistry will not beaware of thechanges you make, possibily causingit to bemissed thenext time youmake a Mnesia backup of theregistry contents. This can beavoided if you mark theobject as dirty afterany such changes with ei reg markdirty(), or pass appropriate flags to ei reg dump().

    11Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    16/86

    Chapter 1: Erl Interface Users Guide

    12 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    17/86

    Erl Interface CommandReference

    Short Summaries

    Command erl call [page 14] C all/Start a Distributed ErlangNode

    erl call

    The following functions are exported:

    erl call options Start/Call Erlang

    13Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    18/86

    erl call Erl Interface Command Reference

    erl call

    Command

    erl call makes it possible to start and/or communicate with a distributed Erlang node.It isbuilt upon the erl interface library as an example application. Its purpose is touse an Unix shell script to interact with a distributed Erlangnode. It performsallcommunication with the Erlang rex server, usingthestandard ErlangRPC facility. Itdoes not require any special software to berun at theErlangtarget node.

    The main use is to either start a distributed Erlang node or to makean ordinary functioncall. However, it is also possibleto pipe an Erlangmodule to erl call and haveitcompiled, or to pipea sequence of Erlangexpressions to beevaluated (similar to theErlang shell).

    Options, which cause stdin to beread, can beused with advantage as scriptsfromwithin (Unix) shell scripts. Another nice use oferl call could be from (http) CG I-binscripts.

    Exports

    erl call

    options

    Each option flag is described below with its name, typeand meaning.

    -a[Mod [Fun[Args ]]]] (optional): Applies thespecified function and returns theresult. Mod must be specified, however [] is assumed for unspecified Fun and Args.Args should bein the same format as for erlang:apply/3. Notethat this flagtakes exactly one argument, so quoting may benecessary in order to group Mod,Fun and Args, in a manner dependent on thebehavior of your command shell.

    -c Cookie (optional): Use this option to specify a certain cookie. If no cookieisspecified, the ~/.erlang.cookie file is read and its content are used as cookie.

    The Erlang node wewant to communicate with must have the same cookie.

    -d (optional): D ebug mode. This causes all IO to beoutput to the file~/.erl call.out.Nodename, where Nodename is the nodename of the Erlangnodein question.

    -e (optional): Readsa sequence of Erlang expressions, separated by , and ended with a., from stdin until EOF (Control-D). Evaluates theexpressions and returns theresult from thelast expression. Returns

    ok,Result

    if successful.

    -hHiddenName (optional): Specifies thename of thehidden nodethat erl callrepresents.

    -m (optional): Readsan Erlangmodule fromstdin and compilesit.

    -n Node (one of-n, -name, -sname is required): Has the same meaningas -name andcan still be used for backwardscompatibility reasons.

    14 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    19/86

    Erl Interface Command Reference erl call

    -nameNode (one of-n, -name, -sname is required): Node is the name of the nodetobe started or communicated with. It is assumed that Node is started with erl-name, which meansthat fully qualified long nodenames are used. If the-s optionis given, an Erlang nodewill (if necessary) bestarted with erl -name.

    -q (optional): Halts theErlangnodespecified with the-n switch. This switch overrides

    the-s switch.-r (optional): Generates a random name of thehidden nodethat erl call represents.

    -s (optional): Starts a distributed Erlangnodeif necessary. This meansthat in asequence of calls, where the -s and -n Node are constant, only thefirst call willstart theErlangnode. This makes therest of thecommunication very fast. Thisflag is currently only available on theUnix platform.

    -snameNode (one of-n, -name, -sname is required): Node is the name of the node tobe started or communicated with. It is assumed that Node is started with erl-sname which meansthat short node names are used. If -s option is given, anErlang nodewill bestarted (if necessary) with erl -sname.

    -v (optional): Printsa lot ofverbose information. This is only useful for thedeveloperand maintainer of erl call.

    -xErlScript (optional): Specifies another name of theErlangstart-up script to beused.If not specified, the standard erl start-up script is used.

    Examples

    Startsan Erlangnodeand calls erlang:time/0.

    erl_call -s -a erlang time -n madonna

    {18,27,34}

    Terminates an Erlang node by calling erlang:halt/0.

    erl_call -s -a erlang halt -n madonna

    An apply with several arguments.

    erl_call -s -a lists map [{math,sqrt},[1,4,9,16,25]] -n madonna

    Evaluates a coupleof expressions. Theinput ends with EOF (Control-D).

    erl_call -s -e -n madonna

    statistics(runtime),

    X=1,

    Y=2,

    {_,T}=statistics(runtime),

    {X+Y,T}.

    ^D{ok,{3,0}}

    Compiles a moduleand runs it. Again, the input ends with EOF (Control-D). (In theexample shown, the output has been formatted afterwards).

    15Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    20/86

    erl_call -s -m -a lolita -n madonna

    -module(lolita).

    -compile(export_all).

    start() ->

    P = processes(),

    F = fun(X) -> {X,process_info(X,registered_name)} end,

    lists:map(F,[],P).

    ^D

    [{,

    {registered_name,init}},

    {,

    {registered_name,erl_prim_loader}},

    {,

    {registered_name,error_logger}},

    {,

    {registered_name,application_controller}},

    {,

    {registered_name,kernel}},

    {,[]},

    {,

    {registered_name,kernel_sup}},

    {,

    {registered_name,net_sup}},

    {,

    {registered_name,net_kernel}},

    {,

    []},

    {,

    {registered_name,global_name_server}},

    {,

    {registered_name,auth}},

    {,

    {registered_name,rex}},

    {,

    []},

    {,

    {registered_name,file_server}},

    {,

    {registered_name,code_server}},

    {,

    {registered_name,user}},

    {,

    []}]

    Erl Interface Library Reference

    16 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    21/86

  • 7/28/2019 Erl Interface 3.3.2

    22/86

  • 7/28/2019 Erl Interface 3.3.2

    23/86

  • 7/28/2019 Erl Interface 3.3.2

    24/86

  • 7/28/2019 Erl Interface 3.3.2

    25/86

  • 7/28/2019 Erl Interface 3.3.2

    26/86

  • 7/28/2019 Erl Interface 3.3.2

    27/86

    Erl Interface Library Reference

    erl format

    The following functions are exported:

    ETERM * erl format(FormatStr, ... ) Creates an Erlang term

    int erl match(Pattern, Term) Performspattern matching

    erl global

    The following functions are exported:

    char ** erl global names(fd,count) Obtain list of Global names

    int erl global register(fd,name,pid) Register a name in Global

    int erl global unregister(fd,name) Unregister a name in Global

    ETERM * erl global whereis(fd,name,node) Look up a name in global

    erl mallocThe following functions are exported:

    ETERM * erl alloc eterm(etype) Allocates an ETERM structure

    void erl eterm release(void) Clears theETERM freelist

    void erl eterm statistics(allocated, freed) Reports term allocationstatistics

    void erl free array(array, size) Frees an array of ETERM structures

    void erl free term(t) Frees an ETERM structure

    void erl free compound(t) Frees an array of ETERM structures

    void erl malloc(size) Allocates some memory

    void erl free(ptr) Frees somememory

    erl marshal

    The following functions are exported:

    int erl compare ext(bufp1, bufp2) Comparesencoded byte sequences

    ETERM * erl decode(bufp) Converts a term from Erlangexternal format

    ETERM * erl decode buf(bufpp) Convertsa term from Erlang external format

    int erl encode(term, bufp) Convertsa term into Erlang external format

    int erl encode buf(term, bufpp) Convertsa term into Erlangexternal format

    int erl ext size(bufp) Countselementsin encoded term

    char erl ext type(bufp) Determines type of an encoded byte sequence

    unsigned char * erl peek ext(bufp, pos) Steps over encoded term

    int erl term len(t) Determines encoded size of term

    23Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    28/86

    registry Erl Interface Library Reference

    registry

    C Module

    This moduleprovidessupport for storing key-valuepairsin a table known as a registry,backing up registries to Mnesia in an atomic manner, and later restoringthecontents ofa registry from Mnesia.

    Exports

    int ei reg close(reg)

    Types:

    ei reg*reg;

    A registry that has previously been created with ei reg open() is closed, and all theobjects it contains are freed.

    reg is theregistry to close.

    The function returns 0.

    int ei reg delete(reg,key)

    Types:

    ei reg*reg;

    const char *key;

    Delete an object fromtheregistry. The object is not actually removed fromtheregistry,it is only marked for later removal so that on subsequent backups to Mnesia, thecorrespondingobject can beremoved fromtheMnesia table as well. If another object islater created with thesame key, theobject will bereused.

    The object will beremoved from the registry after a call to ei reg dump() orei reg purge().

    reg is the registry containing key.

    key is theobject to remove.

    If theobject was found, thefunction returns 0 indicatingsuccess. Otherwise thefunction returns-1.

    int ei reg dump(fd,reg,mntab,flags)

    Types:

    int fd;

    ei reg*reg;

    const char *mntab;

    24 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    29/86

    Erl Interface Library Reference registry

    int flags;

    Dump thecontents of a registry to a Mnesia table in an atomic manner, i.e. either alldatawill beupdated, or none of it will. If any errorsare encountered while backing upthe data, the entire operation is aborted.

    fd is an open connection to Erlang. Mnesia 3.0 or later must berunning on the Erlang

    node.reg is theregistry to back up.

    mntab is thename of theMnesia table where thebacked up data should beplaced. Ifthe table does not exist, it will becreated automatically using configurable defaults. Seeyour Mnesia documentation for information about configuring this behaviour.

    Ifflags is 0, thebackup will includeonly those objects which havebeen created,modified or deleted sincethe last backup or restore(i.e. an incremental backup). Afterthebackup, any objects that were marked dirty are now clean, and any objects that hadbeen marked for deletion are deleted.

    Alternatively, settingflags to EI FORCE will cause a full backup to bedone, andEI NOPURG E will cause thedeleted objects to beleft in theregistry afterwards. These

    can bebitwise ORed together if both behavioursare desired. If EI NOPURG E wasspecified, you can use ei reg purge() to explicitly remove thedeleted items fromtheregistry later.

    The function returns 0 on success, or -1 on failure.

    double ei reg getfval(reg,key)

    Types:

    ei reg*reg;

    const char *key;

    Get the value associated with key in theregistry. The value must bea floatingpointtype.

    reg is theregistry where theobject will belooked up.

    key is the name of the object to look up.

    On success, the function returnsthe value associated with key. If the object was notfound or it was not a floating point object, -1.0 is returned. To avoid problems within-band error reporting(i.e. if you cannot distinguish between -1.0 and a valid result)use the more general function ei reg getval() instead.

    int ei reg getival(reg,key)

    Types:

    ei reg*reg;

    const char *key;Get the value associated with key in the registry. The value must bean integer.

    reg is theregistry where theobject will belooked up.

    key is the name of the object to look up.

    On success, the function returnsthe value associated with key. If the object was notfound or it was not an integer object, -1 is returned. To avoid problems with in-banderror reporting(i.e. if you cannot distinguish between -1 and a valid result) use themoregeneral function ei reg getval() instead.

    25Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    30/86

    registry Erl Interface Library Reference

    const void * ei reg getpval(reg,key,size)

    Types:

    ei reg*reg;

    const char *key;

    int size;

    Get the value associated with key in theregistry. T he value must bea binary (pointer)type.

    reg is theregistry where theobject will belooked up.

    key is the name of the object to look up.

    size will be initialized to contain the length in bytes of theobject, if it is found.

    On success, thefunction returnsthevalue associated with key and indicates its length insize. I f the object was not found or it was not a binary object, NU LL is returned. Toavoid problems with in-band error reporting(i.e. if you cannot distinguish betweenNUL L and a valid result) use themoregeneral function ei reg getval() instead.

    const char * ei reg getsval(reg,key)

    Types:

    ei reg*reg;

    const char *key;

    Get the value associated with key in theregistry. Thevalue must bea string.

    reg is theregistry where theobject will belooked up.

    key is the name of the object to look up.

    On success, the function returnsthe value associated with key. If the object was notfound or it was not a string, NUL L is returned. To avoid problems with in-band errorreporting(i.e. if you cannot distinguish between NUL L and a valid result) use themore

    general function ei reg getval() instead.

    int ei reg getval(reg,key,flags,v,...)

    Types:

    ei reg*reg;

    const char *key;

    int flags;

    void *v (see below)

    This is a general function for retrieving any kind of object from the registry.

    reg is theregistry where theobject will belooked up.

    key is the name of the object to look up.flags indicates the typeof object that you are looking for. If flags is 0, then any kindof object will bereturned. I f flags isone of EI IN T, EI FLT, EI STR or EI BIN, thenonly values of that kind will be returned. The buffer pointed to by v must be largeenough to hold the return data, i.e. it must bea pointer to one ofint, double, char* orvoid*, respectively. Also, if flags is EI BIN, then a fifth argument int *size isrequired, so that thesize of theobject can bereturned.

    If the function succeeds, v (and size if the object is binary) will be initialized with thevalue associated with key, and the function will return one of EI INT, EI FLT, EI STR

    26 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    31/86

    Erl Interface Library Reference registry

    or EI BIN, indicating the typeof object. On failure the function will return -1 and thearguments will not be updated.

    int ei reg markdirty(reg,key)

    Types:

    ei reg*reg;

    const char *key;

    Mark a registry object as dirty. This will ensurethat it is included in the next backup toMnesia. Normally this operation will not benecessary sinceall of the normal registryset functions do thisautomatically. However if you haveretrieved thevalue of a stringor binary object fromtheregistry and modified thecontents, then thechange will beinvisible to theregistry and theobject will beassumed to beunmodified. T his functionallowsyou to make such modifications and then let theregistry know about them.

    reg is theregistry containing the object.

    key is the name of the object to mark.

    The function returns 0 on success, or -1 on failure.

    ei reg * ei reg open(size)

    Types:

    int size;

    Open (create) a registry. The registry will beinitially empty. U se ei reg close() toclose the registry later.

    size is theapproximate number of objects you intend to store in theregistry. Since theregistry uses a hash table with collision chaining, there is no absolute upper limit on thenumber of objectsthat can bestored in it. However for reasons of efficiency, it is a goodidea to choose a number that is appropriate for your needs. It is possible to use

    ei reg resize() to change thesize later. Note that thenumber you provide will beincreased to the nearest larger prime number.

    On success, an empty registry will bereturned. O n failure, NUL L will bereturned.

    int ei reg purge(reg)

    Types:

    ei reg*reg;

    Remove all objects marked for deletion. When objects are deleted withei reg delete() they are not actually removed fromtheregistry, only marked for laterremoval. This is so that on a subsequent backup to Mnesia, theobjects can also beremoved from the Mnesia table. If you are not backing up to Mnesia then you may wish

    to remove theobjects manually with thisfunction.

    reg is a registry containing objects marked for deletion.

    The function returns 0 on success, or -1 on failure.

    int ei reg resize(reg,newsize)

    Types:

    ei reg*reg;

    int newsize;

    27Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    32/86

    registry Erl Interface Library Reference

    Change thesize of a registry.

    newsize is thenew size to make theregistry. The number will be increased to thenearest larger prime number.

    On success, the registry will beresized, all contentsrehashed, and the function willreturn 0. On failure, theregistry will be left unchanged and thefunction will return -1.

    int ei reg restore(fd,reg,mntab)

    Types:

    int fd;

    ei reg*reg;

    const char *mntab;

    The contentsof a Mnesia table are read into the registry.

    fd is an open connection to Erlang. Mnesia 3.0 or later must berunningon the Erlangnode.

    reg is theregistry where thedata should beplaced.

    mntab is the name of the Mnesia tableto read datafrom.

    Note that only tables of a certain format can berestored, i.e. those that havebeencreated and backed up to with ei reg dump(). If the registry was not empty beforetheoperation, then thecontents of thetable are added to thecontents of theregistry. If thetable contains objects with the samekeysas those already in theregistry, the registryobjects will beoverwritten with thenew values. If theregistry contains objects thatwere not in thetable, they will beunchanged by thisoperation.

    After the restoreoperation, the entire contentsof the registry is marked as unmodified.Note that thisincludes any objects that were modified beforetherestore and notoverwritten by the restore.

    The function returns 0 on success, or -1 on failure.

    int ei reg setfval(reg,key,f)

    Types:

    ei reg*reg;

    const char *key;

    double f;

    Create a key-value pair with thespecified key and floating point value f. If an objectalready existed with the same key, the new valuereplaces the old one. If thepreviousvaluewas a binary or string, it is freed with free().

    reg is theregistry where theobject should beplaced.

    key is the name of the object.f is thefloatingpoint value to assign.

    The function returns 0 on success, or -1 on failure.

    int ei reg setival(reg,key,i)

    Types:

    ei reg*reg;

    const char *key;

    28 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    33/86

    Erl Interface Library Reference registry

    int i;

    Create a key-value pair with thespecified key and integer value i. I f an object alreadyexisted with the same key, thenew value replaces theold one. If thepreviousvalue wasa binary or string, it is freed with free().

    reg is theregistry where theobject should beplaced.

    key is thename of the object.

    i is the integer value to assign.

    The function returns 0 on success, or -1 on failure.

    int ei reg setpval(reg,key,p,size)

    Types:

    ei reg*reg;

    const char *key;

    const void *p;

    int size;

    Create a key-value pair with thespecified key whose value is the binary objectpointed to by p. If an object already existed with thesame key, thenew value replacesthe old one. If the previousvaluewas a binary or string, it is freed with free().

    reg is theregistry where theobject should beplaced.

    key is thename of the object.

    p is a pointer to thebinary object. The object itself must havebeen created through asingle call tomalloc() or similar function, so that the registry can later delete it ifnecessary by calling free().

    size is the length in bytes of the binary object.

    The function returns 0 on success, or -1 on failure.

    int ei reg setsval(reg,key,s)

    Types:

    ei reg*reg;

    const char *key;

    const char *s;

    Create a key-value pair with thespecified key whose valueis the specified string s. Ifan object already existed with the samekey, the new valuereplaces the old one. I f theprevious valuewas a binary or string, it is freed with free().

    reg is theregistry where theobject should beplaced.

    key is thename of the object.s is thestringto assign. The stringitself must havebeen created through a single call tomalloc() or similar function, so that theregistry can later delete it if necessary bycalling free().

    The function returns 0 on success, or -1 on failure.

    int ei reg setval(reg,key,flags,v,...)

    Types:

    ei reg*reg;

    29Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    34/86

    registry Erl Interface Library Reference

    const char *key;

    int flags;

    v (see below)

    Create a key-value pair with thespecified key whose value is specified by v. If an objectalready existed with the same key, the new valuereplaces the old one. If theprevious

    valuewas a binary or string, it is freed with free().reg is theregistry where theobject should beplaced.

    key is the name of the object.

    flags indicates thetype of theobject specified by v. Flags must beone of EI IN T,EI FLT, EI STR and EI BIN, indicating whether v is int, double, char* or void*. Ifflags is EI BIN, then a fifth argument size is required, indicating thesize in bytes ofthe object pointed to by v.

    If you wish to store an arbitrary pointer in the registry, specify a size of 0. In this case,theobject itself will not betransferred by an ei reg dump() operation, just the pointervalue.

    The function returns 0 on success, or -1 on failure.

    int ei reg stat(reg,key,obuf)

    Types:

    ei reg*reg;

    const char *key;

    struct ei reg stat *obuf;

    Return information about an object.

    reg is the registry containing the object.

    key is the name of the object.

    obuf is a pointer to an ei reg stat structure, defined below:

    struct ei_reg_stat {

    int attr;

    int size;

    };

    In attr the objects attributes are stored as the logical OR of its type(one of EI IN T,EI FLT, EI BIN and EI STR), whether it is marked for deletion (EI DEL ET) andwhether it has been modified since the last backup to Mnesia (EI DI RTY).

    The size field indicates thesize in bytes required to store EI STR (including theterminating 0) and EI BIN objects, or 0 for EI IN T and EI FLT.

    The function returns 0 and initializes obuf on success, or returns -1 on failure.

    int ei reg tabstat(reg,obuf)

    Types:

    ei reg*reg;

    struct ei reg tabstat *obuf;

    30 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    35/86

    Erl Interface Library Reference registry

    Return information about a registry. Using information returned by this function, youcan see whether thesize of theregistry is suitable for theamount of datait contains.

    reg is theregistry to return information about.

    obuf is a pointer to an ei reg tabstat structure, defined below:

    struct ei_reg_tabstat {

    int size;

    int nelem;

    int npos;

    int collisions;

    };

    The size field indicates thenumber of hash positionsin theregistry. This is thenumberyou provided when you created or last resized theregistry, rounded up to thenearestprime.

    nelem indicates the number of elementsstored in the registry. It includes objects thatare deleted but not purged.

    npos indicates the number of unique positionsthat are occupied in the registry.

    collisions indicates how many elementsare sharing positionsin the registry.

    On success, thefunction returns 0 and obuf is initialized to contain table statistics. Onfailure, thefunction returns -1.

    31Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    36/86

    ei Erl Interface Library Reference

    ei

    C Module

    The library ei contains macros and functionsto encode and decodethe erlangbinaryterm format.

    With ei, you can convert atoms, lists, numbers and binaries to and fromthebinaryformat. This is useful when writing port programsand drivers. ei uses a given buffer,and no dynamic memory (with theexception ofei decode fun), and is often quite fast.

    It also handlesC-nodes, C-programsthat talks erlangdistribution with erlangnodes (orother C-nodes) using the erlangdistribution format. The difference between ei and

    erl interface is that ei uses the binary format directly when sending and receivingterms. It is also thread safe, and using threads, one process can handle multiple C-nodes.The erl interface library is built on top ofei, but of legacy reasons, it doesnt allowfor multiple C-nodes. In general, ei is thepreferred way of doing C-nodes.

    The decode and encode functions use a buffer an index into the buffer, which pointsatthe point whereto encode and decode. The index is updated to point right after theterm encoded/decoded. No checking is donewhether theterm fitsin thebuffer or not.If encoding goes outside the buffer, the program may crash.

    All functionstakes two parameter, buf is apointer to the buffer wherethe binary datais/ will be, index is a pointer to an index into thebuffer. This parameter will beincremented with thesize of the term decoded / encoded. The data is thus atbuf[*index] when an ei function is called.

    The encode functions all assumes that the buf and index parameters pointsto a bufferbigenough for thedata. To get thesize of an encoded term, without encodingit, passNULL instead of abuffer pointer. The index parameter will beincremented, but nothingwill be encoded. Thisis the way in ei to preflightterm encoding.

    There are also encode-functions that uses a dynamic buffer. It is often moreconvenientto use these to encode data. All encode funcionscomes in two versions: those startingwith ei x, uses a dynamic buffer.

    All functions return 0 if successful, and -1 if not. (For instance, if a term is not of theexpected type, or thedata to decodeis not a valid erlangterm.)

    Some of the decode-functionsneedsa preallocated buffer. This buffer must beallocatedbigenough, and theei get type function returns thesize required (note that for

    strings an extrabyte is needed for the0 stringterminator).

    32 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    37/86

  • 7/28/2019 Erl Interface 3.3.2

    38/86

  • 7/28/2019 Erl Interface 3.3.2

    39/86

  • 7/28/2019 Erl Interface 3.3.2

    40/86

    ei Erl Interface Library Reference

    This function decodes an unsigned long (32-bit) integer from the binary format.

    int ei decode double(const char *buf, int *index, double *p

    This function decodes an double-precision (64-bit) floating point number from thebinary format.

    int ei decode boolean(const char *buf, int *index, int *p

    This function decodes a boolean valuefrom the binary format. A boolean is actually anatom, true decodes 1 and false decodes0.

    int ei decode char(const char *buf, int *index, char *p

    This function decodes a char (8-bit) integer from the binary format.

    int ei decode string(const char *buf, int *index, char *p

    This function decodes a string from the binary format. A string in erlang is a list of

    integers between 0 and 255. Notethat since thestringis just a list, sometimes lists areencoded as strings by term to binary/1, even if it was not intended.

    The string is copied to p, and enough spacemust beallocated. The spacerequired canbefetched with ei get type. (Dont forget the ending0.)

    int ei decode atom(const char *buf, int *index, char *p

    This function decodes an atom from the binary format. Thename of the atom is placedat p. There can be at most MAXATOMLEN bytes placed in the buffer.

    int ei decode binary(const char *buf, int *index, void *p, long *len

    This function decodes a binary from the binary format. T helen parameter is set to the

    actual size of the binary. Notethat ei decode binary assumes that there are enoughroom for thebinary. The size required can befetched by ei get type.

    int ei decode fun(const char *buf, int *index, erlang fun *p)

    void free fun(erlang fun* f)

    This function decodes a fun from the binary format. Thep parameter should beNUL Lor point to an erlang fun structure. This is the only decodefunction that allocatesmemory; when the erlang fun is no longer needed, it should befreed with free fun.(This has to do with thearbitrary size of the environment for a fun.)

    int ei decode pid(const char *buf, int *index, erlang pid *p

    Decodes a pid, process identifier, from the binary format.

    int ei decode port(const char *buf, int *index, erlang port *p

    This function decodes a port identifier from the binary format.

    int ei decode ref(const char *buf, int *index, erlang ref *p

    This function decodes a reference from the binary format.

    36 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    41/86

  • 7/28/2019 Erl Interface 3.3.2

    42/86

    ei Erl Interface Library Reference

    ~w - an ETERM from erl interface, ETERM*

    ~a - an atom, char*

    ~s - a string, char*

    ~i - an integer, int

    ~l - a long integer, long int

    ~u - a unsigned long integer, unsigned long int

    ~f - a float, float

    ~d - a double float, double float

    For instance, to encode a tuple with some stuff:

    ei x format(" ~a,~i,~d ", "numbers", 12, 3.14159)

    encodes the tuple

    numbers,12,3.14159

    The ei x format wo ver formatsinto a buffer, without theinitial version byte.

    int ei x new(ei x buff* x)

    int ei x new with version(ei x buff* x)This function allocates a new ei x buff buffer. The fieldsof thestructurepointed to byx parameter is filled in, and a default buffer is allocated. The ei x new with versionalso puts an initial version byte, that is used in thebinary format. (So thatei x encode version wont be needed.)

    int ei x free(ei x buff* x)

    This function frees an ei x buff buffer. The memory used by thebuffer is returned tothe OS.

    int ei x append(ei x buff* x, const ei x buff* x2)

    int ei x append buf(ei x buff* x, const char* buf, int len)

    These functions appends dataat the end of the buffer x.

    int ei skip term(const char* buf, int* index)

    This function skips a term in the given buffer, it recursively skips elementsof listsandtuples, so that a full term is skipped. Thisis a way to get the size of an erlangterm.

    buf is thebuffer.

    index is updated to point right after the term in the buffer.

    Note:This can be useful when you want to hold arbitrary terms: just skip them and copythebinary term data to some buffer.

    The function returns 0 on success and -1 on failure.

    38 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    43/86

    Erl Interface Library Reference ei

    Debug Information

    Some tipson what to check when theemulator doesnt seem to receivetheterms thatyou send.

    be careful with the version header, use ei x new with version when appropriate

    turn on distribution tracing on theerlangnode

    check theresult codes from ei decode -calls

    See Also

    erl interface(3)

    39Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    44/86

    ei connect Erl Interface Library Reference

    ei connect

    C Module

    This moduleenables C programs to communicate with erlang nodes, using the erlangdistribution over TC P/IP.

    A C nodeappears to Erlangas a hidden node. That is, Erlangprocessesthat know thename of theC nodeare able to communicate with it in a normal manner, but the nodename will not appear in thelistingprovided by theErlangfunction nodes/0.

    Exports

    int ei connect init(ei cnode* ec, const char* this node name, const char *cookie,

    short creation)

    int ei connect xinit(ei cnode* ec, const char *thishostname, const char

    *thisalivename, const char *thisnodename, Erl IpAddr thisipaddr, const

    char *cookie, short creation)

    These function initializes the ec structure, to identify thenodename and cookie of theserver. O neof them has to becalled beforeother functions in theei connect moduleare used.

    ec is a structurecontaininginformation about theC-node. It is used in other ei

    functionsfor connecting and receiving data.this node name is the registered name of the process (the namebefore @).

    cookie is the cookiefor the node.

    creation identifies a specific instance of a C node. It can help prevent thenodefromreceiving messages sent to an earlier process with the sameregistered name.

    thishostname is thename of themachine wererunning on. If longnames are to beused, it should befully qualified (i.e. durin.erix.ericsson.se instead ofdurin).

    thisalivename is the registered nameof the process.

    thisnodename is thefull name of the node, i.e. einode@durin.

    thispaddr if theIP address of thehost.

    A C nodeacting as a server will beassigned a creation number when it callserl publish() or erl xpublish().

    A connection is closed by simply closing the socket. Refer to system documentation toclose the socket gracefully (when there are outgoingpackets before close).

    Example 1:

    40 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    45/86

    Erl Interface Library Reference ei connect

    int n = 0;

    struct in_addr addr;

    ei_cnode ec;

    addr = inet_addr("150.236.14.75");

    if (ei_connect_xinit(&ec,

    "chivas",

    "madonna",

    "[email protected]",

    &addr;

    "cookie..."),

    n++) < 0)

    erl_err_quit(" when initializing !");

    Example 2:

    if (ei_connect_init(&ec, "madonna", "cookie...", n++) < 0)

    erl_err_quit(" when initializing !");

    int ei connect(ei cnode* ec, char *nodename)

    int ei xconnect(ei cnode* ec, Erl IpAddr adr, char *alivename)

    These functions set up a connection to an Erlang node.

    erl xconnect() requires the IP address of the remote host and the alivename of theremote nodeto bespecified. erl connect() provides an alternative interface, anddetermines the information from the node nameprovided.

    addr is the32-bit IP address of theremotehost.

    alive is the alivename of the remote node.

    node is thename of theremotenode.

    These functions return an open file descriptor on success, or a negative valueindicatingthat an error occurred in which case they will set erl errno to one of:

    EHOSTUNREACH The remote host node is unreachable

    ENOMEM No more memory available.

    EIO I/O error.

    Additionally, errno valuesfrom socket(2) and connect(2) system calls may bepropagated into erl errno.

    Example:

    #define NODE "[email protected]"

    #define ALIVE "madonna"

    #define IP_ADDR "150.236.14.75"

    /*** Variant 1 ***/

    int fd = erl_connect(&ec, NODE);

    /*** Variant 2 ***/

    struct in_addr addr;

    addr = inet_addr(IP_ADDR);

    erl_xconnect(&ec, &addr, ALIVE);

    int ei receive(int fd, unsigned char* bufp, int bufsize)

    41Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    46/86

    ei connect Erl Interface Library Reference

    This function receives a message consisting of a sequence of bytes in the Erlang externalformat.

    fd is an open descriptor to an Erlangconnection. It is obtained froma previouserl connect or erl accept.

    bufp is a buffer large enough to hold the expected message.

    bufsize indicates the size ofbufp.

    If a tick occurs, i.e., the Erlangnodeon the other end of the connection has polled thisnodeto see if it is still alive, the function will return ERL TICK and no message will beplaced in thebuffer. Also, erl errno will be set to EAGAIN.

    On success, themessage is placed in thespecified buffer and thefunction returns thenumber of bytes actually read. On failure, thefunction returns ERL ERROR and will seterl errno to one of:

    EAGAIN Temporary error: Try again.

    EMSGSIZE Buffer too small.

    EIO I/O error.

    int ei receive msg(int fd, erlang msg* msg, ei x buff* x)

    int ei xreceive msg(int fd, erlang msg* msg, ei x buff* x)

    These functions receives a message to the buffer in x. ei xreceive msg allows thebuffer in x to grow, but ei receive msg fails if themessage is bigger than thepreallocated buffer in x.

    fd is an open descriptor to an Erlangconnection.

    msg is a pointer to an erlang msg structure and contains information on the messagereceived.

    x is buffer obtained from ei x new.

    On success, the function returnsERL MSG and themsg struct will beinitialized.erlang msg is defined as follows:

    typedef struct {

    long msgtype;

    erlang_pid from;

    erlang_pid to;

    char toname[MAXATOMLEN+1];

    char cookie[MAXATOMLEN+1];

    erlang_trace token;

    } erlang_msg;

    msgtype identifies the type of message, and is one ofERL SEND, ERL REG SEND,

    ERL LINK, ERL UNLINK and ERL EXIT.Ifmsgtype is ERL SEND this indicates that an ordinary send operation has taken place,andmsg- to containsthe Pid of the recipient (the C-node). If type is ERL REG SENDthen a registered send operation took place, andmsg- from containsthePid of thesender.

    Ifmsgtype is ERL LINK or ERL UNLINK, thenmsg- to andmsg- from contain thepidsof the sender and receipient of the link or unlink.

    Ifmsgtype is ERL EXIT, then thisindicates that a link has been broken. In thiscase,msg- to andmsg- from contain the pidsof the linked processes.

    42 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    47/86

  • 7/28/2019 Erl Interface 3.3.2

    48/86

    ei connect Erl Interface Library Reference

    emsg is a message containingtheresult of thefunction call.

    x pointsto thedynamic buffer that receives theresult.

    The actual message returned by the rpc server is a 2-tuple rex,Reply .

    erl rpc() returns thenumber of bytes in theresult on success and -1 on failure.erl rpc from returns number of bytes or one ofERL TICK, ERL TIMEOUT and ERL ERROR

    otherwise. When failing, all three functionsset erl errno to one of:

    EIO I/O error.

    ETIMEDOUT Timeout expired.

    EAGAIN Temporary error: Try again.

    Expample, check to see if an erlangprocess is alive.

    int index = 0, is_alive;

    ei_x_buff args, result;

    ei_x_new(&result);

    ei_x_new_with_version(&args);

    ei_x_encode_pid(&args, &check_pid);if (ei_rpc(&ec, fd, "erlang", "is_process_alive",

    args.buff, args.index, &result) < 0)

    error();

    if (ei_decode_version(result.buff, &index) < 0

    || ei_decode_bool(result.buff, &index, &is_alive) < 0)

    error();

    int ei publish(ei cnode *ec, int port)

    These functions areused by a server process to register with the local name server epmd,thereby allowing other processesto send messages by using the registered name. Beforecalling either of these functions, the processshould havecalled bind() and listen()

    on an open socket.

    ec is theC-nodestructure.

    port is thelocal name to register, and should bethesame as theport number that waspreviously bound to the socket.

    addr is the32-bit IP address of thelocal host.

    To unregister with epmd, simply close the returned descriptor. See alsoei unpublish().

    On success, the functionsreturn a descriptor connectingthe calling processto epmd.On failure, they return -1 and set erl errno to EIO.

    Additionally, errno valuesfrom socket(2) and connect(2) system calls may be

    propagated into erl errno.

    int ei accept(ei cnode *ec, int listensock, ErlConnect *conp)

    This function is used by a server processto accept a connection from a client process.

    ec is theC-nodestructure.

    listensock is an open socket descriptor on which listen() has previously been called.

    conp is a pointer to an ErlConnect struct, described as follows:

    44 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    49/86

    Erl Interface Library Reference ei connect

    typedef struct {

    char ipadr[4];

    char nodename[MAXNODELEN];

    } ErlConnect;

    On success, conp is filled in with theaddress and nodename of theconnecting client

    and a file descriptor is returned. O n failure, ERL ERROR is returned and erl errno is setto EIO.

    int ei unpublish(ei cnode *ec)

    Thisfunction can be called by a processto unregister a specified node from epmd onthelocalhost. This may beuseful, for example, when epmd has not detected thefailureof a node, and will not allow the name to bereused. If you use this function tounregister your own process, besure to also close thedescriptor that was returned byei publish().

    Note:

    Careless use of this function may haveunpredictable results, if the registered nodeisin fact still running.

    ec is thenodestructureof thenodeto unregister.

    If the nodewas successfully unregistered from epmd, the function returns0. Otherwise,it returns -1 and setserl errno isto EIO.

    const char * ei thisnodename(ei cnode *ec)

    const char * ei thishostname(ei cnode *ec)

    const char * ei thisalivename(ei cnode *ec)

    These functions can be used to retrieve information about the C Node. These values areinitially set with ei connect init() or ei connect xinit().

    They simply fetches the appropriatefield from the ec structure. Read the field directlywill probably besafe for a long time, so these functions are not really needed.

    erlang pid * ei self(ei cnode *ec)

    Thisfunction retrieves the Pid of the C-node. Every C-node has a (pseudo) pid used inei send reg, ei rpc and others. Thisis contained in a field in theec structure. It willbe safe for a long time to fetch this field directly from the ei cnode structure.

    Debug Information

    If a connection attempt fails, thefollowing can bechecked:

    erl errno

    that theright cookie was used

    that epmd is running

    theremote Erlangnodeon theother side is running thesame version of Erlangasthe erl interface library.

    45Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    50/86

    erl connect Erl Interface Library Reference

    erl connect

    C Module

    This moduleprovidessupport for communication between distributed Erlang nodesand C nodes, in a manner that is transparent to Erlangprocesses.

    A C nodeappears to Erlangas a hidden node. That is, Erlangprocessesthat know thename of theC nodeare able to communicate with it in a normal manner, but the nodename will not appear in thelistingprovided by theErlangfunction nodes/0.

    Exports

    int erl connect init(number, cookie, creation)

    int erl connect xinit(host, alive, node, addr, cookie, creation)

    Types:

    int number;

    char *cookie;

    short creation;

    char *host,*alive,*node;

    struct in addr *addr;

    These functions initializethe erl connect module. In particular, they are used toidentify the name of the C-nodefrom which they are called. Oneof these functionsmust becalled beforeany of theother functions in theerl connect module are used.

    erl connect xinit() stores for later use information about the nodeshost namehost,alive namealive, nodename node, IP address addr, cookiecookie, and creationnumber creation. erl connect init() providesan alternative interfacewhich doesnot require as much information from the caller. Instead, erl connect init() usesgethostbyname() to obtain default values.

    If you use erl connect init() your nodewill have a short name, i.e., it will not befully qualified. If you need to use fully qualified (a.k.a. long) names, useerl connect xinit() instead.

    host is the name of thehost on which the node is running.alive is thealivename of thenode.

    node is thename of thenode. The nodename should beof theformalivename@hostname.

    addr is the32-bit IP address ofhost.

    cookie is theauthorization stringrequired for access to theremote node. Refer to theauth module for more details.

    46 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    51/86

    Erl Interface Library Reference erl connect

    creation helps identify a particular instance of a C node. In particular, it can helpprevent usfrom receiving messages sent to an earlier process with the same registeredname.

    A C nodeacting as a server will beassigned a creation number when it callserl publish() or erl xpublish().

    number is used by erl connect init() to construct the actual node name. In thesecond example shown below, [email protected] will be the resulting node name.

    Example 1:

    struct in_addr addr;

    addr = inet_addr("150.236.14.75");

    if (!erl_connect_xinit("chivas",

    "madonna",

    "[email protected]",

    &addr;

    "samplecookiestring..."),

    0)

    erl_err_quit(" when initializing !");

    Example 2:

    if (!erl_connect_init(17, "samplecookiestring...", 0))

    erl_err_quit(" when initializing !");

    int erl connect(node)

    int erl xconnect(addr, alive)

    Types:

    char *node, *alive;

    struct in addr *addr;

    These functions set up a connection to an Erlang node.erl xconnect() requires the IP address of the remote host and the alivename of theremote nodeto bespecified. erl connect() provides an alternative interface, anddetermines the information from the node nameprovided.

    addr is the32-bit IP address of theremotehost.

    alive is the alivename of the remote node.

    node is thename of theremotenode.

    These functions return an open file descriptor on success, or a negative valueindicatingthat an error occurred in which case they will set erl errno to one of:

    EHOSTUNREACH The remote host node is unreachable

    ENOMEM No more memory available.

    EIO I/O error.

    Additionally, errno valuesfrom socket(2) and connect(2) system calls may bepropagated into erl errno.

    47Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    52/86

  • 7/28/2019 Erl Interface 3.3.2

    53/86

    Erl Interface Library Reference erl connect

    int bufsize;

    ErlMessage *emsg;

    Thisfunction receives the message into the specified buffer, and decodes into the(ErlMessage *) emsg.

    fd is an open descriptor to an Erlangconnection.

    bufp is a buffer large enough to hold the expected message.

    bufsize indicates the size ofbufp.

    emsg is a pointer to an ErlMessage structure, into which the message will bedecoded.ErlMessage is defined as follows:

    typedef struct {

    int type;

    ETERM *msg;

    ETERM *to;

    ETERM *from;

    char to_name[MAXREGLEN];

    } ErlMessage;

    Note:The definition ofErlMessage has changed since earlier versions of Erl Interface.

    type identifies the type of message, one ofERL SEND, ERL REG SEND, ERL LINK,ERL UNLINK and ERL EXIT.

    Iftype contains ERL SEND this indicates that an ordinary send operation has taken place,and emsg-

    to containsthe Pid of the recipient. If type contains ERL REG SEND then aregistered send operation took place, and emsg-

    from contains thePid of thesender. In

    both cases, the actual message will be in emsg-

    msg.Iftype contains one ofERL LINK or ERL UNLINK, then emsg-

    to and emsg-

    from

    contain the pids of the sender and receipient of the link or unlink. emsg-

    msg is notused in these cases.

    Iftype contains ERL EXIT, then thisindicates that a link has been broken. In thiscase,emsg-

    to and emsg-

    from contain the pids of the linked processes, and emsg-

    msg

    contains thereason for theexit.

    Note:It is thecallers responsibility to release thememory pointed to by emsg- msg,emsg- to and emsg- from.

    If a tick occurs, i.e., theErlangnode on theother end of the connection has polled thisnode to see if it is still alive, the function will return ERL TICK indicatingthat thetickhas been received and responded to, but no message will beplaced in thebuffer. In thiscase you should call erl receive msg() again.

    On success, the function returnsERL MSG and theEmsg struct will beinitialized asdescribed above, or ERL TICK, in which case no message is returned. On failure, thefunction returnsERL ERROR and will set erl errno to one of:

    49Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    54/86

    erl connect Erl Interface Library Reference

    EMSGSIZE Buffer too small.

    ENOMEM No more memory available.

    EIO I/O error.

    int erl xreceive msg(fd, bufpp, bufsizep, emsg)Types:

    int fd;

    unsigned char **bufpp;

    int *bufsizep;

    ErlMessage *emsg;

    This function is similar to erl receive msg. The difference is that erl xreceive msgexpectsthe buffer to havebeen allocated bymalloc, and reallocates it if thereceivedmessage does not fit into theoriginal buffer. For that reason, both buffer and bufferlength are given as pointers - their values may change by the call.

    On success, the function returnsERL MSG and theEmsg struct will be initialized as

    described above, or ERL TICK, in which case no message is returned. On failure, thefunction returnsERL ERROR and will set erl errno to one of:

    EMSGSIZE Buffer too small.

    ENOMEM No more memory available.

    EIO I/O error.

    int erl send(fd, to, msg)

    Types:

    int fd;

    ETERM *to, *msg;

    This function sends an Erlang term to a process.

    fd is an open descriptor to an Erlangconnection.

    to is an Erlangterm containingthePid of theintended recipient of themessage.

    msg is the Erlangterm to besent.

    The function returns 1 if successful, otherwise 0 in which case it will set erl errnoto one of:

    EINVAL Invalid argument: to is not a valid Erlang pid.

    ENOMEM No more memory available.

    EIO I/O error.

    int erl reg send(fd, to, msg)

    Types:

    int fd;

    char *to;

    ETERM *msg;

    50 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    55/86

    Erl Interface Library Reference erl connect

    Thisfunction sends an Erlang term to a registered process.

    fd is an open descriptor to an Erlangconnection.

    to is a string containing the registered name of the intended recipient of the message.

    msg is the Erlangterm to besent.

    The function returns 1 if successful, otherwise 0 in which case it will set erl errnoto one of:

    ENOMEM No more memory available.

    EIO I/O error.

    ETERM * erl rpc(fd, mod, fun, args)

    int erl rpc to(fd, mod, fun, args)

    int erl rpc from(fd, timeout, emsg)

    Types:

    int fd, timeout;

    char *mod, *fun;

    ETERM *args;

    ErlMessage *emsg;

    These functions support callingErlang functions on remotenodes. erl rpc to() sendsan rpc request to a remote nodeand erl rpc from() receives theresultsof such a call.erl rpc() combines the functionality of these two functionsby sending an rpc requestand waiting for the results. See also rpc:call/4.

    fd is an open descriptor to an Erlangconnection.

    timeout is themaximum time (in ms) to wait for results. Specify ERL NO TIMEOUT towait forever. When erl rpc() calls erl rpc from(), thecall will never timeout.

    mod is thename of themodule containingthefunction to berun on theremotenode.fun is the name of thefunction to run.

    args is an Erlanglist, containingthearguments to bepassed to thefunction.

    emsg is a message containing the result of thefunction call.

    The actual message returned by the rpc server is a 2-tuple

    rex,Reply

    . If you areusingerl rpc from() in your codethen thisis themessage you will need to parse. Ifyou are usingerl rpc() then thetuple itself is parsed for you, and themessagereturned to your program is theerlangterm containingReply only. Replies to rpcrequests are alwaysERL SEN D messages.

    Note:It is thecallersresponsibility to free thereturned ETERM structure as well as thememory pointed to by emsg- msg and emsg- to.

    erl rpc() returnsthe remotefunctionsreturn value (or NULL if it failed).erl rpc to() returns0 on success, and a negative number on failure. erl rcp from()returns ERL MSG when successful (with Emsg now containingthereply tuple), and oneofERL TICK, ERL TIMEOUT and ERL ERROR otherwise. When failing, all three functionsset erl errno to one of:

    51Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    56/86

    erl connect Erl Interface Library Reference

    ENOMEM No more memory available.

    EIO I/O error.

    ETIMEDOUT Timeout expired.

    EAGAIN Temporary error: Try again.

    int erl publish(port)

    int erl xpublish(port, addr)

    Types:

    int port;

    struct in addr *addr;

    These functions areused by a server process to register with the local name server epmd,thereby allowing other processesto send messages by using the registered name. Beforecalling either of these functions, the processshould havecalled bind() and listen()on an open socket.

    Note:The use oferl xpublish is deprecated. U se erl publish instead.

    port is thelocal name to register, and should bethesame as theport number that waspreviously bound to the socket.

    addr is the32-bit IP address of thelocal host.

    To unregister with epmd, simply close the returned descriptor. See alsoerl unpublish().

    On success, the functionsreturn a descriptor connectingthe calling processto epmd.

    On failure, they return -1 and set erl errno to:

    EIO I/O error

    Additionally, errno valuesfrom socket(2) and connect(2) system calls may bepropagated into erl errno.

    int erl accept(listensock, conp)

    Types:

    int listensock;

    ErlConnect *conp;

    This function is used by a server processto accept a connection from a client process.listensock is an open socket descriptor on which listen() has previously been called.

    conp is a pointer to an ErlConnect struct, described as follows:

    typedef struct {

    char ipadr[4];

    char nodename[MAXNODELEN];

    } ErlConnect;

    52 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    57/86

    Erl Interface Library Reference erl connect

    On success, conp is filled in with theaddress and nodename of theconnecting clientand a file descriptor is returned. O n failure, ERL ERROR is returned and erl errno is setto EIO.

    const char * erl thiscookie()

    const char * erl thisnodename()const char * erl thishostname()

    const char * erl thisalivename()

    short erl thiscreation()

    These functions can be used to retrieve information about the C Node. These values areinitially set with erl connect init() or erl connect xinit().

    int erl unpublish(alive)

    Types:

    char *alive;

    Thisfunction can be called by a process to unregister a specified node name from epmdon thelocalhost. This may beuseful, for example, when epmd has not detected thefailureof a node, and will not allow the name to bereused. If you use this function tounregister your own process, besure to also close thedescriptor that was returned byerl publish().

    Note:Careless use of this function may haveunpredictable results, if the registered nodeisin fact still running.

    alive is the name of the nodeto unregister, i.e., the first component of the nodename,without the@hostname.

    If the nodewas successfully unregistered from epmd, the function returns0. Otherwise,it returns -1 and setserl errno isto EIO.

    Debug Information

    If a connection attempt fails, thefollowing can bechecked:

    erl errno

    that theright cookie was used

    that epmd is running

    theremote Erlangnodeon theother side is running thesame version of Erlangasthe erl interface library.

    53Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    58/86

    erl error Erl Interface Library Reference

    erl error

    C Module

    This modulecontains some error printing routines taken from Advanced ProgrammingintheUNIX Environment by W. Richard Stevens.

    These functions areall called in the same manner as printf(), i.e. with a stringcontaining format specifiers followed by a list of correspondingarguments. All outputfromthese functions is to stderr.

    Exports

    void erl err msg(FormatStr, ... )

    Types:

    const char *FormatStr;

    The message provided by the caller is printed. This function is simply a wrapper forfprintf().

    void erl err quit(FormatStr, ... )

    Types:

    const char *FormatStr;

    Use this function when a fatal error has occurred that is not due to a system call. Themessage provided by thecaller is printed and theprocess terminates with an exit valueof 1. The function does not return.

    void erl err ret(FormatStr, ... )

    Types:

    const char *FormatStr;

    Usethisfunction after a failed system call. The message provided by thecaller isprinted followed by a stringdescribingthereason for failure.

    void erl err sys(FormatStr, ... )

    Types:

    const char *FormatStr;

    Usethisfunction after a failed system call. The message provided by thecaller isprinted followed by a string describingthereason for failure, and the process terminateswith an exit value of 1. The function does not return.

    54 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    59/86

    Erl Interface Library Reference erl error

    Error Reporting

    Most functions in erl interfacereport failures to thecaller by returningsome otherwisemeaningless value (typically NULL or a negativenumber). As thisonly tells you thatthings did not go well, you will have to examinethe error code in erl errno if youwant to find out more about the failure.

    Exports

    volatile int erl errno

    erl errno is initially (at program startup) zero and is then set by many erl interfacefunctionson failureto a non-zero error code to indicate what kind of error itencountered. A successful function call might change erl errno (by calling some otherfunction that fails), but no function will ever set it to zero. This meansthat you cannotuse erl errno to see if a function call failed. Instead, each function reportsfailure in its

    own way (usually by returninga negativenumber or NULL), in which case you canexamine erl errno for details.

    erl errno uses the error codes defined in your systems errno.h .

    Note:Actually, erl errno is a modifiable lvalue (just like ISO C defines errno to be)rather than a variable. This meansit might beimplemented as a macro (expandingto, e.g., * erl errno()). For reasons of thread- (or task-)safety, this is exactly whatwe do on most platforms.

    55Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    60/86

  • 7/28/2019 Erl Interface 3.3.2

    61/86

    Erl Interface Library Reference erl eterm

    int ERL PORT NUMBER(t) The sequence number in port t.

    int ERL PORT CREATION(t) The creation number in port t.

    ETERM *ERL PORT NODE(t) The node in port t.

    int ERL REF NUMBER(t) The first part of thereference number in reft. U se only forcompatibility.

    int ERL REF NUMBERS(t) Pointer to thearray of reference numbers in reft.

    int ERL REF LEN(t) The number of used reference numbersin reft.

    int ERL REF CREATION(t) The creation number in reft.

    int ERL TUPLE SIZE(t) The number of elements in tuple t.

    ETERM *ERL CONS HEAD(t) The head element of list t.

    ETERM *ERL CONS TAIL(t) A L ist representingthe tail elementsof list t.

    Exports

    ETERM * erl cons(head, tail)

    Types:

    ETERM *head;

    ETERM *tail;

    Thisfunction concatenates two Erlang terms, prepending head onto tail and therebycreating a cons cell. To makea proper list, tail should always bea list or an empty list.Note that NULL is not a valid list.

    head is the new term to beadded.

    tail is the existing list to which head will be concatenated.

    The function returns a new list.ERL CONS HEAD(list) and ERL CONS TAIL(list) can beused to retrievethehead andtail componentsfrom the list. erl hd(list) and erl tl(list) will do thesame thing,but check that theargument really is a list.

    For example:

    ETERM *list,*anAtom,*anInt;

    anAtom = erl_mk_atom("madonna");

    anInt = erl_mk_int(21);

    list = erl_mk_empty_list();

    list = erl_cons(anAtom, list);

    list = erl_cons(anInt, list);

    ... /* do some work */

    erl_free_compound(list);

    ETERM * erl copy term(term)

    Types:

    ETERM *term;

    Thisfunction creates and returns a copy of the Erlang term term.

    ETERM * erl element(position, tuple)

    57Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    62/86

    erl eterm Erl Interface Library Reference

    Types:

    int position;

    ETERM *tuple;

    This function extractsa specified element from an Erlang tuple.

    position specifies which element to retrieve from tuple. The elements are numberedstarting from 1.

    tuple is an Erlangterm containingat least position elements.

    The function returns a new Erlang term corresponding to the requested element, orNULL ifposition was greater than thearity oftuple.

    void erl init(NULL, 0)

    Types:

    void *NULL ;

    int 0;

    This function must be called beforeany of the othersin the erl interface library in

    order to initialize the library functions. The argumentsmust bespecified aserl init(NULL,0).

    ETERM * erl hd(list)

    Types:

    ETERM *list;

    Extracts thefirst element froma list.

    list is an Erlangterm containinga list.

    The function returns an Erlang term corresponding to the head element in the list, or aNU LL pointer iflist was not a list.

    ETERM * erl iolist to binary(term)

    Types:

    ETERM *list;

    This function converts an IO list to a binary term.

    list is an Erlangterm containinga list.

    This function an Erlang binary term, or NU LL iflist was not an IO list.

    Informally, an IO list is a deep list of characters and binaries which can besent to anErlangport. In BNF, an IO list is formally defined as follows:

    iolist ::= []

    | Binary

    | [iohead | iolist]

    ;

    iohead ::= Binary

    | Byte (integer in the range [0..255])

    | iolist

    ;

    char * erl iolist to string(list)

    58 Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    63/86

    Erl Interface Library Reference erl eterm

    Types:

    ETERM *list;

    Thisfunction converts an IO list to a \0 terminated C string.

    list is an Erlangterm containing an IO list. TheIO list must not contain the integer 0,sinceC strings may not contain this value except as a terminating marker.

    This function returns a pointer to a dynamically allocated buffer containing a string. Iflist isnot an IO list, or iflist containsthe integer 0, NUL L is returned. It is thecallers responsibility free the allocated buffer with erl free().

    Refer to erl iolist to binary() for the definition of an IO list.

    int erl iolist length(list)

    Types:

    ETERM *list;

    Returns the length of an IO list.

    list is an Erlangterm containing an IO list.

    The function returns the length oflist, or -1 if list is not an IO list.

    Refer to erl iolist to binary() for the definition of an IO list.

    int erl length(list)

    Types:

    ETERM *list;

    Determines thelength of a proper list.

    list is an Erlangterm containingproper list. In a proper list, all tails except thelastpoint to another list cell, and the last tail pointsto an empty list.

    Returns -1 iflist is not a proper list.

    ETERM * erl mk atom(string)

    Types:

    char *string;

    Creates an atom.

    string is thesequence of characters that will beused to create theatom.

    Returns an Erlangterm containingan atom. N otethat it is thecallers responsibility tomake sure that string contains a valid name for an atom.

    ERL ATOM PTR(atom) can beused to retrievetheatom name (as a string). Note that the

    stringis not 0-terminated in theatom. ERL ATOM SIZE(atom)returnsthe length of theatom name.

    ETERM * erl mk binary(bptr, size)

    Types:

    char *bptr;

    int size;

    59Erlang Interface

  • 7/28/2019 Erl Interface 3.3.2

    64/86

    erl eterm Erl Interface Library Reference

    This function produces an Erlang binary object from a buffer containing a sequence ofbytes.

    bptr is a pointer to a buffer containg data to beconverted.

    size indicates the length ofbptr.

    The function returns an Erlang binary object.

    ERL BIN PTR(bin) retrieves a pointer to thebinary data. ERL BIN SIZE(bin) retrievesthe size.

    ETERM * erl mk empty list()

    This function creates and returns an empty Erlang list. N otethat NU LL is not used torepresent an empty list; Use this function instead.

    ETERM * erl mk estring(string, len)

    Types:

    char *string;

    int len;

    This function creates a list from a sequence of bytes.

    string is a buffer containinga sequence of bytes. The buffer does not need to bezero-terminated.

    len is the length ofstring.

    The function returns an Erlang list object corresponding to the character sequence instring.

    ETERM * erl mk float(f)

    Types:

    double f;

    Creates an Erlangfloat.

    f is a valueto beconverted to an Erlangfloat.

    The function returns an Erlang float object with the valuespecified in f.

    ERL FLOAT VALUE(t) can beused to retr