qwc
qwc

Reputation: 343

How to detect if a windows named pipe has been closed?

I've got a third party program which puts data into a windows named pipe.

I access the pipe with

String pipename = "\\\\.\\pipe\\the_pipe";
RandomAccessFile pipe = new RandomAccessFile(pipename, "r");
DataInputStream input = new DataInputStream(Channels.newInputStream(pipe.getChannel()));

So sometimes someone gets the 'perfect' idea to close the third party program before my small data converting tool which of course closes the pipe. When that happens, my tool writes down the last message received million times into the resultfile and successfully fills every hdd up to the last byte within hours, because I am not able to check if the pipe has been closed.

Things I've tried:

// checking file descriptor and file channel
if(!(pipe.getFD().valid() && pipe.getChannel().isOpen())) {
  // quit
}

But both options do not trigger.

Is there a other way to access named pipes where such an information can be obtained? Or do I have overlooked something?

Upvotes: 0

Views: 1892

Answers (2)

user207421
user207421

Reputation: 310985

When that happens, my tool writes down the last message received million times into the resultfile

Only if your tool ignores EOFExceptions and -1 return values from read().

Upvotes: 1

brettw
brettw

Reputation: 11114

I would recommend looking at JNA to access the named pipe directly. Yes, you can detect the pipe closure if you use JNA.

I have done so in a project called NuProcess available on github.com. Particularly, look at the com.zaxxer.nuprocess.windows package. Look at the WindowsProcess.createPipes() method for setting up pipes (the code creates both ends, you only need one).

On the read side, NuProcess is using Windows IOCompletionPorts for asynchronous I/O (in ProcessCompletions.java), which may be overkill for what you need (or not). But once you get your feet wet setting up the pipes, you should be able to figure it out from there reading the Microsoft API docs.

Upvotes: 1

Related Questions