views:

227

answers:

2

I'm writing a bit of JNI code where a DLL running in the process space of various processes on the system needs to talk back to a java process. I've decided to use named pipes to do this (for various reasons) after weighing up shared mem/sockets/rpc etc. My question is, is there a nice way of handling named pipes in Java or should I write one?

A: 

I used to do process communication via the Process's input and output stream: For e.g.

Process p = Runtime.getRuntime().exec("myproc");
OutputStream is = p.getOutputStream();
BufferedOutputStream bis = new BufferedOutputStream(is);
bis.write("your_command");

Similarly you can use inputstreams to read what the other process has to say to you.

Suraj Chandran
+1  A: 

Assuming that you're running on Unix, can't you just create the pipe with exec and then read and write with a File*Stream?

@Test public void pipe() throws IOException, InterruptedException {
    Runtime.getRuntime().exec("mkfifo mypipe");

    final String[] read = new String[1];
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                BufferedReader r = new BufferedReader(new FileReader("mypipe"));
                read[0] = r.readLine();
            } catch (IOException e) {
            }
        }
    };
    t.start();

    FileWriter w = new FileWriter("mypipe");
    w.write("hello\n");
    w.flush();
    t.join();

    assertEquals("hello", read[0]);
}
Duncan McGregor
I'm currently doing it for win32 although I plan to extend this to linux shortly after since I support both. This may well be what I end up doing but I was hoping to find a generic API which worked symmetrically across all platforms. If there isn't one I'll probably just write one which does something very similar to the above.
Benj
For access to the win32 API be sure to check out jna
Duncan McGregor