Ports and external programs

A port is the Erlang side of an operating system process. The runtime starts the program, and from then on the process talks to it with messages: bytes written with port_command/2 arrive on its standard input, and what it writes on standard output arrives as a message. That is how a program written in another language joins an Erlang system without a socket and without a shared library. The two shapes are os:cmd/1, for a command that runs once and prints, and open_port/2, for a conversation.

os:cmd

os:cmd/1 runs a shell command, waits for it to exit and answers everything it wrote on standard output as a string. It is the shortest way to call a tool that has no state and no reply protocol, and it has two limits worth knowing before it is used in a server: it blocks the calling process for the whole run, and it throws the exit status away:

cmd.erl

-module(cmd). -export([main/0]). main() -> io:format("echo: ~p~n", [os:cmd("echo hello")]), io:format("two lines: ~p~n", [os:cmd("printf 'one\ntwo\n'")]), io:format("no status: ~p~n", [os:cmd("printf 'partial'; exit 3")]).

erlc cmd.erl

erl -noshell -eval 'cmd:main(), halt().'

echo: "hello\n" two lines: "one\ntwo\n" no status: "partial"

The third line is the limit: the command exited with status three, and the answer is only the text it managed to write. A program that must know whether the tool worked reads the status from a port instead, or runs a command whose output says so.

A port

open_port({spawn, Command}, Options) starts a program through the shell and answers a port, which is a value like a pid. The owner sends bytes with port_command/2 and receives what the program writes as {Port, {data, Bytes}}. The program below starts tr, sends one line, and reads the answer until the newline:

port_echo.erl

-module(port_echo). -export([main/0]). main() -> Port = open_port({spawn, "tr a-z A-Z"}, [binary]), true = port_command(Port, <<"ping\n">>), Reply = read_until_newline(Port, <<>>), io:format("reply: ~p~n", [Reply]), true = port_close(Port), io:format("info after close: ~p~n", [erlang:port_info(Port)]). read_until_newline(Port, Acc) -> receive {Port, {data, Bytes}} -> case binary:split(Bytes, <<"\n">>) of [Line, _Rest] -> <<Acc/binary, Line/binary>>; [_] -> read_until_newline(Port, <<Acc/binary, Bytes/binary>>) end after 1000 -> timeout end.

erlc port_echo.erl

erl -noshell -eval 'port_echo:main(), halt().'

reply: <<"PING">> info after close: undefined

The read collects data until the newline arrives, because a port delivers the bytes in whatever pieces the operating system hands over: one message per write is a habit of small programs, not a promise. After port_close/1 the port is gone, and port_info/1 answers undefined, the same way whereis/1 does for a name.

Arguments and the exit status

{spawn, Command} hands the line to a shell, which is convenient and is also a quoting problem waiting to happen. {spawn_executable, Path} starts the file directly: each argument is one string in the args option, no shell reads them, and no quote has to survive a second parser. The exit_status option asks for the status of the program as one more message:

port_args.erl

-module(port_args). -export([main/0]). main() -> Port = open_port({spawn_executable, "/bin/echo"}, [{args, ["one", "two"]}, exit_status, binary]), Data = receive {Port, {data, Bytes}} -> Bytes after 1000 -> timeout end, Status = receive {Port, {exit_status, Code}} -> Code after 1000 -> timeout end, io:format("data: ~p~n", [Data]), io:format("status: ~p~n", [Status]).

erlc port_args.erl

erl -noshell -eval 'port_args:main(), halt().'

data: <<"one two\n">> status: 0

Two messages, in the order the program produced them: its output, then the status the operating system reported when it exited. A port whose program exits by itself sends {Port, {exit_status, N}} and then a {Port, closed}, and the process that owns it must handle both, or the port leaks and the message sits in the mailbox.

What a port costs

A port is cheap compared with a thread and expensive compared with a function call: the runtime starts a real program, and the bytes cross a pipe. A port that is used for every small request turns a millisecond into ten, and a port that is never closed leaves a program running after its owner is gone. The rules are the ones a socket follows: open it once, keep it in the state of a gen_server, close it in terminate/2, and give every read a timeout.

The two directions have flow control of their own. A program that writes faster than the Erlang side reads fills the port buffer, and the runtime stops reading until the owner catches up, which is why a busy port belongs in its own process and not in a callback that also answers calls. The TCP server in depth lesson applies the same rule to a socket whose client floods it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a port in Erlang?

    Answer

    A value that talks to an operating system process

    The runtime starts the program and the port carries the bytes in both directions.

  2. What does os:cmd/1 answer?

    Answer

    The standard output as a string

    It waits for the command and hands back what it wrote on standard output.

  3. How does a program write to a port?

    Answer

    port_command/2

    port_command sends bytes to the standard input of the program behind the port.

  4. What is the difference between {spawn, Command} and {spawn_executable, Path}?

    Answer

    The first goes through a shell, the second does not

    The shell parses the line, so quoting becomes part of the problem; the executable form takes each argument as one string.

  5. Which option asks for the status of the program?

    Answer

    exit_status

    It adds a {Port, {exit_status, Code}} message when the program exits.

  6. What does a closed port answer to erlang:port_info/1?

    Answer

    undefined

    The port is gone, so the call has nothing to describe.

  7. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [os:cmd("echo hi")]).

    Answer

    "hi\n"

    The command writes one line, and the answer is the string with its newline.

  8. What does this module print? -module(q2). -export([main/0]). main() -> Port = open_port({spawn_executable, "/bin/echo"}, [{args, ["a", "b"]}, exit_status, binary]), Data = receive {Port, {data, Bytes}} -> Bytes after 1000 -> timeout end, Status = receive {Port, {exit_status, Code}} -> Code after 1000 -> timeout end, io:format("~p~n", [{Data, Status}]).

    Answer

    {<<"a b\n">>,0}

    The two arguments arrive as one line, and the program exits with status zero.

  9. What does this module print? -module(q3). -export([main/0]). main() -> Port = open_port({spawn, "tr a-z A-Z"}, [binary]), true = port_command(Port, <<"abc\n">>), R = receive {Port, {data, Bytes}} -> Bytes after 1000 -> timeout end, true = port_close(Port), io:format("~p~n", [R]).

    Answer

    <<"ABC\n">>

    tr uppercases what it reads, and without a newline it writes the three bytes back at once.

  10. What does this module print? -module(q4). -export([main/0]). main() -> Port = open_port({spawn_executable, "/bin/true"}, [exit_status, binary]), R = receive {Port, {exit_status, Code}} -> Code after 1000 -> timeout end, io:format("~p~n", [R]).

    Answer

    0

    The program exits at once with status zero, and the option delivers it as a message.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev