9

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?

Jonas
  • 121,568
  • 97
  • 310
  • 388
amit.bhayani
  • 508
  • 2
  • 5
  • 7
  • What is the connection to asterisk? – Joachim Sauer Oct 27 '09 at 16:46
  • Actually the /dev/zap/16 is created by Zaptel driver used for Asterisk when you have SS7 card installed on your machine. Asterisk has module that reads this pipe but is in native code. I am trying to get this working on Java. Out of topic but if any of you trying to install Asterisk + SS7 here is my experience http://amitbhayani.blogspot.com/2009/04/asterisk-ss7.html – amit.bhayani Oct 28 '09 at 02:02

3 Answers3

11

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
  • 35,575
  • 15
  • 95
  • 119
6

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
  • 302,674
  • 57
  • 556
  • 614
0

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
  • 85,954
  • 40
  • 175
  • 219