Reputation: 508
My query is on what is the best way to read / write to a linux Pipe in Java? I already am using the java.io.RandomAccessFile like
RandomAccessFile file = new RandomAccessFile("/dev/zap/16", "rw");
and then passing it to worker thread which reads it after every 2ms as
byte[] buffer = new byte[16];
file.read(buffer);
It does read it from Pipe, but I suspect that some bytes are overwritten. Do you know how linux (ubuntu) handles the buffer for pipe's?
Upvotes: 9
Views: 16883
Reputation: 88827
I think you may not be flushing after writing, so do OutputStream.flush() often and read may be a byte at time, at least to see if your data is getting thru. e.g. to start with open a named pipe in readonly mode(FileInputStream) in process1, open it in write mode(FileOutputStream ) in process2, so anything you write in process2 will be read in process1.
also read
http://www.tldp.org/LDP/lpg/node15.html
http://www.unixguide.net/unix/programming/2.10.5.shtml
http://www.unixguide.net/unix/programming/2.10.6.shtml
Upvotes: 0
Reputation: 308131
Pipes aren't handled in any way special by Java as far as I know. You simply open the file for writing and write to it.
You can't really "overwrite" anything in a pipe, since you can't seek in a pipe. For the same reason a RandomAccessFile
isn't the smartest choice to use (since a pipe is explicitely not a random access file). I'd suggest using a FileOutputStream
instead.
Also note that read()
is not guaranteed to read until the buffer is full! It can read a single byte as well and you need to check its return value and possibly loop to read the full buffer.
Upvotes: 6
Reputation: 36095
I haven't ever tried this myself but what your doing feels just wrong. Linux pipes are First in - First out (FIFO) by definition. Hence you should only be able to read bytes in the same order as you've written them - not randomly. I'd suggest to use a normal File
instead and it should work fine.
Upvotes: 11