Skip to content

Instantly share code, notes, and snippets.

@fge
Created February 22, 2015 14:21
Show Gist options
  • Save fge/48a8c2152629fe0c4f78 to your computer and use it in GitHub Desktop.
Save fge/48a8c2152629fe0c4f78 to your computer and use it in GitHub Desktop.
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public final class InheritStdinOutErr
implements Closeable
{
private static final ThreadFactory DEFAULT_THREAD_FACTORY
= Executors.defaultThreadFactory();
private static final ThreadFactory THREAD_FACTORY
= new ThreadFactory()
{
@Override
public Thread newThread(final Runnable r)
{
final Thread ret = DEFAULT_THREAD_FACTORY.newThread(r);
ret.setDaemon(true);
ret.setName(String.format("inheritio-%d", ret.getId()));
return ret;
}
};
// One thread for each of stdin, stdout, stderr
private final ExecutorService executor
= Executors.newFixedThreadPool(3, THREAD_FACTORY);
private final Process process;
private final OutputStream stdin;
private final InputStream stdout;
private final InputStream stderr;
public InheritStdinOutErr(final String... cmdline)
throws IOException
{
final ProcessBuilder pb = new ProcessBuilder(cmdline);
process = pb.start();
stdin = process.getOutputStream();
stdout = process.getInputStream();
stderr = process.getErrorStream();
}
public Process run()
{
final List<Runnable> runnables
= Arrays.asList(stdinPipe(), stdoutPipe(), stderrPipe());
for (final Runnable runnable: runnables)
executor.submit(runnable);
return process;
}
@Override
public void close()
throws IOException
{
executor.shutdownNow();
}
private Runnable stdinPipe()
{
return new Runnable()
{
@Override
public void run()
{
int c;
try {
while ((c = System.in.read()) != -1) {
stdin.write(c);
stdin.flush();
}
} catch (IOException ignored) {
}
}
};
}
private Runnable stdoutPipe()
{
return new Runnable()
{
@Override
public void run()
{
int c;
try {
while ((c = stdout.read()) != -1) {
System.out.write(c);
System.out.flush();
}
;
} catch (IOException ignored) {
}
}
};
}
private Runnable stderrPipe()
{
return new Runnable()
{
@Override
public void run()
{
int c;
try {
while ((c = stderr.read()) != -1) {
System.err.write(c);
System.err.flush();
}
} catch (IOException ignored) {
}
}
};
}
public static void main(final String... args)
throws IOException, InterruptedException
{
final InheritStdinOutErr test
= new InheritStdinOutErr("vim");
System.out.println(test.run().waitFor());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment