Skip to content

Instantly share code, notes, and snippets.

@jkschneider
Last active August 14, 2023 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkschneider/43713e0a5e0597f4f4604dbfe82a8478 to your computer and use it in GitHub Desktop.
Save jkschneider/43713e0a5e0597f4f4604dbfe82a8478 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
ExecutorService executorService = Executors.newSingleThreadExecutor();
System.out.println("Executing command: " + args[0]);
try {
Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", args[0]});
StringBuilder sb = new StringBuilder();
Runnable streamGobbler = new Runnable() {
@Override
public void run() {
new BufferedReader(new InputStreamReader(proc.getInputStream())).lines()
.forEach(sb::append);
new BufferedReader(new InputStreamReader(proc.getErrorStream())).lines()
.forEach(sb::append);
}
};
Future<?> future = executorService.submit(streamGobbler);
if (!proc.waitFor(30, TimeUnit.SECONDS)) {
throw new IOException("Execution timed out for command: " + args[0]);
}
future.get(10, TimeUnit.SECONDS);
if (proc.exitValue() != 0) {
throw new IOException(sb.toString());
}
System.out.println(sb.toString());
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new RuntimeException(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment