Sophie

Sophie

distrib > Fedora > 17 > x86_64 > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 134

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="../otp_doc.css" type="text/css">
<title>Erlang -- Port drivers</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="../js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../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="../erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="../pdf/otp-system-documentation-5.9.3.1.pdf">PDF</a><br><a href="../index.html">Top</a></small><p><strong>Interoperability Tutorial</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="../js/flipmenu">
<li id="no" title="Introduction" expanded="false">Introduction<ul>
<li><a href="introduction.html">
              Top of chapter
            </a></li>
<li title="Purpose"><a href="introduction.html#id60800">Purpose</a></li>
<li title="Prerequisites"><a href="introduction.html#id60757">Prerequisites</a></li>
</ul>
</li>
<li id="no" title="Overview" expanded="false">Overview<ul>
<li><a href="overview.html">
              Top of chapter
            </a></li>
<li title="Built-In Mechanisms"><a href="overview.html#id62194">Built-In Mechanisms</a></li>
<li title="C and Java Libraries"><a href="overview.html#id60915">C and Java Libraries</a></li>
<li title="Standard Protocols"><a href="overview.html#id62774">Standard Protocols</a></li>
<li title="IC"><a href="overview.html#id61047">IC</a></li>
<li title="Old Applications"><a href="overview.html#id62555">Old Applications</a></li>
</ul>
</li>
<li id="no" title="Problem Example" expanded="false">Problem Example<ul>
<li><a href="example.html">
              Top of chapter
            </a></li>
<li title="Description"><a href="example.html#id63860">Description</a></li>
</ul>
</li>
<li id="no" title="Ports" expanded="false">Ports<ul>
<li><a href="c_port.html">
              Top of chapter
            </a></li>
<li title="Erlang Program"><a href="c_port.html#id58262">Erlang Program</a></li>
<li title="C Program"><a href="c_port.html#id62416">C Program</a></li>
<li title="Running the Example"><a href="c_port.html#id63496">Running the Example</a></li>
</ul>
</li>
<li id="no" title="Erl_Interface" expanded="false">Erl_Interface<ul>
<li><a href="erl_interface.html">
              Top of chapter
            </a></li>
<li title="Erlang Program"><a href="erl_interface.html#id63174">Erlang Program</a></li>
<li title="C Program"><a href="erl_interface.html#id63282">C Program</a></li>
<li title="Running the Example"><a href="erl_interface.html#id61784">Running the Example</a></li>
</ul>
</li>
<li id="loadscrollpos" title="Port drivers" expanded="true">Port drivers<ul>
<li><a href="c_portdriver.html">
              Top of chapter
            </a></li>
<li title="Port Drivers"><a href="c_portdriver.html#id61981">Port Drivers</a></li>
<li title="Erlang Program"><a href="c_portdriver.html#id62001">Erlang Program</a></li>
<li title="C Driver"><a href="c_portdriver.html#id62119">C Driver</a></li>
<li title="Running the Example"><a href="c_portdriver.html#id63970">Running the Example</a></li>
</ul>
</li>
<li id="no" title="C Nodes" expanded="false">C Nodes<ul>
<li><a href="cnode.html">
              Top of chapter
            </a></li>
<li title="Erlang Program"><a href="cnode.html#id64088">Erlang Program</a></li>
<li title="C Program"><a href="cnode.html#id64168">C Program</a></li>
<li title="Running the Example"><a href="cnode.html#id64499">Running the Example</a></li>
</ul>
</li>
<li id="no" title="NIFs" expanded="false">NIFs<ul>
<li><a href="nif.html">
              Top of chapter
            </a></li>
<li title="NIFs"><a href="nif.html#id64799">NIFs</a></li>
<li title="Erlang Program"><a href="nif.html#id64820">Erlang Program</a></li>
<li title="NIF library code"><a href="nif.html#id64884">NIF library code</a></li>
<li title="Running the Example"><a href="nif.html#id64985">Running the Example</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>6 Port drivers</h1>
  
  <p>This is an example of how to solve the <span class="bold_code"><a href="example.html">example problem</a></span> by using a linked in port driver.</p>
  <img alt="IMAGE MISSING" src="../tutorial/port_driver.gif"><br>
    <em>Figure
        6.1:
         
        Port Driver Communication.</em>
  

  <h3><a name="id61981">6.1 
        Port Drivers</a></h3>
    
    <p>A port driver is a linked in driver, that is accessible as a
      port from an Erlang program. It is a shared library (SO in Unix,
      DLL in Windows), with special entry points. The Erlang runtime
      calls these entry points, when the driver is started and when
      data is sent to the port. The port driver can also send data to
      Erlang.</p>
    <p>Since a port driver is dynamically linked into the emulator
      process, this is the fastest way of calling C-code from Erlang.
      Calling functions in the port driver requires no context
      switches. But it is also the least safe, because a crash in the
      port driver brings the emulator down too.</p>
  

  <h3><a name="id62001">6.2 
        Erlang Program</a></h3>
    
    <p>Just as with a port program, the port communicates with a Erlang
      process. All communication goes through one Erlang process that
      is the <strong>connected process</strong> of the port
      driver. Terminating this process closes the port driver.</p>
    <p>Before the port is created, the driver must be loaded. This is
      done with the function <span class="code">erl_dll:load_driver/1</span>, with the
      name of the shared library as argument.</p>
    <p>The port is then created using the BIF <span class="code">open_port/2</span> with
      the tuple <span class="code">{spawn, DriverName}</span> as the first argument. The
      string <span class="code">SharedLib</span> is the name of the port driver. The second
      argument is a list of options, none in this case.</p>
    <div class="example"><pre>
-module(complex5).
-export([start/1, init/1]).

start(SharedLib) -&gt;
    case erl_ddll:load_driver(".", SharedLib) of
        ok -&gt; ok;
        {error, already_loaded} -&gt; ok;
        _ -&gt; exit({error, could_not_load_driver})
    end,
    spawn(?MODULE, init, [SharedLib]).

init(SharedLib) -&gt;
  register(complex, self()),
  Port = open_port({spawn, SharedLib}, []),
  loop(Port).</pre></div>
    <p>Now it is possible to implement <span class="code">complex5:foo/1</span> and
      <span class="code">complex5:bar/1</span>. They both send a message to the
      <span class="code">complex</span> process and receive the reply.</p>
    <div class="example"><pre>
foo(X) -&gt;
    call_port({foo, X}).
bar(Y) -&gt;
    call_port({bar, Y}).

call_port(Msg) -&gt;
    complex ! {call, self(), Msg},
    receive
        {complex, Result} -&gt;
            Result
    end.</pre></div>
    <p>The <span class="code">complex</span> process encodes the message into a sequence
      of bytes, sends it to the port, waits for a reply, decodes the
      reply and sends it back to the caller.
      </p>
    <div class="example"><pre>
loop(Port) -&gt;
    receive
        {call, Caller, Msg} -&gt;
            Port ! {self(), {command, encode(Msg)}},
            receive
                {Port, {data, Data}} -&gt;
                    Caller ! {complex, decode(Data)}
            end,
            loop(Port)
    end.</pre></div>
    <p>Assuming that both the arguments and the results from the C
      functions will be less than 256, a very simple encoding/decoding
      scheme is employed where <span class="code">foo</span> is represented by the byte
      1, <span class="code">bar</span> is represented by 2, and the argument/result is
      represented by a single byte as well.
      </p>
    <div class="example"><pre>
encode({foo, X}) -&gt; [1, X];
encode({bar, Y}) -&gt; [2, Y].
      
decode([Int]) -&gt; Int.</pre></div>
    <p>The resulting Erlang program, including functionality for
      stopping the port and detecting port failures is shown below.</p>
<div class="example"><pre>

-module(complex5).
-export([start/1, stop/0, init/1]).
-export([foo/1, bar/1]).

start(SharedLib) -&gt;
    case erl_ddll:load_driver(".", SharedLib) of
	ok -&gt; ok;
	{error, already_loaded} -&gt; ok;
	_ -&gt; exit({error, could_not_load_driver})
    end,
    spawn(?MODULE, init, [SharedLib]).

init(SharedLib) -&gt;
    register(complex, self()),
    Port = open_port({spawn, SharedLib}, []),
    loop(Port).

stop() -&gt;
    complex ! stop.

foo(X) -&gt;
    call_port({foo, X}).
bar(Y) -&gt;
    call_port({bar, Y}).

call_port(Msg) -&gt;
    complex ! {call, self(), Msg},
    receive
	{complex, Result} -&gt;
	    Result
    end.

loop(Port) -&gt;
    receive
	{call, Caller, Msg} -&gt;
	    Port ! {self(), {command, encode(Msg)}},
	    receive
		{Port, {data, Data}} -&gt;
		    Caller ! {complex, decode(Data)}
	    end,
	    loop(Port);
	stop -&gt;
	    Port ! {self(), close},
	    receive
		{Port, closed} -&gt;
		    exit(normal)
	    end;
	{'EXIT', Port, Reason} -&gt;
	    io:format("~p ~n", [Reason]),
	    exit(port_terminated)
    end.

encode({foo, X}) -&gt; [1, X];
encode({bar, Y}) -&gt; [2, Y].

decode([Int]) -&gt; Int.
</pre></div>  

  <h3><a name="id62119">6.3 
        C Driver</a></h3>
    
    <p>The C driver is a module that is compiled and linked into a
      shared library. It uses a driver structure, and includes the
      header file <span class="code">erl_driver.h</span>.</p>
    <p>The driver structure is filled with the driver name and function
      pointers. It is returned from the special entry point, declared
      with the macro <span class="code">DRIVER_INIT(&lt;driver_name&gt;)</span>.</p>
    <p>The functions for receiving and sending data, are combined into
      a function, pointed out by the driver structure. The data sent
      into the port is given as arguments, and the data the port
      sends back is sent with the C-function <span class="code">driver_output</span>.</p>
    <p>Since the driver is a shared module, not a program, no main
      function should be present. All function pointers are not used
      in our example, and the corresponding fields in the
      <span class="code">driver_entry</span> structure are set to NULL.</p>
    <p>All functions in the driver, takes a handle (returned from
      <span class="code">start</span>), that is just passed along by the erlang
      process. This must in some way refer to the port driver
      instance.</p>
    <p>The example_drv_start, is the only function that is called with
      a handle to the port instance, so we must save this. It is
      customary to use a allocated driver-defined structure for this
      one, and pass a pointer back as a reference.</p>
    <p>It is not a good idea to use a global variable; since the port
      driver can be spawned by multiple Erlang processes, this
      driver-structure should be instantiated multiple times.
      </p>
<div class="example"><pre>

/* port_driver.c */

#include &lt;stdio.h&gt;
#include "erl_driver.h"

typedef struct {
    ErlDrvPort port;
} example_data;

static ErlDrvData example_drv_start(ErlDrvPort port, char *buff)
{
    example_data* d = (example_data*)driver_alloc(sizeof(example_data));
    d-&gt;port = port;
    return (ErlDrvData)d;
}

static void example_drv_stop(ErlDrvData handle)
{
    driver_free((char*)handle);
}

static void example_drv_output(ErlDrvData handle, char *buff, 
			       ErlDrvSizeT bufflen)
{
    example_data* d = (example_data*)handle;
    char fn = buff[0], arg = buff[1], res;
    if (fn == 1) {
      res = foo(arg);
    } else if (fn == 2) {
      res = bar(arg);
    }
    driver_output(d-&gt;port, &amp;res, 1);
}

ErlDrvEntry example_driver_entry = {
    NULL,			/* F_PTR init, called when driver is loaded */
    example_drv_start,		/* L_PTR start, called when port is opened */
    example_drv_stop,		/* F_PTR stop, called when port is closed */
    example_drv_output,		/* F_PTR output, called when erlang has sent */
    NULL,			/* F_PTR ready_input, called when input descriptor ready */
    NULL,			/* F_PTR ready_output, called when output descriptor ready */
    "example_drv",		/* char *driver_name, the argument to open_port */
    NULL,			/* F_PTR finish, called when unloaded */
    NULL,                       /* void *handle, Reserved by VM */
    NULL,			/* F_PTR control, port_command callback */
    NULL,			/* F_PTR timeout, reserved */
    NULL,			/* F_PTR outputv, reserved */
    NULL,                       /* F_PTR ready_async, only for async drivers */
    NULL,                       /* F_PTR flush, called when port is about 
				   to be closed, but there is data in driver 
				   queue */
    NULL,                       /* F_PTR call, much like control, sync call
				   to driver */
    NULL,                       /* F_PTR event, called when an event selected 
				   by driver_event() occurs. */
    ERL_DRV_EXTENDED_MARKER,    /* int extended marker, Should always be 
				   set to indicate driver versioning */
    ERL_DRV_EXTENDED_MAJOR_VERSION, /* int major_version, should always be 
				       set to this value */
    ERL_DRV_EXTENDED_MINOR_VERSION, /* int minor_version, should always be 
				       set to this value */
    0,                          /* int driver_flags, see documentation */
    NULL,                       /* void *handle2, reserved for VM use */
    NULL,                       /* F_PTR process_exit, called when a 
				   monitored process dies */
    NULL                        /* F_PTR stop_select, called to close an 
				   event object */
};

DRIVER_INIT(example_drv) /* must match name in driver_entry */
{
    return &amp;example_driver_entry;
}

</pre></div>  

  <h3><a name="id63970">6.4 
        Running the Example</a></h3>
    
    <p>1. Compile the C code.</p>
    <div class="example"><pre>
unix&gt; <span class="bold_code">gcc -o exampledrv -fpic -shared complex.c port_driver.c</span>
windows&gt; <span class="bold_code">cl -LD -MD -Fe exampledrv.dll complex.c port_driver.c</span></pre></div>
    <p>2. Start Erlang and compile the Erlang code.</p>
    <div class="example"><pre>
&gt; <span class="bold_code">erl</span>
Erlang (BEAM) emulator version 5.1

Eshell V5.1 (abort with ^G)
1&gt; <span class="bold_code">c(complex5).</span>
{ok,complex5}</pre></div>
    <p>3. Run the example.</p>
    <div class="example"><pre>
2&gt; <span class="bold_code">complex5:start("example_drv").</span>
&lt;0.34.0&gt;
3&gt; <span class="bold_code">complex5:foo(3).</span>
4
4&gt; <span class="bold_code">complex5:bar(5).</span>
10
5&gt; <span class="bold_code">complex5:stop().</span>
stop</pre></div>
  
</div>
<div class="footer">
<hr>
<p>Copyright © 2000-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>