Using Ports to Communicate With External Programs

// December 10th, 2009 // Uncategorized

A rather nice fellow on the Erlang Questions list has been having some trouble with communicating with an external Java program.  Now, I’m not sure what he’s trying to do, exactly, but I thought that a good example is in order.

I wrote two programs to help with this.  One of them is an Erlang program (and escript, actually) that runs the second program.  The second program is supposed to, in his case, be the Java code he wants to chat with.  In my case, it’s a shell script that reads two lines, then prints out various things (including the data it was given, a random number, and the command line).  For added measure, it exits with an exit status of 42.

Thus, this example shows how to do the following core activities:

  • open an external program with port_open/2
  • write to an external program with port_control/2
  • read from that external program by receiving messages
  • use line-mode framing to receive whole lines of data

In addition, I’ve spiced it up a bit with some other useful tidbits:

  • collect a return status from the process
  • searching the path for your program
  • using spawn_executable to have strong control over your arguments
  • specifying an arg0 for those commands that need it (busybox, I’m looking at you)

Hopefully this is a help to all of the people who have been struggling with it.  Here’s a link to the code.

There are two final things that you should know.  First, if you need to move lots of data, using {packet,N} and binary are probably the way to go.  Second, if the program you’re running wants STDIN to close, there doesn’t seem to be any way to do this using a port.

Comments are closed.