views:

1360

answers:

4

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?

+3  A: 

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.

sfussenegger
Do you mean a normal `FileInputStream`? That's what I'd try first, too.
erickson
`FileInputStream` and `FileOutputStream` respectively, yes
sfussenegger
A: 

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.

Joachim Sauer
A: 

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

Anurag Uniyal
A: 

Hey thanks for answer. What we are trying to achieve it two way communciation, so two different java.io.File and two different streams would do. Thing is that for instance read operations take extremly long. See:

  • NIO - ~130ms (!)
  • regular IO ~30ms
  • Process.getInputStream - 1/60ms(!)

Where Process p = Runtime.exec("cat /dev/xxx/xx");

With Process data recevied is correct in 100%. Now it seems a bit odd that difference, is so huge between different stream implementation

baranowb