Named pipes between Java and C/C++ programs

后端 未结 3 617
北恋
北恋 2021-01-21 17:38

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 a

相关标签:
3条回答
  • 2021-01-21 17:55

    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.

    0 讨论(0)
  • 2021-01-21 18:00

    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)

    0 讨论(0)
  • 2021-01-21 18:14

    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();
    
    0 讨论(0)
提交回复
热议问题