<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns:erl="http://erlang.org" 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> <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"> <div class="erlang-logo-wrapper"><a href="../../../doc/index.html"><img alt="Erlang Logo" src="../../../doc/erlang-logo.png" class="erlang-logo"></a></div> <p class="section-title">Erlang Run-Time System Application (ERTS)</p> <p class="section-subtitle">User's Guide</p> <p class="section-version">Version 10.2.3</p> <ul class="panel-sections"> <li><a href="users_guide.html">User's Guide</a></li> <li><a href="index.html">Reference Manual</a></li> <li><a href="release_notes.html">Release Notes</a></li> <li><a href="../pdf/erts-10.2.3.pdf">PDF</a></li> <li><a href="../../../doc/index.html">Top</a></li> </ul> <ul class="expand-collapse-items"> <li><a href="javascript:openAllFlips()">Expand All</a></li> <li><a href="javascript:closeAllFlips()">Contract All</a></li> </ul> <h3>Chapters</h3> <ul class="flipMenu" imagepath="../../../doc/js/flipmenu"> <li id="no" title="Introduction" expanded="false">Introduction<ul> <li><a href="introduction.html"> Top of chapter </a></li> <li title="Scope"><a href="introduction.html#scope">Scope</a></li> <li title="Prerequisites"><a href="introduction.html#prerequisites">Prerequisites</a></li> </ul> </li> <li id="no" title="Communication in Erlang" expanded="false">Communication in Erlang<ul> <li><a href="communication.html"> Top of chapter </a></li> <li title="Passing of Signals"><a href="communication.html#passing-of-signals">Passing of Signals</a></li> <li title="Synchronous Communication"><a href="communication.html#synchronous-communication">Synchronous Communication</a></li> <li title="Implementation"><a href="communication.html#implementation">Implementation</a></li> </ul> </li> <li id="no" title="Time and Time Correction in Erlang" expanded="false">Time and Time Correction in Erlang<ul> <li><a href="time_correction.html"> Top of chapter </a></li> <li title="New Extended Time Functionality"><a href="time_correction.html#new-extended-time-functionality">New Extended Time Functionality</a></li> <li title="Terminology"><a href="time_correction.html#terminology">Terminology</a></li> <li title="Introduction"><a href="time_correction.html#introduction">Introduction</a></li> <li title="Time Correction"><a href="time_correction.html#time-correction">Time Correction</a></li> <li title="Time Warp Safe Code"><a href="time_correction.html#time-warp-safe-code">Time Warp Safe Code</a></li> <li title="Time Warp Modes"><a href="time_correction.html#time-warp-modes">Time Warp Modes</a></li> <li title="New Time API"><a href="time_correction.html#new-time-api">New Time API</a></li> <li title="Support of Both New and Old OTP Releases"><a href="time_correction.html#support-of-both-new-and-old-otp-releases">Support of Both New and Old OTP Releases</a></li> </ul> </li> <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#grammar">Grammar</a></li> <li title="Function Descriptions"><a href="match_spec.html#function-descriptions">Function Descriptions</a></li> <li title="Match target"><a href="match_spec.html#match-target">Match target</a></li> <li title="Variables and Literals"><a href="match_spec.html#variables-and-literals">Variables and Literals</a></li> <li title="Execution of the Match"><a href="match_spec.html#execution-of-the-match">Execution of the Match</a></li> <li title="Differences between Match Specifications in ETS and Tracing"><a href="match_spec.html#differences-between-match-specifications-in-ets-and-tracing">Differences between Match Specifications in ETS and Tracing</a></li> <li title="Tracing Examples"><a href="match_spec.html#tracing-examples">Tracing Examples</a></li> <li title="ETS Examples"><a href="match_spec.html#ets-examples">ETS 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#general-information">General Information</a></li> <li title="Scheduler Information"><a href="crash_dump.html#scheduler-information">Scheduler Information</a></li> <li title="Memory Information"><a href="crash_dump.html#memory-information">Memory Information</a></li> <li title="Internal Table Information"><a href="crash_dump.html#internal-table-information">Internal Table Information</a></li> <li title="Allocated Areas"><a href="crash_dump.html#allocated-areas">Allocated Areas</a></li> <li title="Allocator"><a href="crash_dump.html#allocator">Allocator</a></li> <li title="Process Information"><a href="crash_dump.html#process-information">Process Information</a></li> <li title="Port Information"><a href="crash_dump.html#port-information">Port Information</a></li> <li title="ETS Tables"><a href="crash_dump.html#ets-tables">ETS Tables</a></li> <li title="Timers"><a href="crash_dump.html#timers">Timers</a></li> <li title="Distribution Information"><a href="crash_dump.html#distribution-information">Distribution Information</a></li> <li title="Loaded Module Information"><a href="crash_dump.html#loaded-module-information">Loaded Module Information</a></li> <li title="Fun Information"><a href="crash_dump.html#fun-information">Fun Information</a></li> <li title="Process Data"><a href="crash_dump.html#process-data">Process Data</a></li> <li title="Atoms"><a href="crash_dump.html#atoms">Atoms</a></li> <li title="Disclaimer"><a href="crash_dump.html#disclaimer">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#introduction">Introduction</a></li> <li title="Distribution Module"><a href="alt_dist.html#distribution-module">Distribution Module</a></li> <li title="The Driver"><a href="alt_dist.html#the-driver">The Driver</a></li> <li title="Putting It All Together"><a href="alt_dist.html#putting-it-all-together">Putting It All Together</a></li> </ul> </li> <li id="no" title="How to Implement an Alternative Service Discovery for Erlang Distribution " expanded="false">How to Implement an Alternative Service Discovery for Erlang Distribution <ul> <li><a href="alt_disco.html"> Top of chapter </a></li> <li title="Introduction"><a href="alt_disco.html#introduction">Introduction</a></li> <li title="Discovery module"><a href="alt_disco.html#discovery-module">Discovery module</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#module-declarations-and-forms">Module Declarations and Forms</a></li> <li title="Atomic Literals"><a href="absform.html#atomic-literals">Atomic Literals</a></li> <li title="Patterns"><a href="absform.html#patterns">Patterns</a></li> <li title="Expressions"><a href="absform.html#expressions">Expressions</a></li> <li title="Clauses"><a href="absform.html#clauses">Clauses</a></li> <li title="Guards"><a href="absform.html#guards">Guards</a></li> <li title="Types"><a href="absform.html#types">Types</a></li> <li title="The Abstract Format after Preprocessing"><a href="absform.html#the-abstract-format-after-preprocessing">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#normal-mode">Normal Mode</a></li> <li title="Shell Break Mode"><a href="tty.html#shell-break-mode">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#introduction">Introduction</a></li> <li title="Sample Driver"><a href="driver.html#sample-driver">Sample Driver</a></li> <li title="Compiling and Linking the Sample Driver"><a href="driver.html#compiling-and-linking-the-sample-driver">Compiling and Linking the Sample Driver</a></li> <li title="Calling a Driver as a Port in Erlang"><a href="driver.html#calling-a-driver-as-a-port-in-erlang">Calling a Driver as a Port in Erlang</a></li> <li title="Sample Asynchronous Driver"><a href="driver.html#sample-asynchronous-driver">Sample Asynchronous Driver</a></li> <li title="An Asynchronous Driver Using driver_async"><a href="driver.html#an-asynchronous-driver-using-driver_async">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#introduction">Introduction</a></li> <li title="Configuration Data"><a href="inet_cfg.html#configuration-data">Configuration Data</a></li> <li title="User Configuration Example"><a href="inet_cfg.html#user-configuration-example">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#introduction">Introduction</a></li> <li title="Distribution Header"><a href="erl_ext_dist.html#distribution-header">Distribution Header</a></li> <li title="ATOM_CACHE_REF"><a href="erl_ext_dist.html#atom_cache_ref">ATOM_CACHE_REF</a></li> <li title="SMALL_INTEGER_EXT"><a href="erl_ext_dist.html#small_integer_ext">SMALL_INTEGER_EXT</a></li> <li title="INTEGER_EXT"><a href="erl_ext_dist.html#integer_ext">INTEGER_EXT</a></li> <li title="FLOAT_EXT"><a href="erl_ext_dist.html#float_ext">FLOAT_EXT</a></li> <li title="REFERENCE_EXT"><a href="erl_ext_dist.html#reference_ext">REFERENCE_EXT</a></li> <li title="PORT_EXT"><a href="erl_ext_dist.html#port_ext">PORT_EXT</a></li> <li title="PID_EXT"><a href="erl_ext_dist.html#pid_ext">PID_EXT</a></li> <li title="SMALL_TUPLE_EXT"><a href="erl_ext_dist.html#small_tuple_ext">SMALL_TUPLE_EXT</a></li> <li title="LARGE_TUPLE_EXT"><a href="erl_ext_dist.html#large_tuple_ext">LARGE_TUPLE_EXT</a></li> <li title="MAP_EXT"><a href="erl_ext_dist.html#map_ext">MAP_EXT</a></li> <li title="NIL_EXT"><a href="erl_ext_dist.html#nil_ext">NIL_EXT</a></li> <li title="STRING_EXT"><a href="erl_ext_dist.html#string_ext">STRING_EXT</a></li> <li title="LIST_EXT"><a href="erl_ext_dist.html#list_ext">LIST_EXT</a></li> <li title="BINARY_EXT"><a href="erl_ext_dist.html#binary_ext">BINARY_EXT</a></li> <li title="SMALL_BIG_EXT"><a href="erl_ext_dist.html#small_big_ext">SMALL_BIG_EXT</a></li> <li title="LARGE_BIG_EXT"><a href="erl_ext_dist.html#large_big_ext">LARGE_BIG_EXT</a></li> <li title="NEW_REFERENCE_EXT"><a href="erl_ext_dist.html#new_reference_ext">NEW_REFERENCE_EXT</a></li> <li title="FUN_EXT"><a href="erl_ext_dist.html#fun_ext">FUN_EXT</a></li> <li title="NEW_FUN_EXT"><a href="erl_ext_dist.html#new_fun_ext">NEW_FUN_EXT</a></li> <li title="EXPORT_EXT"><a href="erl_ext_dist.html#export_ext">EXPORT_EXT</a></li> <li title="BIT_BINARY_EXT"><a href="erl_ext_dist.html#bit_binary_ext">BIT_BINARY_EXT</a></li> <li title="NEW_FLOAT_EXT"><a href="erl_ext_dist.html#new_float_ext">NEW_FLOAT_EXT</a></li> <li title="ATOM_UTF8_EXT"><a href="erl_ext_dist.html#atom_utf8_ext">ATOM_UTF8_EXT</a></li> <li title="SMALL_ATOM_UTF8_EXT"><a href="erl_ext_dist.html#small_atom_utf8_ext">SMALL_ATOM_UTF8_EXT</a></li> <li title="ATOM_EXT (deprecated)"><a href="erl_ext_dist.html#atom_ext--deprecated-">ATOM_EXT (deprecated)</a></li> <li title="SMALL_ATOM_EXT (deprecated)"><a href="erl_ext_dist.html#small_atom_ext--deprecated-">SMALL_ATOM_EXT (deprecated)</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#epmd-protocol">EPMD Protocol</a></li> <li title="Distribution Handshake"><a href="erl_dist_protocol.html#distribution-handshake">Distribution Handshake</a></li> <li title="Protocol between Connected Nodes"><a href="erl_dist_protocol.html#protocol-between-connected-nodes">Protocol between Connected Nodes</a></li> <li title="New Ctrlmessages for distrvsn = 1 (Erlang/OTP R4)"><a href="erl_dist_protocol.html#new-ctrlmessages-for-distrvsn-=-1--erlang-otp-r4-">New Ctrlmessages for distrvsn = 1 (Erlang/OTP R4)</a></li> <li title="New Ctrlmessages for distrvsn = 2"><a href="erl_dist_protocol.html#new-ctrlmessages-for-distrvsn-=-2">New Ctrlmessages for distrvsn = 2</a></li> <li title="New Ctrlmessages for distrvsn = 3 (Erlang/OTP R5C)"><a href="erl_dist_protocol.html#new-ctrlmessages-for-distrvsn-=-3--erlang-otp-r5c-">New Ctrlmessages for distrvsn = 3 (Erlang/OTP R5C)</a></li> <li title="New Ctrlmessages for distrvsn = 4 (Erlang/OTP R6)"><a href="erl_dist_protocol.html#new-ctrlmessages-for-distrvsn-=-4--erlang-otp-r6-">New Ctrlmessages for distrvsn = 4 (Erlang/OTP R6)</a></li> <li title="New Ctrlmessages for Erlang/OTP 21"><a href="erl_dist_protocol.html#new-ctrlmessages-for-erlang-otp-21">New Ctrlmessages for Erlang/OTP 21</a></li> </ul> </li> </ul> </div></div> <div id="content"> <div class="innertube"> <h1>10 How to Implement a Driver</h1> <div class="note"> <div class="label">Note</div> <div class="content"><p> <p>This section was written a long time ago. Most of it is still valid, as it explains important concepts, but this was written for an older driver interface so the examples do not work anymore. The reader is encouraged to read the <span class="bold_code bc-19"><a href="erl_driver.html"><span class="code">erl_driver</span></a></span> and <span class="bold_code bc-19"><a href="driver_entry.html"><span class="code">driver_entry</span></a></span> documentation also.</p> </p></div> </div> <h3><span onMouseOver="document.getElementById('ghlink-introduction-idm281472685304840').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-introduction-idm281472685304840').style.visibility = 'hidden';"><span id="ghlink-introduction-idm281472685304840" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/erts/doc/src/driver.xml#L42" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="introduction" href="#introduction">10.1 Introduction</a></span></h3> <p>This section describes how to build your own driver for Erlang.</p> <p>A driver in Erlang is a library written in C, which is linked to the Erlang emulator and called from Erlang. Drivers can be used when C is more suitable than Erlang, to speed up things, 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 section.</p> <div class="warning"> <div class="label">Warning</div> <div class="content"><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 brings the whole emulator down. In short, be careful.</p> </p></div> </div> <h3><span onMouseOver="document.getElementById('ghlink-sample-driver-idm281472685300536').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-sample-driver-idm281472685300536').style.visibility = 'hidden';"><span id="ghlink-sample-driver-idm281472685300536" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/erts/doc/src/driver.xml#L66" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="sample-driver" href="#sample-driver">10.2 Sample Driver</a></span></h3> <p>This section describes a simple driver for accessing a postgres database using the libpq C client library. Postgres is used because it is free and open source. For information on postgres, see <span class="bold_code bc-20"><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, but not good, as it halts the emulator while waiting for the database. This is improved below with an asynchronous sample driver.</p> <p>The code is straightforward: 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>, which 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 is passed every time the emulator calls us. First we store the driver handle, as it is needed in later 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 flag <span class="code">PORT_CONTROL_FLAG_BINARY</span>, calling <span class="code">set_port_control_flags</span>. (This is because we do not know if our data will fit in the result buffer of <span class="code">control</span>, which has a default size, 64 bytes, set up by the emulator.)</p> <p>An entry <span class="code">init</span> is called when the driver is loaded. However, we do not use this, as 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 log in 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 this example, only <span class="code">start</span>, <span class="code">stop</span>, and <span class="code">control</span> are provided:</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>The control codes that we have defined are as follows:</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 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 &pq_driver_entry; }</pre></div> <p>Here some initialization is done, <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->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 parameter 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, as 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, allocates a binary, and copies the data there. This binary is returned in <span class="code">*rbuf</span>. (Notice 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); /* As 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(&x); switch (command) { case DRV_CONNECT: r = do_connect(s, data, &x); break; case DRV_DISCONNECT: r = do_disconnect(data, &x); break; case DRV_SELECT: r = do_select(s, data, &x); break; default: r = -1; break; } *rbuf = (char*)ei_x_to_new_binary(&x); ei_x_free(&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 the driver data, and return <span class="code">'ok'</span>. 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->conn = conn; return 0; }</pre></div> <p>If we are connected (and 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 <span class="code">'ok'</span>, as we can get here from function <span class="code">stop</span>, which does not return data to the emulator:</p> <div class="example"><pre>static int do_disconnect(our_data_t* data, ei_x_buff* x) { if (data->conn == NULL) return 0; PQfinish(data->conn); data->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->conn, s); encode_result(x, res, data->conn); PQclear(res); return 0; }</pre></div> <p>Here we check the result from postgres. If it is data, we encode it as lists of lists with column data. Everything from postgres is C strings, so we 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 < n_cols; ++col) { ei_x_encode_string(x, PQfname(res, col)); } ei_x_encode_empty_list(x); for (row = 0; row < n_rows; ++row) { ei_x_encode_list_header(x, n_cols); for (col = 0; col < 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><span onMouseOver="document.getElementById('ghlink-compiling-and-linking-the-sample-driver-idm281472685253384').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-compiling-and-linking-the-sample-driver-idm281472685253384').style.visibility = 'hidden';"><span id="ghlink-compiling-and-linking-the-sample-driver-idm281472685253384" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/erts/doc/src/driver.xml#L376" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="compiling-and-linking-the-sample-driver" href="#compiling-and-linking-the-sample-driver">10.3 Compiling and Linking the Sample Driver</a></span></h3> <p>The driver is to be compiled and linked to a shared library (DLL on Windows). With gcc, this is done with link flags <span class="code">-shared</span> and <span class="code">-fpic</span>. As 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><span onMouseOver="document.getElementById('ghlink-calling-a-driver-as-a-port-in-erlang-idm281472685248680').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-calling-a-driver-as-a-port-in-erlang-idm281472685248680').style.visibility = 'hidden';"><span id="ghlink-calling-a-driver-as-a-port-in-erlang-idm281472685248680" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/erts/doc/src/driver.xml#L389" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="calling-a-driver-as-a-port-in-erlang" href="#calling-a-driver-as-a-port-in-erlang">10.4 Calling a Driver as a Port in Erlang</a></span></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 successfull, 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 do not 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) -> case erl_ddll:load_driver(".", "pg_sync") of ok -> ok; {error, already_loaded} -> ok; E -> exit({error, E}) end, Port = open_port({spawn, ?MODULE}, []), case binary_to_term(port_control(Port, ?DRV_CONNECT, ConnectStr)) of ok -> {ok, Port}; Error -> Error end. disconnect(Port) -> R = binary_to_term(port_control(Port, ?DRV_DISCONNECT, "")), port_close(Port), R. select(Port, Query) -> binary_to_term(port_control(Port, ?DRV_SELECT, Query)).</pre></div> <p>The API is simple:</p> <ul> <li> <p><span class="code">connect/1</span> loads the driver, opens it, and logs on to the database, returning the Erlang port if successful.</p> </li> <li> <p><span class="code">select/2</span> sends a query to the driver and returns the result.</p> </li> <li> <p><span class="code">disconnect/1</span> closes the database connection and the driver. (However, it does not unload it.)</p> </li> </ul> <p>The connection string is to be a connection string for postgres.</p> <p>The driver is loaded with <span class="code">erl_ddll:load_driver/2</span>. If this is successful, or if it is 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><span onMouseOver="document.getElementById('ghlink-sample-asynchronous-driver-idm281472685232904').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-sample-asynchronous-driver-idm281472685232904').style.visibility = 'hidden';"><span id="ghlink-sample-asynchronous-driver-idm281472685232904" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/erts/doc/src/driver.xml#L471" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="sample-asynchronous-driver" href="#sample-asynchronous-driver">10.5 Sample Asynchronous Driver</a></span></h3> <p>Sometimes database queries can take a 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, as no other Erlang process gets a chance to do anything. To improve on our postgres driver, we re-implement 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>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 is 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 signaled, indicating there is data to read, the <span class="code">ready_input</span> entry is called. More about 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, as the entry <span class="code">ready_io</span> is 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(&x); encode_error(&x, conn); PQfinish(conn); conn = NULL; driver_output(data->port, x.buff, x.index); ei_x_free(&x); } PQconnectPoll(conn); int socket = PQsocket(conn); data->socket = socket; driver_select(data->port, (ErlDrvEvent)socket, DO_READ, 1); driver_select(data->port, (ErlDrvEvent)socket, DO_WRITE, 1); data->conn = conn; data->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 is called.</p> <p>Notice 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 is called.</p> <div class="example"><pre>static int do_select(const char* s, our_data_t* data) { data->connecting = 0; PGconn* conn = data->conn; /* if there's an error return it now */ if (PQsendQuery(conn, s) == 0) { ei_x_buff x; ei_x_new_with_version(&x); encode_error(&x, conn); driver_output(data->port, x.buff, x.index); ei_x_free(&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 result is 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->conn; ei_x_buff x; ei_x_new_with_version(&x); if (data->connecting) { ConnStatusType status; PQconnectPoll(conn); status = PQstatus(conn); if (status == CONNECTION_OK) encode_ok(&x); else if (status == CONNECTION_BAD) encode_error(&x, conn); } else { PQconsumeInput(conn); if (PQisBusy(conn)) return; res = PQgetResult(conn); encode_result(&x, res, conn); PQclear(res); for (;;) { res = PQgetResult(conn); if (res == NULL) break; PQclear(res); } } if (x.index > 1) { driver_output(data->port, x.buff, x.index); if (data->connecting) driver_select(data->port, (ErlDrvEvent)data->socket, DO_WRITE, 0); } ei_x_free(&x); }</pre></div> <p>The <span class="code">ready_io</span> function is 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 is not. If the connection is not yet established, we simply return; <span class="code">ready_io</span> is 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 are not connecting, we wait 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>Error handling is to be added here, for example, checking that the socket is still open, but this is only 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) -> case erl_ddll:load_driver(".", "pg_async") of ok -> ok; {error, already_loaded} -> ok; _ -> 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 -> {ok, Port}; Error -> Error end. disconnect(Port) -> port_control(Port, ?DRV_DISCONNECT, ""), R = return_port_data(Port), port_close(Port), R. select(Port, Query) -> port_control(Port, ?DRV_SELECT, Query), return_port_data(Port). return_port_data(Port) -> receive {Port, {data, Data}} -> binary_to_term(Data) end.</pre></div> <p>The Erlang code is slightly different, as we do not 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. As the data is in binary format, we use <span class="code">binary_to_term/1</span> to convert it to an Erlang term. Notice that the driver is opened in binary mode (<span class="code">open_port/2</span> is called with option <span class="code">[binary]</span>). This means that data sent from the driver to the emulator is sent as binaries. Without option <span class="code">binary</span>, they would have been lists of integers.</p> <h3><span onMouseOver="document.getElementById('ghlink-an-asynchronous-driver-using-driver_async-idm281472685202280').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-an-asynchronous-driver-using-driver_async-idm281472685202280').style.visibility = 'hidden';"><span id="ghlink-an-asynchronous-driver-using-driver_async-idm281472685202280" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/erts/doc/src/driver.xml#L714" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="an-asynchronous-driver-using-driver_async" href="#an-asynchronous-driver-using-driver_async">10.6 An Asynchronous Driver Using driver_async</a></span></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 use the <span class="code">next_permutation</span> algorithm to get the next permutation of a list of integers. For large lists (> 100,000 elements), this takes some time, so we perform this as an asynchronous task.</p> <p>The asynchronous API for drivers is complicated. First, the work must be prepared. In the example, this is done in <span class="code">output</span>. We could have used <span class="code">control</span>, but we want some variation in the examples. In our driver, we allocate a structure that contains anything that is 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. Notice that the driver functions are not re-entrant, so they are not to 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 cannot return the result from within the asynchronous function, as we cannot call the driver functions.)</p> <p>The following code is from the sample file <span class="code">next_perm.cc</span>. The driver entry looks like before, but also contains the callback <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. As we use C++, we use a struct, and stuff the data in it. We must 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 is called later, and from another thread. We return no data here, instead it is sent later from the <span class="code">ready_async</span> callback.</p> <p>The <span class="code">async_data</span> is 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 is only used if the task is cancelled programmatically.</p> <div class="example"><pre>struct our_async_data { bool prev; vector<int> 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 < 1 || *buf > 2) return; ErlDrvPort port = reinterpret_cast<ErlDrvPort>(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 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<our_async_data*>(async_data); if (d->prev) prev_permutation(d->data.begin(), d->data.end()); else next_permutation(d->data.begin(), d->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 the simple example this works well, and we do not 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<ErlDrvPort>(drv_data); our_async_data* d = reinterpret_cast<our_async_data*>(async_data); int n = d->data.size(), result_n = n*2 + 3; ErlDrvTermData *result = new ErlDrvTermData[result_n], *rp = result; for (vector<int>::iterator i = d->data.begin(); i != d->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, as we use <span class="code">driver_output_term</span>, there is no need to call <span class="code">binary_to_term</span>. 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() -> case whereis(next_perm) of undefined -> case erl_ddll:load_driver(".", "next_perm") of ok -> ok; {error, already_loaded} -> ok; E -> exit(E) end, Port = open_port({spawn, "next_perm"}, []), register(next_perm, Port); _ -> ok end. list_to_integer_binaries(L) -> [<<I:32/integer-native>> || I <- L]. next_perm(L) -> next_perm(L, 1). prev_perm(L) -> next_perm(L, 2). next_perm(L, Nxt) -> load(), B = list_to_integer_binaries(L), port_control(next_perm, Nxt, B), receive Result -> Result end. all_perm(L) -> New = prev_perm(L), all_perm(New, L, [New]). all_perm(L, L, Acc) -> Acc; all_perm(L, Orig, Acc) -> New = prev_perm(L), all_perm(New, Orig, [New | Acc]).</pre></div> </div> <div class="footer"> <hr> <p>Copyright © 1997-2019 Ericsson AB. All Rights Reserved.</p> </div> </div> </div> <script type="text/javascript">window.__otpTopDocDir = '../../../doc/js/';</script><script type="text/javascript" src="../../../doc/js/highlight.js"></script> </body> </html>