Cover by Francesco Cesarini, Simon Thompson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Port Programs

An Erlang port allows communication between an Erlang node and an external program through binary messages sent to and from an Erlang process running in the node—known as the connected process of the port—and the external program, running in a separate operating system thread (see Figure 16-1). The wxErlang binding to wxWidgets, described in Chapter 14, uses ports.

One of the simplest applications of a port is the os:cmd/1 function, which can call an operating system command from inside the Erlang shell:

1> os:cmd("date").
"Sat 21 Mar 2009 18:11:24 GMT\n"
An Erlang port, its connected process, and an external program

Figure 16-1. An Erlang port, its connected process, and an external program

The port is made to behave like an Erlang process that is not trapping exits. Connected processes can link to it, as well as send and receive Erlang messages and exit signals. The mechanism underlying the binary communication depends on the operating system: for instance, on Unix-based systems, communication will be through pipes. On the Erlang side, the template for a port-based interaction is given by the following:

Port = open_port({spawn, Cmd}, ...),
 ...
port_command(Port, Payload),
 ...
receive
  {Port, {data, Data}} ->
 ...

In this fragment, the port is opened by the call to open_port/2, returning the port identifier, Port. Data is sent to the Port (and on to the external program) through the call to port_command(Port,...) in the connected process, ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required