in Android, you can create piped ProcessBuilder with fifo (named pipe) file
static File createTempFifo() throws IOException, ErrnoException {
File fifoFile = File.createTempFile("PipedProcessBuilders", ".fifo");
fifoFile.delete();
Os.mkfifo(fifoFile.getPath(), 0666);
return fifoFile;
}
static void safeClose(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
// ignore
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
static Process[] startPipelineProcessBuilder(ProcessBuilder... builders) throws IOException, ErrnoException {
final Process[] processes = new Process[builders.length];
final File[] fifoFiles = new File[builders.length - 1];
final RandomAccessFile[] randomAccessFiles = new RandomAccessFile[builders.length - 1];
try {
for (int i = 0; i < builders.length; i++) {
if (i < builders.length - 1) {
fifoFiles[i] = createTempFifo();
// because linux require the first opener must open the fifo with Read&Write permission
// otherwise the open method will block!
randomAccessFiles[i] = new RandomAccessFile(fifoFiles[i], "rw");
builders[i].redirectOutput(fifoFiles[i]);
}
if (i > 0) {
builders[i].redirectInput(fifoFiles[i - 1]);
}
processes[i] = builders[i].start();
}
} finally {
Arrays.stream(fifoFiles).filter(Objects::nonNull).forEach(File::delete);
Arrays.stream(randomAccessFiles).filter(Objects::nonNull).forEach(Client::safeClose);
}
return processes;
}
or use the anonymous pipe
static Process[] startPipelineProcessBuilder(ProcessBuilder... builders) throws IOException {
final Process[] processes = new Process[builders.length];
ParcelFileDescriptor[] newPipes = null, oldPipes = null;
for (int i = 0; i < processes.length; i++) {
if (i < processes.length - 1) {
newPipes = ParcelFileDescriptor.createPipe();
builders[i].redirectOutput(new File("/proc/self/fd/" + newPipes[1].getFd()));
}
if (i > 0) {
builders[i].redirectInput(new File("/proc/self/fd/" + oldPipes[0].getFd()));
}
processes[i] = builders[i].start();
if (i > 0) {
oldPipes[0].close();
oldPipes[1].close();
}
oldPipes = newPipes;
}
return processes;
}
test code
Process[] processes1 = startPipelineProcessBuilder(new ProcessBuilder("busybox", "seq", "1"));
try (BufferedReader reader = new BufferedReader(new InputStreamReader(processes1[processes1.length - 1].getInputStream()))) {
assertEquals("1", reader.readLine());
}
Process[] processes2 = startPipelineProcessBuilder(new ProcessBuilder("busybox", "seq", "10000"), new ProcessBuilder("wc", "-l"));
try (BufferedReader reader = new BufferedReader(new InputStreamReader(processes2[processes2.length - 1].getInputStream()))) {
assertEquals("10000", reader.readLine());
}
assertThrows(IOException.class, ()->{
startPipelineProcessBuilder(new ProcessBuilder("busybox","seq","10000"), new ProcessBuilder("not_exist_file"));
});