Named pipes between Java and C/C++ programs

2019-02-26 06:00发布

I think of using in windows a named pipe to communicate between two apps written in Java and C. Normally i use socket connection to do this, but now i have to cancel this idea and find a new solution.

I read that named pipe in java can be visible only inside JVM-is this true? Is there a way to establish named pipe between two apps wriiten in different language?

If not, what kind of technology do You advice?

3条回答
乱世女痞
2楼-- · 2019-02-26 07:02

You can simply start an external process in Java and connect to it's pipes.

    // Execute command
    String command = "ls";
    Process child = Runtime.getRuntime().exec(command);

    // Get pipes from process
    InputStream in = child.getInputStream();
    OutputStream out = child.getOutputStream();
    InputStream error = child.getErrorStream();
查看更多
forever°为你锁心
3楼-- · 2019-02-26 07:06

In order to create a Windows named pipe in Java, you'd have to resort to using JNI to call the native WINAPI functions.

You can create the named pipe in C++, though, and consume it in Java by opening it as a file in the pipe namespace after it has been created.

查看更多
在下西门庆
4楼-- · 2019-02-26 07:07

Named pipes are much harder to get right than using sockets. Conceptually they are simpler. However making them reliable and reasonably fault tolerant is much harder than for sockets.

I would suggest you reconsider sockets, this is designed for communication between processes. Can you clarify why you cannot use sockets? The reason I ask is that named pipes actually used sockets over loopback in reality.

A named pipe is an OS construct. You can create the named pipe in your OS and then it can be accessed as if it were a file by Java and C, or any other program. Communication between processes via file is very difficult to get right (if not impossible) For example, you will have no idea that when you write to the named pipe, that anything is reading it unless you design your own flow control protocol. (Very difficult to test in all cases)

You may have heard of PipedInputStream and PipedOutputStream and these classes can only be used in the same process (making them pretty useless)

EDIT: If you want an independant view of the most common and possibly the most sensible way to send data I suggest you try google.

java sockets - 2,210,000 hits
java named pipes - 90,000 hits

So perhaps sockets is 25x more sensible than named pipes. (and more supportable as there more tutorials and people who have experience with them)

查看更多
登录 后发表回答