1. knarf
  2. emacs-ipc-example

Overview

What is this?

It's a very simple example of interprocess communication in GNU Emacs using TCP sockets.

The process

  • the process (a perl script) starts a server on a random available port.
  • writes the port to a temporary file
  • waits for connections
  • waits for input (whole line)
  • sends back length of the input

Emacs

  • given the process id, reads the port number
  • connects to the process server
  • sends a string
  • waits for result which are inserted in the process buffer
  • reads and returns the first Lisp atom of the buffer, which happens to be an integer.

Notes

It might be less portable but there is a way to know which port a process is listening to on Linux using netstat. For example, with a process id of 2327:

$ netstat -naop | perl -nE 'say $1 if /:(\d+).+LISTEN\s+2327\D/'
35904

Usage

  • run the process in a terminal

    $ ./prog.pl
    PID 2302 listening on port 51776
    
  • evaluate the Emacs Lisp function

  • run prog-length

    (prog-length 2302 "foo")
    => 3
    

If you switch back to your terminal you should see something like:

connection from 127.0.0.1
received foo