3

What is the reliable way of implementing bidirectional communication to a Linux process?

I see that popen does not seem to support "r" and "w" access at the same time... or at least that's what is implied:

The type argument is a pointer to a null-terminated string which must be either 'r' for reading or 'w' for writing.

(I am so missing Erlang at the moment)

2 Answers 2

8

Unix domain sockets are your friend.

A Unix domain socket or IPC socket (inter-process communication socket) is a data communications endpoint that is similar to an Internet socket, but does not use a network protocol for communication. It is used in POSIX operating systems for inter-process communication.

You reserve a name for your communications channel, such as /myapp/ipc, and then both processes open that address using a UNIX socket:

struct sockaddr_un local;
int len;

s = socket(AF_UNIX, SOCK_STREAM, 0);
local.sun_family = AF_UNIX;
strcpy(local.sun_path, "/myapp/ipc");
len = strlen(local.sun_path) + sizeof(local.sun_family);
bind(s, (struct sockaddr *)&local, len);

Now you can use listen or connect or whatever else in the socket family. It's a little bit of work, but is the best way to achieve IPC on Linux.

Since Erlang is just a nice language for specifying little servers (processes) that communicate over named pipes (processes), this model should feel comfortable to you.

2
  • ... so I would spawn a process and pass a reference to an opened & listening socket in the arguments?
    – jldupont
    Commented Nov 5, 2009 at 19:21
  • 2
    Or use a named socket (see mkfifo). For bidirectional communication, you just need two of them...
    – Wim
    Commented Nov 5, 2009 at 19:25
2

Good old TCP/IP connections have always worked well for me.

2
  • 3
    Unix domain sockets are much more efficient than TCP. Commented Nov 5, 2009 at 19:32
  • 1
    But TCP has the benefit of allowing your system to scale to more than 1 box. Fortunately, porting code from unix domain sockets to TCP is trivial. Commented Nov 5, 2009 at 19:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.