artem
artem

Reputation: 16777

How to listen for data in named pipe in Java/Kotlin in Linux?

I want to listen for a named pipe on Linux (and only Linux) using Kotlin or Java. Currently I do the following:

val reader = File(PIPE_NAME).bufferedReader()
while (true) {
  reader.readLine()?.let { string ->
  // Next actions
}

This approach works, however the downside is that if nothing is available at the moment, readLine will return null, so the loop will consume the CPU.

Adding sleep is not an option as it's critical to get data ASAP.

So, the question is — is it possible to somehow read lines from a named pipe only when they're available and block otherwise?

Upvotes: 0

Views: 462

Answers (1)

Andrey B. Panfilov
Andrey B. Panfilov

Reputation: 6073

If I understood properly, the problem starts when other side closes pipe, we may overcome that by opening pipe in rw mode:

try (RandomAccessFile raf = new RandomAccessFile(PIPE_NAME, "rw")) {
    String str;
    while ((str = raf.readLine()) != null) {
        System.out.println(str);
    }
}

in that case you will never get EOF since pipe is always open for write, thus the while loop never exits, however I do believe that is exactly what you want to achieve.

Another options is to reopen pipe after EOF, i.e.:

while (true) {
    try (BufferedReader reader = new BufferedReader(new FileReader(PIPE_NAME))) {
        String str;
        while ((str = reader.readLine()) != null) {
            System.out.println(str);
        }
    }
}

Upvotes: 1

Related Questions