Search code examples
javanamed-pipes

Read continuously from a named pipe using Java


I am trying to read continuously from a named pipe using java. This question answers it for python/bash.

public class PipeProducer {
    private BufferedReader pipeReader;

public PipeProducer(String namedPipe) throws IOException {
    this.pipeReader = new BufferedReader(new FileReader(new File(namedPipe)));
} 

public void process() {
    while ((msg = this.pipeReader.readLine()) != null) {
          //Process
    }
}

public static void main(String args[]) throws JSONException,IOException {
       PipeProducer p = new PipeProducer("/tmp/testpipe");
       while(true) {
            p.process();              
            System.out.println("Encountered EOF");
            now = new Date();
            System.out.println("End : " + now);
        }       
}       

Questions

  1. What happens if there is no data from pipe for some time ?
  2. Can Reader object be reused when EOF is encountered ?
  3. Is EOF is sent by pipe only when it terminate and not otherwise ?
  4. Does pipe guarantees to be alive and working unless something really goes wrong ?

Environment is CentOS 6.7 with Java 7

This is tested and works fine but corner cases needs to be handled so that continuous operation is ensured.


Solution

    1. What happens if there is no data from pipe for some time ?

    The program blocks until there is data to read or until EOF is detected, just like a Reader connected to any other kind of file.

    1. Can Reader object be reused when EOF is encountered ?

    I wouldn't count on it. It would be safer to close the Reader and create a new one in that case.

    1. Is EOF is sent by pipe only when it terminate and not otherwise ?

    On Unix, EOF will be received from the pipe after it goes from having one writer to having zero, when no more data are available from it. I am uncertain whether Windows named pipe semantics differ in this regard, but since you're on Linux, that doesn't matter to you.

    1. Does pipe guarantees to be alive and working unless something really goes wrong ?

    If the named pipe in fact exists on the file system and you have sufficient permission, then you should reliably be able to open it for reading, but that may block until there is at least one writer. Other than that, I'm not sure what you mean.