Sunday, May 12, 2013

Java writes to named pipe

I did while ago article where Java talks to C++ using standard input/output, now this is just addition to it. As in last example all that happens on Linux and we are using named pipe or FIFO. Need to transfer result of some periodic operation to remote listener and do not want to block process with network transfer. It slows it down and also introduces new opportunities for failure. In original problem that process is written in some funny functional language where many things may go wrong. Naturally I will not bother you with networking or what is being processed. It will be just small IPC example.
So here is C++ listener:


We run it the first, to create MYFIFO. BTW on Ubuntu 12.10 it will fail to compile, to remedy that add unistd.h to includes. Then comes Java class which is talking to C++ listener:


We run listener in terminal, then Orator class in different terminal and type short messages. When we hit enter message goes through pipe and appears in terminal. If you didn’t know how to turn string into byte array and write it to buffer now you know. Only tricky point is that you need to flush output stream to go through pipe, it’s all about plumbing.