开发者

Is there a cross platform way of handling named pipes in Java or should I write my own?

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 nam开发者_如何转开发ed pipes in Java or should I write one?


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]);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜