On our Linux system we use named pipes for interprocess communication (a producer and a consumer).
In order to test the consumer (Java) code, I would like to implement (in Java) a dummy producer which writes to a named pipe which is connected to the consumer.
Now the test should also work in the Windows development environment. Thus I would like to know how to create a named pipe in Windows from Java. In Linux I can use mkfifo (called using Runtime.exec()
), but how should I do this on Windows?
Use Named Pipes to Communicate Between Java and .Net Processes
Relevant part in the link
try {
// Connect to the pipe
RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\testpipe", "rw");
String echoText = "Hello word\n";
// write to pipe
pipe.write ( echoText.getBytes() );
// read response
String echoResponse = pipe.readLine();
System.out.println("Response: " + echoResponse );
pipe.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In windows, named pipes exist but they cannot be created as files in a writeable filesystem and there is no command line tool. They live in a special filesystem and can be created only by using the Win32 API.
Looks like you'll have to resort to native code, or switch from pipes to sockets for IPC - probably the best longterm solution, since it's much more portable.
You can create named pipe using JNA library https://github.com/java-native-access/jna
It is clearly shown in the following test: https://github.com/java-native-access/jna/blob/master/contrib/platform/test/com/sun/jna/platform/win32/Kernel32NamedPipeTest.java
API of JNA wrapper is the same as Win32 hence you will be able to use all the features and power of named pipes on Windows.
It is very much possible to read and write to an existing named pipe in Java. You cannot, to my knowledge, create a named pipe in a Windows environment. Linux is a different story as named pipes can be created and consumed like files.
Relevant link on interacting with an existing pipe: http://v01ver-howto.blogspot.com/2010/04/howto-use-named-pipes-to-communicate.html
maybe could use cygwin named pipes--if all your processes are cygwin.
来源:https://stackoverflow.com/questions/634564/how-to-open-a-windows-named-pipe-from-java