nio will not work, because when you create a process, you can only access the OutputStream, not the channel.
You can have 1 stream reading multiple InputStreams.
Sort of,
import java.io.InputStream; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; class MultiSwallower implements Runnable { private List<InputStream> streams = new CopyOnWriteArrayList<InputStream>(); public void addStream(InputStream s) { streams.add(s); } public void removeStream(InputStream s) { streams.remove(s); } public void run() { byte[] buffer = new byte[1024]; while(true) { boolean sleep = true; for(InputStream s : streams) {
You can associate the above class with another class that is waiting for processes to finish, something like
class ProcessWatcher implements Runnable { private MultiSwallower swallower = new MultiSwallower(); private ConcurrentMap<Process, InputStream> proceses = new ConcurrentHashMap<Process, InputStream>(); public ProcessWatcher() { } public void startThreads() { new Thread(this).start(); new Thread(swallower).start(); } public void addProcess(Process p) { swallower.add(p.getInputStream()); proceses.put(p, p.getInputStream()); } @Override public void run() { while(true) { for(Process p : proceses.keySet()) { try {
In addition, you do not need to have 1 stream for each error stream, if you use ProcessBuilder.redirectErrorStream (true) and you do not need 1 stream to read the process input stream, you can simply ignore the input if you are not writing anything.
source share