Sophie

Sophie

distrib > Fedora > 17 > i386 > media > updates > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 162

erlang-doc-R15B-03.3.fc17.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../doc/otp_doc.css" type="text/css">
<title>Erlang -- How to implement a driver</title>
</head>
<body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container">
<script id="js" type="text/javascript" language="JavaScript" src="../../../doc/js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../../../doc/js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript">
            <!--
              function getWinHeight() {
                var myHeight = 0;
                if( typeof( window.innerHeight ) == 'number' ) {
                  //Non-IE
                  myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth ||
                                                         document.documentElement.clientHeight ) ) {
                  //IE 6+ in 'standards compliant mode'
                  myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                  //IE 4 compatible
                  myHeight = document.body.clientHeight;
                }
                return myHeight;
              }

              function setscrollpos() {
                var objf=document.getElementById('loadscrollpos');
                 document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2;
              }

              function addEvent(obj, evType, fn){
                if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
              } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
              } else {
                return false;
              }
             }

             addEvent(window, 'load', setscrollpos);

             //--></script><div id="leftnav"><div class="innertube">
<img alt="Erlang logo" src="../../../doc/erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="index.html">Reference Manual</a><br><a href="release_notes.html">Release Notes</a><br><a href="../pdf/erts-5.9.3.1.pdf">PDF</a><br><a href="../../../doc/index.html">Top</a></small><p><strong>Erlang Run-Time System Application (ERTS)</strong><br><strong>User's Guide</strong><br><small>Version 5.9.3.1</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p>
<ul class="flipMenu" imagepath="../../../doc/js/flipmenu">
<li id="no" title="Match specifications in Erlang" expanded="false">Match specifications in Erlang<ul>
<li><a href="match_spec.html">
              Top of chapter
            </a></li>
<li title="Grammar"><a href="match_spec.html#id67432">Grammar</a></li>
<li title="Function descriptions"><a href="match_spec.html#id65382">Function descriptions</a></li>
<li title="Variables and literals"><a href="match_spec.html#id73136">Variables and literals</a></li>
<li title="Execution of the match"><a href="match_spec.html#id73066">Execution of the match</a></li>
<li title="Differences between match specifications in ETS and tracing"><a href="match_spec.html#id69369">Differences between match specifications in ETS and tracing</a></li>
<li title="Examples"><a href="match_spec.html#id69408">Examples</a></li>
</ul>
</li>
<li id="no" title="How to interpret the Erlang crash dumps" expanded="false">How to interpret the Erlang crash dumps<ul>
<li><a href="crash_dump.html">
              Top of chapter
            </a></li>
<li title="General information"><a href="crash_dump.html#id71973">General information</a></li>
<li title="Memory information"><a href="crash_dump.html#id69719">Memory information</a></li>
<li title="Internal table information"><a href="crash_dump.html#id69746">Internal table information</a></li>
<li title="Allocated areas"><a href="crash_dump.html#id71628">Allocated areas</a></li>
<li title="Allocator"><a href="crash_dump.html#id71654">Allocator</a></li>
<li title="Process information"><a href="crash_dump.html#id71693">Process information</a></li>
<li title="Port information"><a href="crash_dump.html#id70337">Port information</a></li>
<li title="ETS tables"><a href="crash_dump.html#id70354">ETS tables</a></li>
<li title="Timers"><a href="crash_dump.html#id70452">Timers</a></li>
<li title="Distribution information"><a href="crash_dump.html#id77672">Distribution information</a></li>
<li title="Loaded module information"><a href="crash_dump.html#id77796">Loaded module information</a></li>
<li title="Fun information"><a href="crash_dump.html#id77887">Fun information</a></li>
<li title="Process Data"><a href="crash_dump.html#id77959">Process Data</a></li>
<li title="Atoms"><a href="crash_dump.html#id78034">Atoms</a></li>
<li title="Disclaimer"><a href="crash_dump.html#id78051">Disclaimer</a></li>
</ul>
</li>
<li id="no" title="How to implement an alternative carrier for  the Erlang distribution" expanded="false">How to implement an alternative carrier for  the Erlang distribution<ul>
<li><a href="alt_dist.html">
              Top of chapter
            </a></li>
<li title="Introduction"><a href="alt_dist.html#id78171">Introduction</a></li>
<li title="The driver"><a href="alt_dist.html#id78261">The driver</a></li>
<li title="Putting it all together"><a href="alt_dist.html#id79511">Putting it all together</a></li>
</ul>
</li>
<li id="no" title="The Abstract Format" expanded="false">The Abstract Format<ul>
<li><a href="absform.html">
              Top of chapter
            </a></li>
<li title="Module declarations and forms"><a href="absform.html#id79791">Module declarations and forms</a></li>
<li title="Atomic literals"><a href="absform.html#id79999">Atomic literals</a></li>
<li title="Patterns"><a href="absform.html#id80061">Patterns</a></li>
<li title="Expressions"><a href="absform.html#id80275">Expressions</a></li>
<li title="Clauses"><a href="absform.html#id80983">Clauses</a></li>
<li title="Guards"><a href="absform.html#id81203">Guards</a></li>
<li title="The abstract format after preprocessing"><a href="absform.html#id81478">The abstract format after preprocessing</a></li>
</ul>
</li>
<li id="no" title="tty - A command line interface" expanded="false">tty - A command line interface<ul>
<li><a href="tty.html">
              Top of chapter
            </a></li>
<li title="Normal Mode"><a href="tty.html#id81651">Normal Mode</a></li>
<li title="Shell Break Mode"><a href="tty.html#id82034">Shell Break Mode</a></li>
</ul>
</li>
<li id="loadscrollpos" title="How to implement a driver" expanded="true">How to implement a driver<ul>
<li><a href="driver.html">
              Top of chapter
            </a></li>
<li title="Introduction"><a href="driver.html#id82159">Introduction</a></li>
<li title="Sample driver"><a href="driver.html#id82191">Sample driver</a></li>
<li title="Compiling and linking the sample driver"><a href="driver.html#id82593">Compiling and linking the sample driver</a></li>
<li title="Calling a driver as a port in Erlang"><a href="driver.html#id82629">Calling a driver as a port in Erlang</a></li>
<li title="Sample asynchronous driver"><a href="driver.html#id82736">Sample asynchronous driver</a></li>
<li title="An asynchronous driver using driver_async"><a href="driver.html#id83010">An asynchronous driver using driver_async</a></li>
</ul>
</li>
<li id="no" title="Inet configuration" expanded="false">Inet configuration<ul>
<li><a href="inet_cfg.html">
              Top of chapter
            </a></li>
<li title="Introduction"><a href="inet_cfg.html#id83274">Introduction</a></li>
<li title="Configuration Data"><a href="inet_cfg.html#id83378">Configuration Data</a></li>
<li title="User Configuration Example"><a href="inet_cfg.html#id84255">User Configuration Example</a></li>
</ul>
</li>
<li id="no" title="External Term Format" expanded="false">External Term Format<ul>
<li><a href="erl_ext_dist.html">
              Top of chapter
            </a></li>
<li title="Introduction"><a href="erl_ext_dist.html#id84356">Introduction</a></li>
<li title="Distribution header"><a href="erl_ext_dist.html#id84636">Distribution header</a></li>
<li title="ATOM_CACHE_REF"><a href="erl_ext_dist.html#id85209">ATOM_CACHE_REF</a></li>
<li title="SMALL_INTEGER_EXT"><a href="erl_ext_dist.html#id85285">SMALL_INTEGER_EXT</a></li>
<li title="INTEGER_EXT"><a href="erl_ext_dist.html#id85348">INTEGER_EXT</a></li>
<li title="FLOAT_EXT"><a href="erl_ext_dist.html#id85412">FLOAT_EXT</a></li>
<li title="ATOM_EXT"><a href="erl_ext_dist.html#id85488">ATOM_EXT</a></li>
<li title="REFERENCE_EXT"><a href="erl_ext_dist.html#id85583">REFERENCE_EXT</a></li>
<li title="PORT_EXT"><a href="erl_ext_dist.html#id85741">PORT_EXT</a></li>
<li title="PID_EXT"><a href="erl_ext_dist.html#id85860">PID_EXT</a></li>
<li title="SMALL_TUPLE_EXT"><a href="erl_ext_dist.html#id86004">SMALL_TUPLE_EXT</a></li>
<li title="LARGE_TUPLE_EXT"><a href="erl_ext_dist.html#id86096">LARGE_TUPLE_EXT</a></li>
<li title="NIL_EXT"><a href="erl_ext_dist.html#id86186">NIL_EXT</a></li>
<li title="STRING_EXT"><a href="erl_ext_dist.html#id86237">STRING_EXT</a></li>
<li title="LIST_EXT"><a href="erl_ext_dist.html#id86329">LIST_EXT</a></li>
<li title="BINARY_EXT"><a href="erl_ext_dist.html#id86448">BINARY_EXT</a></li>
<li title="SMALL_BIG_EXT"><a href="erl_ext_dist.html#id86545">SMALL_BIG_EXT</a></li>
<li title="LARGE_BIG_EXT"><a href="erl_ext_dist.html#id86652">LARGE_BIG_EXT</a></li>
<li title="NEW_REFERENCE_EXT"><a href="erl_ext_dist.html#id86755">NEW_REFERENCE_EXT</a></li>
<li title="SMALL_ATOM_EXT"><a href="erl_ext_dist.html#id86928">SMALL_ATOM_EXT</a></li>
<li title="FUN_EXT"><a href="erl_ext_dist.html#id87034">FUN_EXT</a></li>
<li title="NEW_FUN_EXT"><a href="erl_ext_dist.html#id87281">NEW_FUN_EXT</a></li>
<li title="EXPORT_EXT"><a href="erl_ext_dist.html#id87658">EXPORT_EXT</a></li>
<li title="BIT_BINARY_EXT"><a href="erl_ext_dist.html#id87802">BIT_BINARY_EXT</a></li>
<li title="NEW_FLOAT_EXT"><a href="erl_ext_dist.html#id87908">NEW_FLOAT_EXT</a></li>
</ul>
</li>
<li id="no" title="Distribution Protocol" expanded="false">Distribution Protocol<ul>
<li><a href="erl_dist_protocol.html">
              Top of chapter
            </a></li>
<li title="EPMD Protocol"><a href="erl_dist_protocol.html#id88085">EPMD Protocol</a></li>
<li title="Handshake"><a href="erl_dist_protocol.html#id89383">Handshake</a></li>
<li title="Protocol between connected nodes"><a href="erl_dist_protocol.html#id89399">Protocol between connected nodes</a></li>
<li title="New Ctrlmessages for distrvsn = 1 (OTP R4)"><a href="erl_dist_protocol.html#id89841">New Ctrlmessages for distrvsn = 1 (OTP R4)</a></li>
<li title="New Ctrlmessages for distrvsn = 2"><a href="erl_dist_protocol.html#id89939">New Ctrlmessages for distrvsn = 2</a></li>
<li title="New Ctrlmessages for distrvsn = 3 (OTP R5C)"><a href="erl_dist_protocol.html#id89951">New Ctrlmessages for distrvsn = 3 (OTP R5C)</a></li>
<li title="New Ctrlmessages for distrvsn = 4 (OTP R6)"><a href="erl_dist_protocol.html#id89963">New Ctrlmessages for distrvsn = 4 (OTP R6)</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>6 How to implement a driver</h1>
  

  <div class="note">
<div class="label">Note</div>
<div class="content"><p><p>This document was written a long time ago. A lot of it is still
           interesting since it explains important concepts, but it was
	   written for an older driver interface so the examples do not
	   work anymore. The reader is encouraged to read
	   <span class="bold_code"><a href="erl_driver.html">erl_driver</a></span> and the
	   <span class="bold_code"><a href="driver_entry.html">driver_entry</a></span> documentation.
   </p></p></div>
</div>

  <h3><a name="id82159">6.1 
        Introduction</a></h3>
    
    <p>This chapter tells you how to build your own driver for erlang.</p>
    <p>A driver in Erlang is a library written in C, that is linked to
      the Erlang emulator and called from erlang. Drivers can be used
      when C is more suitable than Erlang, to speed things up, or to
      provide access to OS resources not directly accessible from
      Erlang.</p>
    <p>A driver can be dynamically loaded, as a shared library (known as
      a DLL on windows), or statically loaded, linked with the emulator
      when it is compiled and linked. Only dynamically loaded drivers
      are described here, statically linked drivers are beyond the scope
      of this chapter.</p>
    <p>When a driver is loaded it is executed in the context of the
      emulator, shares the same memory and the same thread. This means
      that all operations in the driver must be non-blocking, and that
      any crash in the driver will bring the whole emulator down. In
      short: you have to be extremely careful!</p>
    <p></p>
  

  <h3><a name="id82191">6.2 
        Sample driver</a></h3>
    
    <p>This is a simple driver for accessing a postgres
      database using the libpq C client library. Postgres
      is used because it's free and open source. For information
      on postgres, refer to the website
      <span class="bold_code"><a href="http://www.postgres.org">www.postgres.org</a></span>.</p>
    <p>The driver is synchronous, it uses the synchronous calls of
      the client library. This is only for simplicity, and is
      generally not good, since it will
      halt the emulator while waiting for the database.
      This will be improved on below with an asynchronous
      sample driver.</p>
    <p>The code is quite straight-forward: all
      communication between Erlang and the driver
      is done with <span class="code">port_control/3</span>, and the
      driver returns data back using the <span class="code">rbuf</span>.</p>
    <p>An Erlang driver only exports one function: the driver
      entry function. This is defined with a macro,
      <span class="code">DRIVER_INIT</span>, and returns a pointer to a
      C <span class="code">struct</span> containing the entry points that are
      called from the emulator. The <span class="code">struct</span> defines the
      entries that the emulator calls to call the driver, with
      a <span class="code">NULL</span> pointer for entries that are not defined
      and used by the driver.</p>
    <p>The <span class="code">start</span> entry is called when the driver
      is opened as a port with <span class="code">open_port/2</span>. Here
      we allocate memory for a user data structure.
      This user data will be passed every time the emulator
      calls us. First we store the driver handle, because it
      is needed in subsequent calls. We allocate memory for
      the connection handle that is used by LibPQ. We also
      set the port to return allocated driver binaries, by
      setting the flag <span class="code">PORT_CONTROL_FLAG_BINARY</span>, calling
      <span class="code">set_port_control_flags</span>. (This is because
      we don't know whether our data will fit in the
      result buffer of <span class="code">control</span>, which has a default size
      set up by the emulator, currently 64 bytes.)</p>
    <p>There is an entry <span class="code">init</span> which is called when
      the driver is loaded, but we don't use this, since
      it is executed only once, and we want to have the
      possibility of several instances of the driver.</p>
    <p>The <span class="code">stop</span> entry is called when the port
      is closed.</p>
    <p>The <span class="code">control</span> entry is called from the emulator
      when the Erlang code calls <span class="code">port_control/3</span>,
      to do the actual work. We have defined a simple set of
      commands: <span class="code">connect</span> to login to the database, <span class="code">disconnect</span>
      to log out and <span class="code">select</span> to send a SQL-query and get the result.
      All results are returned through <span class="code">rbuf</span>.
      The library <span class="code">ei</span> in <span class="code">erl_interface</span> is used
      to encode data in binary term format. The result is returned
      to the emulator as binary terms, so <span class="code">binary_to_term</span>
      is called in Erlang to convert the result to term form.</p>
    <p>The code is available in <span class="code">pg_sync.c</span> in the <span class="code">sample</span>
      directory of <span class="code">erts</span>.</p>
    <p>The driver entry contains the functions that
      will be called by the emulator. In our simple
      example, we only provide <span class="code">start</span>, <span class="code">stop</span>
      and <span class="code">control</span>.</p>
    <div class="example"><pre>
/* Driver interface declarations */
static ErlDrvData start(ErlDrvPort port, char *command);
static void stop(ErlDrvData drv_data);
static int control(ErlDrvData drv_data, unsigned int command, char *buf, 
                   int len, char **rbuf, int rlen); 

static ErlDrvEntry pq_driver_entry = {
    NULL,                        /* init */
    start, 
    stop, 
    NULL,                        /* output */
    NULL,                        /* ready_input */
    NULL,                        /* ready_output */ 
    "pg_sync",                   /* the name of the driver */
    NULL,                        /* finish */
    NULL,                        /* handle */
    control, 
    NULL,                        /* timeout */
    NULL,                        /* outputv */
    NULL,                        /* ready_async */
    NULL,                        /* flush */
    NULL,                        /* call */
    NULL                         /* event */
};
    </pre></div>
    <p>We have a structure to store state needed by the driver,
      in this case we only need to keep the database connection.</p>
    <div class="example"><pre>
typedef struct our_data_s {
    PGconn* conn;
} our_data_t;
    </pre></div>
    <p>These are control codes we have defined.</p>
    <div class="example"><pre>
/* Keep the following definitions in alignment with the
 * defines in erl_pq_sync.erl
 */

#define DRV_CONNECT             'C'
#define DRV_DISCONNECT          'D'
#define DRV_SELECT              'S'
    </pre></div>
    <p>This just returns the driver structure. The macro
      <span class="code">DRIVER_INIT</span> defines the only exported function.
      All the other functions are static, and will not be exported
      from the library.</p>
    <div class="example"><pre>
/* INITIALIZATION AFTER LOADING */

/* 
 * This is the init function called after this driver has been loaded.
 * It must *not* be declared static. Must return the address to 
 * the driver entry.
 */

DRIVER_INIT(pq_drv)
{
    return &amp;pq_driver_entry;
}
    </pre></div>
    <p>Here we do some initialization, <span class="code">start</span> is called from
      <span class="code">open_port</span>. The data will be passed to <span class="code">control</span>
      and <span class="code">stop</span>.</p>
    <div class="example"><pre>
/* DRIVER INTERFACE */
static ErlDrvData start(ErlDrvPort port, char *command)
{ 
    our_data_t* data;

    data = (our_data_t*)driver_alloc(sizeof(our_data_t));
    data-&gt;conn = NULL;
    set_port_control_flags(port, PORT_CONTROL_FLAG_BINARY);
    return (ErlDrvData)data;
}
    </pre></div>
    <p>We call disconnect to log out from the database.
      (This should have been done from Erlang, but just in case.)</p>
    <div class="example"><pre>
static int do_disconnect(our_data_t* data, ei_x_buff* x);

static void stop(ErlDrvData drv_data)
{
    our_data_t* data = (our_data_t*)drv_data;

    do_disconnect(data, NULL);
    driver_free(data);
}
    </pre></div>
    <p>We use the binary format only to return data to the emulator;
      input data is a string paramater for <span class="code">connect</span> and
      <span class="code">select</span>. The returned data consists of Erlang terms.</p>
    <p>The functions <span class="code">get_s</span> and <span class="code">ei_x_to_new_binary</span> are
      utilities that are used to make the code shorter. <span class="code">get_s</span>
      duplicates the string and zero-terminates it, since the
      postgres client library wants that. <span class="code">ei_x_to_new_binary</span>
      takes an <span class="code">ei_x_buff</span> buffer and allocates a binary and
      copies the data there. This binary is returned in <span class="code">*rbuf</span>.
      (Note that this binary is freed by the emulator, not by us.)</p>
    <div class="example"><pre>
static char* get_s(const char* buf, int len);
static int do_connect(const char *s, our_data_t* data, ei_x_buff* x);
static int do_select(const char* s, our_data_t* data, ei_x_buff* x);

/* Since we are operating in binary mode, the return value from control
 * is irrelevant, as long as it is not negative.
 */
static int control(ErlDrvData drv_data, unsigned int command, char *buf, 
                   int len, char **rbuf, int rlen)
{
    int r;
    ei_x_buff x;
    our_data_t* data = (our_data_t*)drv_data;
    char* s = get_s(buf, len);
    ei_x_new_with_version(&amp;x);
    switch (command) {
        case DRV_CONNECT:    r = do_connect(s, data, &amp;x);  break;
        case DRV_DISCONNECT: r = do_disconnect(data, &amp;x);  break;
        case DRV_SELECT:     r = do_select(s, data, &amp;x);   break;
        default:             r = -1;        break;
    }
    *rbuf = (char*)ei_x_to_new_binary(&amp;x);
    ei_x_free(&amp;x);
    driver_free(s);
    return r;
}
    </pre></div>
    <p><span class="code">do_connect</span> is where we log in to the database. If the connection
      was successful we store the connection handle in our driver
      data, and return ok. Otherwise, we return the error message
      from postgres, and store <span class="code">NULL</span> in the driver data.</p>
    <div class="example"><pre>
static int do_connect(const char *s, our_data_t* data, ei_x_buff* x)
{
    PGconn* conn = PQconnectdb(s);
    if (PQstatus(conn) != CONNECTION_OK) {
        encode_error(x, conn);
        PQfinish(conn);
        conn = NULL;
    } else {
        encode_ok(x);
    }
    data-&gt;conn = conn;
    return 0;
}
    </pre></div>
    <p>If we are connected (if the connection handle is not <span class="code">NULL</span>),
      we log out from the database. We need to check if we should
      encode an ok, since we might get here from the <span class="code">stop</span>
      function, which doesn't return data to the emulator.</p>
    <div class="example"><pre>
static int do_disconnect(our_data_t* data, ei_x_buff* x)
{
    if (data-&gt;conn == NULL)
        return 0;
    PQfinish(data-&gt;conn);
    data-&gt;conn = NULL;
    if (x != NULL)
        encode_ok(x);
    return 0;
}
    </pre></div>
    <p>We execute a query and encode the result. Encoding is done
      in another C module, <span class="code">pg_encode.c</span> which is also provided
      as sample code.</p>
    <div class="example"><pre>
static int do_select(const char* s, our_data_t* data, ei_x_buff* x)
{
   PGresult* res = PQexec(data-&gt;conn, s);
    encode_result(x, res, data-&gt;conn);
    PQclear(res);
    return 0;
}
    </pre></div>
    <p>Here we simply check the result from postgres, and
      if it's data we encode it as lists of lists with
      column data. Everything from postgres is C strings,
      so we just use <span class="code">ei_x_encode_string</span> to send
      the result as strings to Erlang. (The head of the list
      contains the column names.)</p>
    <div class="example"><pre>
void encode_result(ei_x_buff* x, PGresult* res, PGconn* conn)
{
    int row, n_rows, col, n_cols;
    switch (PQresultStatus(res)) {
    case PGRES_TUPLES_OK: 
        n_rows = PQntuples(res); 
        n_cols = PQnfields(res); 
        ei_x_encode_tuple_header(x, 2);
        encode_ok(x);
        ei_x_encode_list_header(x, n_rows+1);
        ei_x_encode_list_header(x, n_cols);
        for (col = 0; col &lt; n_cols; ++col) {
            ei_x_encode_string(x, PQfname(res, col));
        }
        ei_x_encode_empty_list(x); 
        for (row = 0; row &lt; n_rows; ++row) {
            ei_x_encode_list_header(x, n_cols);
            for (col = 0; col &lt; n_cols; ++col) {
                ei_x_encode_string(x, PQgetvalue(res, row, col));
            }
            ei_x_encode_empty_list(x);
        }
        ei_x_encode_empty_list(x); 
        break; 
    case PGRES_COMMAND_OK:
        ei_x_encode_tuple_header(x, 2);
        encode_ok(x);
        ei_x_encode_string(x, PQcmdTuples(res));
        break;
    default:
        encode_error(x, conn);
        break;
    }
}
    </pre></div>
  

  <h3><a name="id82593">6.3 
        Compiling and linking the sample driver</a></h3>
    
    <p>The driver should be compiled and linked to a shared
      library (DLL on windows). With gcc this is done
      with the link flags <span class="code">-shared</span> and <span class="code">-fpic</span>.
      Since we use the <span class="code">ei</span> library we should include
      it too. There are several versions of <span class="code">ei</span>, compiled
      for debug or non-debug and multi-threaded or single-threaded.
      In the makefile for the samples the <span class="code">obj</span> directory
      is used for the <span class="code">ei</span> library, meaning that we use
      the non-debug, single-threaded version.</p>
  

  <h3><a name="id82629">6.4 
        Calling a driver as a port in Erlang</a></h3>
    
    <p>Before a driver can be called from Erlang, it must be
      loaded and opened. Loading is done using the <span class="code">erl_ddll</span>
      module (the <span class="code">erl_ddll</span> driver that loads dynamic
      driver, is actually a driver itself). If loading is ok
      the port can be opened with <span class="code">open_port/2</span>. The port
      name must match the name of the shared library and
      the name in the driver entry structure.</p>
    <p>When the port has been opened, the driver can be called. In
      the <span class="code">pg_sync</span> example, we don't have any data from
      the port, only the return value from the
      <span class="code">port_control</span>.</p>
    <p>The following code is the Erlang part of the synchronous
      postgres driver, <span class="code">pg_sync.erl</span>.</p>
    <div class="example"><pre>
-module(pg_sync).

-define(DRV_CONNECT, 1).
-define(DRV_DISCONNECT, 2).
-define(DRV_SELECT, 3).

-export([connect/1, disconnect/1, select/2]).

connect(ConnectStr) -&gt;
    case erl_ddll:load_driver(".", "pg_sync") of
        ok -&gt; ok;
        {error, already_loaded} -&gt; ok;
        E -&gt; exit({error, E})
    end,
    Port = open_port({spawn, ?MODULE}, []),
    case binary_to_term(port_control(Port, ?DRV_CONNECT, ConnectStr)) of
        ok -&gt; {ok, Port};
        Error -&gt; Error
    end.

disconnect(Port) -&gt;
    R = binary_to_term(port_control(Port, ?DRV_DISCONNECT, "")),
    port_close(Port),
    R.

select(Port, Query) -&gt;
    binary_to_term(port_control(Port, ?DRV_SELECT, Query)).
    </pre></div>
    <p>The API is simple: <span class="code">connect/1</span> loads the driver, opens it
      and logs on to the database, returning the Erlang port
      if successful, <span class="code">select/2</span> sends a query to the driver,
      and returns the result, <span class="code">disconnect/1</span> closes the
      database connection and the driver. (It does not unload it,
      however.) The connection string should be a connection
      string for postgres.</p>
    <p>The driver is loaded with <span class="code">erl_ddll:load_driver/2</span>,
      and if this is successful, or if it's already loaded,
      it is opened. This will call the <span class="code">start</span> function
      in the driver.</p>
    <p>We use the <span class="code">port_control/3</span> function for all
      calls into the driver, the result from the driver is
      returned immediately, and converted to terms by calling
      <span class="code">binary_to_term/1</span>. (We trust that the terms returned
      from the driver are well-formed, otherwise the
      <span class="code">binary_to_term</span> calls could be contained in a
      <span class="code">catch</span>.)</p>
  

  <h3><a name="id82736">6.5 
        Sample asynchronous driver</a></h3>
    
    <p>Sometimes database queries can take long time to
      complete, in our <span class="code">pg_sync</span> driver, the emulator
      halts while the driver is doing its job. This is
      often not acceptable, since no other Erlang process
      gets a chance to do anything. To improve on our
      postgres driver, we reimplement it using the asynchronous
      calls in LibPQ.</p>
    <p>The asynchronous version of the driver is in the
      sample files <span class="code">pg_async.c</span> and <span class="code">pg_asyng.erl</span>.</p>
    <div class="example"><pre>
/* Driver interface declarations */
static ErlDrvData start(ErlDrvPort port, char *command);
static void stop(ErlDrvData drv_data);
static int control(ErlDrvData drv_data, unsigned int command, char *buf, 
                   int len, char **rbuf, int rlen); 
static void ready_io(ErlDrvData drv_data, ErlDrvEvent event);

static ErlDrvEntry pq_driver_entry = {
    NULL,                     /* init */
    start, 
    stop, 
    NULL,                     /* output */
    ready_io,                 /* ready_input */
    ready_io,                 /* ready_output */ 
    "pg_async",               /* the name of the driver */
    NULL,                     /* finish */
    NULL,                     /* handle */
    control, 
    NULL,                     /* timeout */
    NULL,                     /* outputv */
    NULL,                     /* ready_async */
    NULL,                     /* flush */
    NULL,                     /* call */
    NULL                      /* event */
};

typedef struct our_data_t {
    PGconn* conn;
    ErlDrvPort port;
    int socket;
    int connecting;
} our_data_t;
    </pre></div>
    <p>Here some things have changed from <span class="code">pg_sync.c</span>: we use the
      entry <span class="code">ready_io</span> for <span class="code">ready_input</span> and
      <span class="code">ready_output</span> which will be called from the emulator only
      when there is input to be read from the socket. (Actually, the
      socket is used in a <span class="code">select</span> function inside
      the emulator, and when the socket is signalled,
      indicating there is data to read, the <span class="code">ready_input</span> entry
      is called. More on this below.)</p>
    <p>Our driver data is also extended, we keep track of the
      socket used for communication with postgres, and also
      the port, which is needed when we send data to the port with
      <span class="code">driver_output</span>. We have a flag <span class="code">connecting</span> to tell
      whether the driver is waiting for a connection or waiting
      for the result of a query. (This is needed since the entry
      <span class="code">ready_io</span> will be called both when connecting and
      when there is a query result.)</p>
    <div class="example"><pre>
static int do_connect(const char *s, our_data_t* data)
{
    PGconn* conn = PQconnectStart(s);
    if (PQstatus(conn) == CONNECTION_BAD) {
        ei_x_buff x;
        ei_x_new_with_version(&amp;x);
        encode_error(&amp;x, conn);
        PQfinish(conn);
        conn = NULL;
        driver_output(data-&gt;port, x.buff, x.index);
        ei_x_free(&amp;x);
    }
    PQconnectPoll(conn);
    int socket = PQsocket(conn);
    data-&gt;socket = socket;
    driver_select(data-&gt;port, (ErlDrvEvent)socket, DO_READ, 1);
    driver_select(data-&gt;port, (ErlDrvEvent)socket, DO_WRITE, 1);
    data-&gt;conn = conn;
    data-&gt;connecting = 1;
    return 0;
}
    </pre></div>
    <p>The <span class="code">connect</span> function looks a bit different too. We connect
      using the asynchronous <span class="code">PQconnectStart</span> function. After the
      connection is started, we retrieve the socket for the connection
      with <span class="code">PQsocket</span>. This socket is used with the
      <span class="code">driver_select</span> function to wait for connection. When
      the socket is ready for input or for output, the <span class="code">ready_io</span>
      function will be called.</p>
    <p>Note that we only return data (with <span class="code">driver_output</span>) if there
      is an error here, otherwise we wait for the connection to be completed,
      in which case our <span class="code">ready_io</span> function will be called.</p>
    <div class="example"><pre>
static int do_select(const char* s, our_data_t* data)
{
    data-&gt;connecting = 0;
    PGconn* conn = data-&gt;conn;
    /* if there's an error return it now */
    if (PQsendQuery(conn, s) == 0) {
        ei_x_buff x;
        ei_x_new_with_version(&amp;x);
        encode_error(&amp;x, conn);
        driver_output(data-&gt;port, x.buff, x.index);
        ei_x_free(&amp;x);
    }
    /* else wait for ready_output to get results */
    return 0;
}
    </pre></div>
    <p>The <span class="code">do_select</span> function initiates a select, and returns
      if there is no immediate error. The actual result will be returned
      when <span class="code">ready_io</span> is called.</p>
    <div class="example"><pre>
static void ready_io(ErlDrvData drv_data, ErlDrvEvent event)
{
    PGresult* res = NULL;
    our_data_t* data = (our_data_t*)drv_data;
    PGconn* conn = data-&gt;conn;
    ei_x_buff x;
    ei_x_new_with_version(&amp;x);
    if (data-&gt;connecting) {
        ConnStatusType status;
        PQconnectPoll(conn);
        status = PQstatus(conn);
        if (status == CONNECTION_OK)
            encode_ok(&amp;x);
        else if (status == CONNECTION_BAD)
            encode_error(&amp;x, conn);
    } else {
        PQconsumeInput(conn);
        if (PQisBusy(conn))
            return;
        res = PQgetResult(conn);
        encode_result(&amp;x, res, conn);
        PQclear(res);
        for (;;) {
            res = PQgetResult(conn);
            if (res == NULL)
                break;
            PQclear(res);
        }
    }
    if (x.index &gt; 1) {
        driver_output(data-&gt;port, x.buff, x.index);
        if (data-&gt;connecting) 
            driver_select(data-&gt;port, (ErlDrvEvent)data-&gt;socket, DO_WRITE, 0);
    }
    ei_x_free(&amp;x);
}
    </pre></div>
    <p>The <span class="code">ready_io</span> function will be called when the socket
      we got from postgres is ready for input or output. Here
      we first check if we are connecting to the database. In that
      case we check connection status and return ok if the 
      connection is successful, or error if it's not. If the
      connection is not yet established, we simply return; <span class="code">ready_io</span>
      will be called again.</p>
    <p>If we have a result from a connect, indicated by having data in
      the <span class="code">x</span> buffer, we no longer need to select on
      output (<span class="code">ready_output</span>), so we remove this by calling
      <span class="code">driver_select</span>.</p>
    <p>If we're not connecting, we're waiting for results from a
      <span class="code">PQsendQuery</span>, so we get the result and return it. The
      encoding is done with the same functions as in the earlier
      example.</p>
    <p>We should add error handling here, for instance checking
      that the socket is still open, but this is just a simple
      example.</p>
    <p>The Erlang part of the asynchronous driver consists of the
      sample file <span class="code">pg_async.erl</span>.</p>
    <div class="example"><pre>
-module(pg_async).

-define(DRV_CONNECT, $C).
-define(DRV_DISCONNECT, $D).
-define(DRV_SELECT, $S).

-export([connect/1, disconnect/1, select/2]).

connect(ConnectStr) -&gt;
    case erl_ddll:load_driver(".", "pg_async") of
        ok -&gt; ok;
        {error, already_loaded} -&gt; ok;
        _ -&gt; exit({error, could_not_load_driver})
    end,
    Port = open_port({spawn, ?MODULE}, [binary]),
    port_control(Port, ?DRV_CONNECT, ConnectStr),
    case return_port_data(Port) of
        ok -&gt; 
            {ok, Port};
        Error -&gt;
            Error
    end.    

disconnect(Port) -&gt;
    port_control(Port, ?DRV_DISCONNECT, ""),
    R = return_port_data(Port),
    port_close(Port),
    R.

select(Port, Query) -&gt;
    port_control(Port, ?DRV_SELECT, Query),
    return_port_data(Port).

return_port_data(Port) -&gt;
    receive
        {Port, {data, Data}} -&gt;
            binary_to_term(Data)
    end.
    </pre></div>
    <p>The Erlang code is slightly different, this is because we
      don't return the result synchronously from <span class="code">port_control</span>,
      instead we get it from <span class="code">driver_output</span> as data in the
      message queue. The function <span class="code">return_port_data</span> above
      receives data from the port. Since the data is in
      binary format, we use <span class="code">binary_to_term/1</span> to convert
      it to an Erlang term. Note that the driver is opened in
      binary mode (<span class="code">open_port/2</span> is called with the option
      <span class="code">[binary]</span>). This means that data sent from the driver
      to the emulator is sent as binaries. Without the <span class="code">binary</span>
      option, they would have been lists of integers.</p>
  

  <h3><a name="id83010">6.6 
        An asynchronous driver using driver_async</a></h3>
    
    <p>As a final example we demonstrate the use of <span class="code">driver_async</span>.
      We also use the driver term interface. The driver is written
      in C++. This enables us to use an algorithm from STL. We will
      use the <span class="code">next_permutation</span> algorithm to get the next permutation
      of a list of integers. For large lists (more than 100000
      elements), this will take some time, so we will perform this
      as an asynchronous task.</p>
    <p>The asynchronous API for drivers is quite complicated. First
      of all, the work must be prepared. In our example we do this
      in <span class="code">output</span>. We could have used <span class="code">control</span> just as well,
      but we want some variation in our examples. In our driver, we allocate
      a structure that contains anything that's needed for the asynchronous task
      to do the work. This is done in the main emulator thread.
      Then the asynchronous function is called from a driver thread,
      separate from the main emulator thread. Note that the driver-functions
      are not reentrant, so they shouldn't be used.
      Finally, after the function is completed, the driver callback
      <span class="code">ready_async</span> is called from the main emulator thread,
      this is where we return the result to Erlang. (We can't
      return the result from within the asynchronous function, since
      we can't call the driver-functions.)</p>
    <p>The code below is from the sample file <span class="code">next_perm.cc</span>.</p>
    <p>The driver entry looks like before, but also contains the
      call-back <span class="code">ready_async</span>.</p>
    <div class="example"><pre>
static ErlDrvEntry next_perm_driver_entry = {
    NULL,                        /* init */
    start,
    NULL,                        /* stop */
    output,
    NULL,                        /* ready_input */
    NULL,                        /* ready_output */ 
    "next_perm",                 /* the name of the driver */
    NULL,                        /* finish */
    NULL,                        /* handle */
    NULL,                        /* control */
    NULL,                        /* timeout */
    NULL,                        /* outputv */
    ready_async,
    NULL,                        /* flush */
    NULL,                        /* call */
    NULL                         /* event */
};
    </pre></div>
    <p>The <span class="code">output</span> function allocates the work-area of the
      asynchronous function. Since we use C++, we use a struct,
      and stuff the data in it. We have to copy the original data,
      it is not valid after we have returned from the <span class="code">output</span>
      function, and the <span class="code">do_perm</span> function will be called later,
      and from another thread. We return no data here, instead it will
      be sent later from the <span class="code">ready_async</span> call-back.</p>
    <p>The <span class="code">async_data</span> will be passed to the <span class="code">do_perm</span> function.
      We do not use a <span class="code">async_free</span> function (the last argument to
      <span class="code">driver_async</span>), it's only used if the task is cancelled
      programmatically.</p>
    <div class="example"><pre>
struct our_async_data {
    bool prev;
    vector&lt;int&gt; data;
    our_async_data(ErlDrvPort p, int command, const char* buf, int len);
};

our_async_data::our_async_data(ErlDrvPort p, int command,
                               const char* buf, int len)
    : prev(command == 2),
      data((int*)buf, (int*)buf + len / sizeof(int))
{
}

static void do_perm(void* async_data);

static void output(ErlDrvData drv_data, char *buf, int len)
{
    if (*buf &lt; 1 || *buf &gt; 2) return;
    ErlDrvPort port = reinterpret_cast&lt;ErlDrvPort&gt;(drv_data);
    void* async_data = new our_async_data(port, *buf, buf+1, len);
    driver_async(port, NULL, do_perm, async_data, do_free);
}
    </pre></div>
    <p>In the <span class="code">do_perm</span> we simply do the work, operating
      on the structure that was allocated in <span class="code">output</span>.</p>
    <div class="example"><pre>
static void do_perm(void* async_data)
{
    our_async_data* d = reinterpret_cast&lt;our_async_data*&gt;(async_data);
    if (d-&gt;prev)
        prev_permutation(d-&gt;data.begin(), d-&gt;data.end());
    else
        next_permutation(d-&gt;data.begin(), d-&gt;data.end());
}
    </pre></div>
    <p>In the <span class="code">ready_async</span> function, the output is sent back to the
      emulator. We use the driver term format instead of <span class="code">ei</span>.
      This is the only way to send Erlang terms directly to a driver,
      without having the Erlang code to call <span class="code">binary_to_term/1</span>. In
      our simple example this works well, and we don't need to use
      <span class="code">ei</span> to handle the binary term format.</p>
    <p>When the data is returned we deallocate our data.</p>
    <div class="example"><pre>
static void ready_async(ErlDrvData drv_data, ErlDrvThreadData async_data)
{
    ErlDrvPort port = reinterpret_cast&lt;ErlDrvPort&gt;(drv_data);
    our_async_data* d = reinterpret_cast&lt;our_async_data*&gt;(async_data);
    int n = d-&gt;data.size(), result_n = n*2 + 3;
    ErlDrvTermData *result = new ErlDrvTermData[result_n], *rp = result;
    for (vector&lt;int&gt;::iterator i = d-&gt;data.begin();
         i != d-&gt;data.end(); ++i) {
        *rp++ = ERL_DRV_INT;
        *rp++ = *i;
    }
    *rp++ = ERL_DRV_NIL;
    *rp++ = ERL_DRV_LIST;
    *rp++ = n+1;
    driver_output_term(port, result, result_n);    
    delete[] result;
    delete d;
}
    </pre></div>
    <p>This driver is called like the others from Erlang, however, since
      we use <span class="code">driver_output_term</span>, there is no need to call
      binary_to_term. The Erlang code is in the sample file
      <span class="code">next_perm.erl</span>.</p>
    <p>The input is changed into a list of integers and sent to
      the driver.</p>
    <div class="example"><pre>
-module(next_perm).

-export([next_perm/1, prev_perm/1, load/0, all_perm/1]).

load() -&gt;
    case whereis(next_perm) of
        undefined -&gt;
            case erl_ddll:load_driver(".", "next_perm") of
                ok -&gt; ok;
                {error, already_loaded} -&gt; ok;
                E -&gt; exit(E)
            end,
            Port = open_port({spawn, "next_perm"}, []),
            register(next_perm, Port);
        _ -&gt;
            ok
    end.

list_to_integer_binaries(L) -&gt;
    [&lt;&lt;I:32/integer-native&gt;&gt; || I &lt;- L].

next_perm(L) -&gt;
    next_perm(L, 1).

prev_perm(L) -&gt;
    next_perm(L, 2).

next_perm(L, Nxt) -&gt;
    load(),
    B = list_to_integer_binaries(L),
    port_control(next_perm, Nxt, B),
    receive
        Result -&gt;
            Result
    end.

all_perm(L) -&gt;
    New = prev_perm(L),
    all_perm(New, L, [New]).

all_perm(L, L, Acc) -&gt;
    Acc;
all_perm(L, Orig, Acc) -&gt;
    New = prev_perm(L),
    all_perm(New, Orig, [New | Acc]).
    </pre></div>
  
</div>
<div class="footer">
<hr>
<p>Copyright © 1997-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>